language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 6,146 | 2.59375 | 3 |
[] |
no_license
|
三十三
二十一
路易丝·德·绍利厄致勒内·德·莱斯托拉德
嫁了人的亲爱的小鹿,你这封信来得正好。它为我证明了一个大胆计划的正确性,对于这个计划,我已经酝酿了无数个日日夜夜。我心里产生了一种难以名状的欲望,想了解某些从未经历过、甚至被禁止知道的事,这种欲望使我时刻不得安宁。它也说明,社会法则和自然法则在我的头脑里正进行着一场战斗。我说不清楚,自然法则在我身上是否要比社会法则更加强大,然而,我惊讶地发现,我正在调和这两大力量。说得明白一点:我想找一个晚上,单独和费利普在花园尽头的菩提树下谈一个小时。公爵夫人曾笑着把我称作情窦初开的饶舌妇,这一说法还得到父亲的肯定。现在,我这种欲望倒是使我无愧于这一称号了。尽管如此,我还是认为,这种做法虽有不妥,但还是谨慎和明智的。我一方面要对费利普在墙脚下度过的无数夜晚给予报偿,另一方面我还想知道费利普先生对我这次举动有什么想法,以便及时对他作出判断;如果他把我的过失加以神化,我就让他做我的好丈夫;如果他一反在爱丽舍田园大道骑马兜风时那种恭顺小心的态度,我就再也不和他见面了。说到社交界么,与其在德·摩弗里纽斯夫人或者鲍赛昂老侯爵夫人家对我的情人频频微笑,不如这样和他见面,还可以少担一些风险。因为,在这些夫人家里,我们已经被间谍包围了;上帝知道,一个姑娘被怀疑钟情于玛居梅这样一头怪物,会招来多少异样的目光。啊!你可知道,我在酝酿这一计划的时候,心情是何等纷乱;为了使这个计划得以实现,我操了多少心哟!可惜你不在我身边,要不然我们可以谈上几个小时,或在一座座吉凶未卜的迷宫中寻找出路,或不论好歹,事先领略一下夜阑人静的时刻,在绍利厄公馆,在透过点点月光的美丽菩提树下初次幽会的滋味。我独自一人扪着跳动的心儿对自己说:
“勒内啊,你在哪儿?”就这样,你的来信无异是烈火碰上了干柴,烧掉了我仅余的一点踌躇。我终于向窗外那个惊愕不已的崇拜者抛出一封短信,信中附有一纸花园小门钥匙的精确图样。我写道:
有人要阻止你做出疯狂的举动。你在摔得头破血流的同时,将败坏你所爱的那个人的名声。当月光将花园尽头的菩提树置于阴影之中的时候,你值得人家这时来和你谈话,配得上这个新的敬重的表示吗?
昨晚深夜一时,正当格里菲思准备回房就寝时,我对她说:
“亲爱的,请戴上披巾,陪我出去走一走,我想到花园尽头去一下,但不想让旁人看见。”
她什么也没有说,当即跟着我走了。勒内,我怀着忧喜交集的心情等了他好一会儿,当我看到他象一个影子似的闪了过来时,真说不出那是什么滋味!顺利地来到花园以后,我对格里菲思说:
“请不必惊讶,那是玛居梅男爵,正是为了他,我才把你带到这儿来的。”
她还是一言不发。
“您叫我来有什么吩咐?”费利普的声音充满着激情;在夜阑人静的气氛中,我们衣裙的窸窣声,脚踩在沙子上的响声,尽管非常轻微,却已经使他不能自持了。
“有些事我无法写在信中,所以想当面和您谈谈。”我这样回答。
格里菲思走到六步以外等着。这是一个暖洋洋的夜晚,空气中弥漫着阵阵花香;现在,我几乎是单独和他置身于菩提树下恬静的阴影之中;树荫之外,府邸被月光照成白幽幽的一片,使花园更显得光熠熠的;此时此刻,我感到有一种醉人的快意。月光所造成的明暗对比为我俩的爱情增添了神秘的色彩,而这一爱情终将归结为盛大的婚礼。我们俩对于这一新奇的意境深感惊讶,同时又觉得十分愉快。这样过了一会,我才想起要说的话:
“虽然我不怕别人恶意中伤,我还是不能让您再爬这棵树,翻上这堵墙,”我指着榆树对他说,“我们俩一个象小学生,一个象寄宿学校的女孩子,这样的把戏应该玩够了。让我们把自己的感情升华到决定命运的高度吧。万一您跌下来摔死,我就是跟您死了也落个不清不白……”
我注视着他,他的脸色变得十分苍白。
“要是您被人发现,那么,我,或者我母亲将会受到怀疑……”
“请原谅。”他用微弱的声音说。
“以后可以在路上走走,我听得到您的脚步声,要是我想见您,我会打开窗子的;不过,我不想让您担这种风险,我自己也只有在事态严重时才会冒这个险。您为什么用冒冒失失的行为逼着我做出同样冒失的举动,从而使您对我作出不良的评价呢?”
我看到他眼眶里闪动着泪花,这实在是世界上最美好的回答了。
“您一定认为,”我含笑对他说,“我今天的举动是极为轻率的……”
我们默默地在树下踱了两圈,然后他开了腔:
“您一定认为我傻气十足;幸福使我那样的陶醉,以至于我一点力气和头脑都没有了;但至少请了解这一点:在我的心目中,您只是用自己所许可的办法使您的行为变得更加圣洁。我对您怀有的敬意只能与我对上帝的敬意相比。再说,格里菲思小姐也在这儿。”
“费利普,她在这儿是防别人,而不是防我们。”我急忙向他解释。
亲爱的,他明白了我的意思。
“我知道,”他用极为谦恭的目光看了我一眼,“即使她不在,我们之间发生的一切,也会象她看到我们时一样:如果我们面前没有别人,至少还有上帝,我们既需要得到社会的尊重,也需要自爱自重。”
|
Python
|
UTF-8
| 1,642 | 2.859375 | 3 |
[
"Apache-2.0"
] |
permissive
|
import sys
sys.path.append("../../src/")
from DEVS import *
import random
class Generator(AtomicDEVS):
def __init__(self, num, ta):
AtomicDEVS.__init__(self, "Generator" + str(num))
self.state = None
self.ta = ta
def timeAdvance(self):
return self.ta
class StaticModel(CoupledDEVS):
def __init__(self, size, actives):
CoupledDEVS.__init__(self, "Root")
random.seed(1)
tas = [round(random.random(), 3) for _ in range(int(size/actives+1))]
ta_counter = 0
for i in range(size):
self.addSubModel(Generator(i, tas[0]))
if ta_counter >= actives:
ta_counter = 0
tas.pop(0)
else:
ta_counter += 1
class DynamicGenerator(AtomicDEVS):
def __init__(self, num, nexttype):
AtomicDEVS.__init__(self, "Generator" + str(num))
self.state = (nexttype, True, round(random.uniform(4.00, 6.00), 4))
self.nexttype = nexttype
def intTransition(self):
if self.state[0] - self.timeAdvance() <= 0:
return (self.nexttype, not self.state[1], self.state[2])
else:
return (self.state[0] - self.timeAdvance(), self.state[1], self.state[2])
def timeAdvance(self):
if self.state[1]:
return min(1.0, self.state[0])
else:
return min(self.state[2], self.state[0])
class DynamicModel(CoupledDEVS):
def __init__(self, size):
CoupledDEVS.__init__(self, "Root")
random.seed(1)
for i in range(size):
self.addSubModel(DynamicGenerator(i, 2000))
|
Python
|
UTF-8
| 274 | 3.953125 | 4 |
[] |
no_license
|
x1=float(input("Enter Value: "))
x2=str(input("Enter unit A(Feet) or B(Inches): "))
if x2!="A" and x2 != "B" :
print("Error")
elif x2=="A":
print( "the Value in Centimeter is: " + str(x1*30.28))
elif x2=="B":
print( "the Value in Centimeter is: " + str(x1*2.54))
|
Markdown
|
UTF-8
| 6,353 | 2.8125 | 3 |
[] |
no_license
|
MEGA65 Extended BASIC
-------------------
This extended BASIC is intended as a starting point, not a finished product.
For convenience, I have created it by extending the relatively simple starting point
that is the C64's BASIC 2. It would of course be better to extend BASIC 7 or BASIC 10,
but for now this is what we have.
The purpose of this extended BASIC more specifically is to provide a convenient testbed
for the 256-colour text mode graphics and 16-colour sprite capabilities of the MEGA65.
But more than just being a tool for the development team, it is intended to be easy and
fun for end users to create their own programs with.
Considerable effort is being put into making the syntax as human readable as possible,
compared with the very terse syntax of BASIC 7 and BASIC 10.
Command reference
-------------
* FAST - Set CPU to full speed
* SLOW - Disable MEGA65 fast CPU (C128 style and C65 style 2MHz and 3.5MHz selection is unaffected)
* COLOUR TEXT <0-255> - Select text foreground colour (16 colours only). Upper 4 bits are VIC-III extended attributes (this command might get extended to allow easier setting of attributes. 16 = BLINK, 128 = UNDERLINE, 32 = REVERSE, 64 = BOLD (selects colours 32-47 instead of colours 0 - 15).
* COLOUR BORDER <0-255> - Set border colour
* COLOUR SCREEN <0-255> - Set screen background colour
* COLOUR SPRITE <sprite number> COLOUR <colour index in sprite>> = <0-255>,<0-255>,<0-255> - Set the R,G,B values of a sprite colour
* TILE SET LOAD <"filename"> [, device] - Load a set of tiles and pre-prepared canvases from the specified device. These load into the graphics memory, leaving the full 38911 program bytes free. Loading a tile set replaces any existing tile set and canvases. Any currently displayed graphics will be disabled before loading, to prevent screen glitches. Loading a tile set also loads the associated palette.
* CANVAS <0-255> <NEW <width>,<height>> - Create a new canvas with the specified ID. Canvases are rectangular arrangements of tiles. A FILE EXISTS ERROR will be generated if the canvas already exists.
* CANVAS <0-255> DELETE - Delete the specified canvas. Canvas 0 is special, and cannot be deleted.
* CANVAS <0-255> CLR [FROM <x1>,<y1> TO <x2>,<y2>] - Erase the contents of the specifed canvas, filling it with tile number 0.
* CANVAS <0-255> STAMP [FROM <x1>,<y1> TO <x2,y2>] ON CANVAS <0-255> [AT <x>,<y>]> - Copy the whole or part of one canvas onto the whole or part of another canvas. This is a very versatile command, and can be used to display a canvas (by STAMPing it onto canvas 0, the display canvas), or to compose scenes using various elements. Because tile number 0 is transparent, such compositions can use complex shaped objects, the only limitation being that the objects consist of 8x8 tiles, i.e., you can't select pixels to be part of a composition with finer than 8x8 granularity (this may be relaxed in a future version through the use of a transparent colour and complex tile compositing algorithms, but such composing of tiles together will require the creation of additional tiles with the combined data, thus increasing memory usage.)
* CANVAS <0-255> SET TILE <x>,<y> = <tile number> - Set the specified tile on the specified canvas to display the specified tile number. Tile number 0 is reserved as the "transparent tile", i.e., tile zero will not STAMP over an existing tile in another canvas, and will show the screen colour behind.
Memory Layout
------------
For now, the memory layout is a bit sub-optimal, because the C65 DOS sits in BANK 1, meaning we have only 56KB free there
(in fact 54KB, because the last 2KB are colour RAM).
We also need to have screen RAM for the current screen. We use this to take over the BASIC screen, so that tiles and text
can happily coexist. A raster IRQ reads the C64 screen (at 50MHz) and composes this onto the contents of CANVAS 0, to
produce the actual display screen. Any character on the BASIC screen at $0400 that is not a space will overwrite the
tile otherwise being displayed at that screen position.
We allow enough space in CANVAS 0 for an 80x50 screen, thus requiring 80 x 50 x 2 bytes = 8000 bytes. We hide that under
the C64 KERNAL. Because of the compositing of the BASIC screen on this, we need another 8000 bytes, which we hide under
the C64 BASIC ROM. This buffering of screen 0 is required so that you can freely type and clear the BASIC screen, and
the tile-based graphics screen from behind will update magically. This makes programs MUCH easier to write and debug.
You can even POKE to $0400, and thanks to the raster interrupt, the changes will magically appear on the next frame.
There will eventually be an option to tell BASIC that the screen is bigger, so that 80 column and 50 rows of text in
BASIC become possible. The cost will simply be the loss of 3000 bytes of BASIC program space.
8000 bytes of colour RAM are also required to be reserved for CANVAS 0's off-screen buffer, and also the on-screen buffer.
These are at $0800 and $2800 in the colour RAM, leaving from $4800-$7FFF in colour RAM free. It would be nice to make that
14KB available for storing other CANVASes, to effectively increase the available graphics memory.
The video mode will be set to use a virtual row length of 80, regardless of 40 or 80 column mode, so that it is possible to
switch between the two freely. For the memory frugal, it is of course possible to STAMP into and out of the off-display
portions of CANVAS 0, thus reducing the effective overhead. Thus the 8000 bytes of CANVAS 0 are in effect in addition to
the headline 54KB of graphics memory. Similarly, the use of the 32KB colour RAM is not counted.
In summary, the VIC-IV will be set to show:
* 40x25 - 80x50 screen, with screen RAM at $A000-$BFFF, colour RAM at $FF80800-$FF827FF.
* virtual row length = 80 characters.
* 16-bit colour mode enabled.
* multi-colour mode off.
And the raster interrupt will read from $E000-$FFFF, $FF82800-$FF847FF and $0400-$07E7 to dynamically generate
the screen and colour RAM data at $A000 and $FF80800. This will be done by first copying the CANVAS 0 contents,
and then stepping through the C64 screen, and for characters that are not space, copy the screen and colour RAM
contents to the correct address in the VIC-IV screen and colour RAM at $A000 and $FF80800.
|
Java
|
UTF-8
| 243 | 2.515625 | 3 |
[] |
no_license
|
package Model;
/**
*
* @author dvandenberge
*/
public class CircleAreaService {
public double getArea(String r){
double rad=r!=null?Double.parseDouble(r):0;
return Math.PI*Math.pow(rad,2);
}
}
|
Markdown
|
UTF-8
| 6,346 | 3.109375 | 3 |
[
"MIT"
] |
permissive
|
---
date: "1"
---
# ENS Domains
You can easily point an [Ethereum Name Service](https://ens.domains/) (ENS) domain to your **IPFS site** and have the content automatically update for future deployments. The benefit of ENS domains is that they are decentralized and trustless, running on the Ethereum blockchain network through smart contracts.
It's important to note that, for a user to **resolve/visit an ENS domain** they will need to have a compatible provider/browser installed that is able to resolve them. **Using the MetaMask browser extension is one option**, as it resolves .eth domains.
**Need help with an ENS domain?** Visit the [ENS troubleshooting section](https://docs.fleek.co/domain-management/troubleshooting/#troubleshooting-ens-domains).
!!! info
Ethereum Name Service (ENS) domains are only compatible with IPFS sites at the moment. We are exploring ways to bring ENS to Internet Computer hosted sites in the future!
### Deploying
Once your app is deployed on Fleek, go to the settings page in the left-hand bar menu and click `Domain Management`. Scrolling a bit would land you on the section that says `ENS`

### Adding ENS Domain
Click Add ENS to add your ENS domain. Input your domain to verify it and add it. If the domain does not belong to anyone you will be redirected to the [ENS Dashboard](https://app.ens.domains) to buy it.
!!! note
Your domain will appear in the settings page and can also be deleted from there.

### Set the Content Hash
Once you add your first ENS domain, you will need to SET THE CONTENT hash. This means you will set the IPNS address that references your site on Fleek, and that Fleek will update periodically upon each deployment to keep your sites' content up to date. **Click set content hash to begin the process**

You need to trigger one transaction through an Ethereum Web3 provider, such as [Metamask](https://metamask.io/). If using Metamask, a popup will appear asking to connect.
!!! info
Important: If when you click 'set content hash', you see a prompt to "Migrate your ENS domain" there is an extra step you need to do before you continue. See the 'Migrate Your ENS Resolver' section below.
This transaction sets the initial content hash / IPNS address that Fleek will automatically update on your ENS domain upon each deployment to refresh the content to the latest commit.

**Previously, when Fleek didn't use IPNS**, Fleek was set as the controller of the ENS domain to modify the IPFS content hash manually each time. Now, using IPNS, that is not necessary and only one transaction is needed.
**Once you approve the transaction**, on the Settings section, the domain will show that the Ethereum transaction is pending confirmation. **Upon confirmation** the ENS domain will have been successfully added to Fleek. Hooray!
### Migrate Your ENS Resolver
If when you begin the "Set the Content Hash Flow", you find yourself viewing a **different screen, that tells you you need to "Migrate Your ENS"**, it means you need to migrate your ENS domain's resolver to be able to use that domain with Fleek.

!!! info
Why does this happen? The resolver is the "service" your ENS domain name uses so that when someone visits the domain, it translates the request to the addresses/URLs/content that your ENS name represents. Resolvers are Smart Contracts on Ethereum, and there are many of them to choose from, thereforee they are set as a record in your ENS domain nam where the address of said contract is specified. Usually, when you create a new ENS domain name, a default, public resolver is set.
**If your ENS domain name is configured using a legacy, or outdated resolver** you won't be able to access your site since resolving won't work properly.
**To migrate your domain: Click the Migrate button on the window seen above** and the Ethereum Name Service Application will open, on your domain's details page.

**In the RESOLVER section, click the SET button** to open up the window that will help you reconfigure your ENS domain resolver. **Click the 'USE PUBLIC RESOLVER' option to have ENS auto-fill with a public, up-to-date, resolver**. Alternatively, you can use a custom one if you now the proper address.

**Hit SAVE** and you will prompt a transaction on the ENS application that you will need to confirm with any compatible wallet, like MetaMask, paying the associated gas fee for the transaction that sets the record.

**When the transaction is confirmed**, go back to the Fleek application and your site's domain management page. You will see that if you reopen the 'SET CONTENT HASH' window, the migration will be registered and you can continue with the flow normally following the steps above.

### Review Your ENS Site with eth.link, ens.limo, MetaMask, or Other Options.
If you’re using an ENS-compatible browser, like [Brave](https://brave.com/), or if you have the [MetaMask](https://metamask.io/) extension installed like in the GIF above, you can just type your address in the search bar “address.eth/” (don’t forget the “/”) and it should be automatically resolved: fleekhq.eth/
**Using eth.link**
If you have none of those, you can always append the “.link” suffix after your domain to visit your IPFS+ENS website on any browser, thanks to a service made available by ENS and Cloudflare that makes all the .eth domains accessible via traditional DNS addresses. Anyone can visit and resolve your site. [Visit the ENS app with .link!](http://ens.eth.link/)
**Using eth.limo**
An alternative to eth.link is eth.limo! It's a decentralized option (Cloudflare's eth.link is centralized and can experience downtimes) that was created so that there is not only one Web2 gateway to IPFS+ENS sites. As easy as .eth.link. You just add .limo at the end of your ENS name. EG, http://ens.eth.limo/
**All of these are third-party resolving options** you, or anyone, can use to visit your site using .eth ENS domains. Be aware that these are non-Fleek platforms. If your ENS record is configured properly, and you experience an issue on any of these gateways, contact that specific provider.
|
C#
|
UTF-8
| 8,518 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Collections.ObjectModel;
#region title
#endregion
namespace LgdLogo
{
using LgdLogo.ExtensionMethod;
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class LogoFile
{
public FileHeader Header = new FileHeader();
public List<LogoData> LogoData = new List<LogoData>();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class FileHeader
{
//constはlgdファイルに保存されない。
public const string Str_v1 = "<logo data file ver0.1>";
public const string Str_v2 = "<logo data file ver0.2>";
public const int Str_FixSize = 28;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = Str_FixSize)]
public string Str;
//LogoNumはビッグエンディアンで格納されている。
private int _logonum;
public int LogoNum
{
// get little
get { return System.Net.IPAddress.NetworkToHostOrder(_logonum); }
// set big
set { _logonum = System.Net.IPAddress.HostToNetworkOrder(value); }
}
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class LogoData
{
public DataHeader Header;
public List<LOGO_PIXEL> Pixels = new List<LOGO_PIXEL>();
//Imageはファイルに保存しない
private Bitmap _image;
public Bitmap Image
{
get
{
_image = _image ?? this.GetBitmap();
return _image;
}
}
}
public interface IDataHeader
{
void SetFromLatestVer(DataHeader header_latest);
DataHeader ToLatestVer();
void Validate();
}
public class DataHeader : DataHeader_v2
{
// implement nothing
// inherit latest DataHeader
// publish to external class
}
#region DataHeader_v1
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class DataHeader_v1 : IDataHeader
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string Name; //終端の\0も含めて32byte
public Int16 X, Y; /* ロゴの位置 */
public Int16 Height, Width; /* ロゴの高さ・幅 */
public Int16 FadeIn, FadeOut; /* デフォルトのFadeIn/Out */
public Int16 Start, End; /* デフォルトの開始・終了 */
public DataHeader_v1() { }
public DataHeader_v1(DataHeader header_latest)
{
SetFromLatestVer(header_latest);
}
/// <summary>
/// Latest --> v1
/// </summary>
public void SetFromLatestVer(DataHeader header_latest)
{
this.Name = header_latest.Name;
this.X = header_latest.X;
this.Y = header_latest.Y;
this.Height = header_latest.Height;
this.Width = header_latest.Width;
this.FadeIn = header_latest.FadeIn;
this.FadeOut = header_latest.FadeOut;
this.Start = header_latest.Start;
this.End = header_latest.End;
Validate();
}
/// <summary>
/// v1 --> Latest
/// </summary>
public DataHeader ToLatestVer()
{
var header_latest = new DataHeader();
header_latest.Name = this.Name;
header_latest.X = this.X;
header_latest.Y = this.Y;
header_latest.Height = this.Height;
header_latest.Width = this.Width;
header_latest.FadeIn = this.FadeIn;
header_latest.FadeOut = this.FadeOut;
header_latest.Start = this.Start;
header_latest.End = this.End;
header_latest.Reserved = null;
header_latest.Validate();
return header_latest;
}
/// <summary>
/// Nameのサイズを32byte以下に
/// </summary>
public void Validate()
{
Name = StrUtility.TrimSize(Name, 32);
}
}
#endregion
#region DataHeader_v2
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class DataHeader_v2 : IDataHeader
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string Name; //終端の\0も含めて256byte
public Int16 X, Y; /* ロゴの位置 */
public Int16 Height, Width; /* ロゴの高さ・幅 */
public Int16 FadeIn, FadeOut; /* デフォルトのFadeIn/Out */
public Int16 Start, End; /* デフォルトの開始・終了 */
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 240)]
public Byte[] Reserved;
public DataHeader_v2() { }
public DataHeader_v2(DataHeader header_latest)
{
SetFromLatestVer(header_latest);
}
/// <summary>
/// Latest --> v2
/// </summary>
public void SetFromLatestVer(DataHeader header_latest)
{
this.Name = header_latest.Name;
this.X = header_latest.X;
this.Y = header_latest.Y;
this.Height = header_latest.Height;
this.Width = header_latest.Width;
this.FadeIn = header_latest.FadeIn;
this.FadeOut = header_latest.FadeOut;
this.Start = header_latest.Start;
this.End = header_latest.End;
this.Reserved = header_latest.Reserved;
Validate();
}
/// <summary>
/// v2 --> Latest
/// </summary>
public DataHeader ToLatestVer()
{
var header_latest = new DataHeader();
header_latest.Name = this.Name;
header_latest.X = this.X;
header_latest.Y = this.Y;
header_latest.Height = this.Height;
header_latest.Width = this.Width;
header_latest.FadeIn = this.FadeIn;
header_latest.FadeOut = this.FadeOut;
header_latest.Start = this.Start;
header_latest.End = this.End;
header_latest.Reserved = this.Reserved;
header_latest.Validate();
return header_latest;
}
/// <summary>
/// Nameのサイズを256byte以下に
/// </summary>
public void Validate()
{
Name = StrUtility.TrimSize(Name, 256);
}
}
#endregion
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class LOGO_PIXEL
{
public const int LOGO_MAX_OPACITY = 1000;
public Int16 Op__Y_; /* 不透明度(輝度) */
public Int16 Clr_Y_; /* 輝度 0~4096 */
public Int16 Op__Cb; /* 不透明度(青) */
public Int16 Clr_Cb; /* 色差(青) -2048~2048 */
public Int16 Op__Cr; /* 不透明度(赤) */
public Int16 Clr_Cr; /* 色差(赤) -2048~2048 */
}
/// <summary>
/// Preset Color
/// </summary>
public static class Preset_LOGO_PIXEL
{
public static LOGO_PIXEL Red { get { return Rgb255_to_LogoPixel(new Byte[] { 255, 0, 0 }); } }
public static LOGO_PIXEL Green { get { return Rgb255_to_LogoPixel(new Byte[] { 0, 255, 0 }); } }
public static LOGO_PIXEL Blue { get { return Rgb255_to_LogoPixel(new Byte[] { 0, 0, 255 }); } }
public static LOGO_PIXEL Gray { get { return Rgb255_to_LogoPixel(new Byte[] { 200, 200, 200 }); } }
public static LOGO_PIXEL Black { get { return Rgb255_to_LogoPixel(new Byte[] { 0, 0, 0 }); } }
private static LOGO_PIXEL Rgb255_to_LogoPixel(Byte[] rgb)
{
Byte[] bgr = ColorConv.Swap_RGB_to_BGR(rgb);
Int16[] yc48 = YC48Conv.BGR_to_YC48(new double[] { bgr[0], bgr[1], bgr[2] });
var logo_pixel = new LOGO_PIXEL()
{
Op__Y_ = LOGO_PIXEL.LOGO_MAX_OPACITY,
Clr_Y_ = yc48[0],
Op__Cb = LOGO_PIXEL.LOGO_MAX_OPACITY,
Clr_Cb = yc48[1],
Op__Cr = LOGO_PIXEL.LOGO_MAX_OPACITY,
Clr_Cr = yc48[2],
};
return logo_pixel;
}
}
static class StrUtility
{
/// <summary>
/// 文字列をbyteSize以内に切り詰める。 Shift_JIS
/// </summary>
/// <param name="byteSize">文字列+'\0' のバイトサイズ</param>
public static string TrimSize(string str, int byteSize)
{
if (byteSize <= 1) throw new ArgumentException("byteSizeは2以上にしてください。");
var enc = Encoding.GetEncoding("Shift_JIS");
string trimmed = str;
while (true)
{
int curSize = enc.GetByteCount(trimmed + '\0');
int trimSize = curSize - byteSize;
if (0 < trimSize)
{
//後ろの1文字カット
// カットする文字が全角、半角かはわからない。
trimmed = trimmed.Substring(0, trimmed.Length - 1);
}
else
break;
}
return trimmed;
}
}
}
|
C#
|
UTF-8
| 525 | 2.796875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Dora.Caching
{
public static class CacheExtensions
{
public static async Task<T> GetValueAsync<T>(this ICache cache, string key, T defaultValue = default(T))
{
Guard.ArgumentNotNull(cache, nameof(cache));
Guard.ArgumentNotNullOrWhiteSpace(key, nameof(key));
var cacheValue = await cache.GetAsync(key);
return cacheValue.Exists ? (T)cacheValue.Value : defaultValue;
}
}
}
|
PHP
|
UTF-8
| 11,859 | 2.765625 | 3 |
[] |
no_license
|
<!DOCTYPE html>
<html lang="en" >
<?php
include 'header.php';
include 'common/common.php';
?>
<head>
<title>Schedule Administration</title>
</head>
<body>
<?php include 'navStart.php'; ?>
<div class="container">
<h2>Schedule Administration</h2>
<?php
function formatMonthlySchedule($scheduleData) {
$output = array();
foreach ($scheduleData as $obj) {
if (!isset($output[$obj->siteID])) {
$output[$obj->siteID] = array();
}
if (!isset($output[$obj->siteID][$obj->shifts])) {
$output[$obj->siteID][$obj->shifts]= array();
}
if (!isset($output[$obj->siteID][$obj->shifts][$obj->day])) {
$output[$obj->siteID][$obj->shifts][$obj->day] = array();
}
array_push($output[$obj->siteID][$obj->shifts][$obj->day], $obj->employeeID);
}
return $output;
}
if (isset($_GET['month']) && isset($_GET['year'])) {
$month = $_GET['month'];
$year = $_GET['year'];
} else {
$month = intval(date('m'));
$year = intval(date('yy'));
}
$currentMonth = intval(date('m'));
$currentYear = intval(date('yy'));
?>
<hr>
<span>Month: </span>
<input type="number" min="1" max="12" step="1" id='generateMonth' value=<?php echo $currentMonth; ?>>
<span>Year: </span>
<input type="number" min="2019" max="2050" step="1" id='generateYear'value=<?php echo $currentYear; ?>>
<button class="btn btn-sm btn-dark" id="generateSchedule">Generate Schedule</button>
<hr>
<form action="scheduleAdministration.php" method="get">
<span>Month: </span>
<input type="number" min="1" max="12" step="1" id='month' name='month' value=<?php echo $month; ?>>
<span>Year: </span>
<input type="number" min="2019" max="2050" step="1" id='year' name='year' value=<?php echo $year; ?>>
<button type="submit" class="btn btn-sm btn-dark">Show</button>
</form>
<br>
<button type="button" class="btn btn-sm btn-dark" data-toggle="modal" data-target="#add"> Add Site </button>
<button type="button" class="btn btn-sm btn-dark" data-toggle="modal" data-target="#remove"> Remove Site </button>
<br>
<br>
<table id="myTable" class="table table-striped table-bordered w-100">
<?php
// Extracting necessary data and formatting into desired form
$sql = "SELECT Year, Month, Day, Site_ID, Shift, schedule.Employee_ID, First_Name, Last_Name, Project_Name from schedule
inner join (select Employee_ID, First_Name, Last_Name from emp_basic_information) as emp on schedule.Employee_ID = emp.Employee_ID
inner join (select Project_ID, Project_Name from site) as site_temp on site_temp.Project_ID = schedule.Site_ID
where schedule.Month=:month and schedule.Year=:year";
$connMgr = new connectionManager();
$conn = $connMgr->getConnection();
$stmt = $conn->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->bindParam(':month', $month, PDO::PARAM_INT);
$stmt->bindParam(':year', $year, PDO::PARAM_INT);
$stmt->execute();
$result = array();
$nameArr = array();
$siteArr = array();
$uniqueDays = array();
$noOfDays = 0;
while ($row = $stmt->fetch()) {
$result[] = new schedule($row['Year'], $row['Month'], $row['Day'], $row['Site_ID'], $row['Shift'], $row['Employee_ID']);
if (!isset($nameArr[$row['Employee_ID']])) {
$nameArr[$row['Employee_ID']] = $row['First_Name'] . " " . $row['Last_Name'];
}
if (!isset($siteArr[$row['Site_ID']])) {
$siteArr[$row['Site_ID']] = $row['Project_Name'];
}
if (!in_array($row['Day'], $uniqueDays)) {
array_push($uniqueDays, $row['Day']);
$noOfDays++;
}
}
$formattedSchedule = formatMonthlySchedule($result);
$sql = "SELECT Employee_ID, First_Name, Last_Name, Identification_No from emp_basic_information";
$stmt = $conn->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->bindParam(':month', $month, PDO::PARAM_INT);
$stmt->bindParam(':year', $year, PDO::PARAM_INT);
$stmt->execute();
$employeeList = array();
while ($row = $stmt->fetch()) {
array_push($employeeList, array($row['Employee_ID'], $row['First_Name'], $row['Last_Name'], $row['Identification_No']));
}
// Setting headers of the table
echo "<thead class='thead-dark'>";
echo "<th>Location/Day</th>";
echo "<th>Shift</th>";
for ($daysHeader = 1; $daysHeader <= $noOfDays; $daysHeader++) {
echo "<th>$daysHeader</th>";
}
echo "</thead>";
// Setting body of the table
echo "<tbody>";
foreach ($formattedSchedule as $site => $siteDetails) {
foreach ($siteDetails as $shift => $shiftDetails) {
echo "<tr>";
$siteName = $siteArr[$site];
echo "<td>$siteName</td>";
echo "<td>$shift</td>";
for ($day=1; $day<=count($shiftDetails); $day++) {
echo "<td>";
foreach ($shiftDetails[$day] as $empID) {
echo "<select class='selectEmp'>";
foreach ($employeeList as $employee) {
$id = $employee[0];
$display = $employee[1] . " " . $employee[2] . " (" . $employee[3] . ")";
if ($id == $empID) {
echo "<option value='$id|$year|$month|$day|$site|$shift' selected>$display</option>";
} else {
echo "<option value='$id|$year|$month|$day|$site|$shift' >$display</option>";
}
}
echo "</select>";
}
echo "</td>";
}
echo "</tr>";
}
}
echo "</tbody>";
?>
</table>
<!-- Add Modal -->
<div class="modal fade" id="add" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addModalLabel">Add Site</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<?php
$sql = "SELECT Project_ID, Project_Name from Site where Project_ID not in (select distinct(Site_ID) from schedule where year=$year and month=$month)";
$stmt = $conn->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
$empty = true;
$options = "";
while($row = $stmt->fetch()) {
$projectID = $row['Project_ID'];
$projectName = $row['Project_Name'];
$options .= "<option value='$projectID'>$projectName</option>";
$empty = false;
}
if ($empty) {
echo "All sites are present already.";
} else {
echo "<select id='toAdd' class='d-block mx-auto'>";
echo $options;
echo "</select>";
}
?>
</div>
<div class="modal-footer">
<?php
if (!$empty) {
echo "<button type='button' class='btn btn-success' id='addButton'>Add</button>";
}
?>
<button type="button" class="btn btn-dark" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Remove Modal -->
<div class="modal fade" id="remove" tabindex="-1" role="dialog" aria-labelledby="removeModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="removeModalLabel">Remove Site</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<?php
$sql = "SELECT distinct(Site_ID), Project_Name from schedule inner join Site on schedule.Site_ID = Site.Project_ID where year=$year and month=$month";
$stmt = $conn->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
$empty = true;
$options = "";
while($row = $stmt->fetch()) {
$projectID = $row['Site_ID'];
$projectName = $row['Project_Name'];
$options .= "<option value='$projectID'>$projectName</option>";
$empty = false;
}
if ($empty) {
echo "Schedule is not generated yet";
} else {
echo "<select id='toRemove' class='d-block mx-auto'>";
echo $options;
echo "</select>";
}
?>
</div>
<div class="modal-footer">
<?php
if (!$empty) {
echo "<button type='button' class='btn btn-success' id='removeButton'>Remove</button>";
}
?>
<button type="button" class="btn btn-dark" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script src="js/scheduleAdministration.js"></script>
</div>
<?php include 'navEnd.php'; ?>
</body>
</html>
|
C#
|
UTF-8
| 1,900 | 2.515625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using Server;
namespace Server.Mobiles
{
public class Cobbler : BaseVendor
{
private List<SBInfo> m_SBInfos = new List<SBInfo>();
protected override List<SBInfo> SBInfos{ get { return m_SBInfos; } }
[Constructable]
public Cobbler()
: base("Cordonnier")
{
SetSkill( SkillName.Couture, 60.0, 83.0 );
}
public override void InitSBInfo()
{
m_SBInfos.Clear();
//switch (races)
//{
// case Race.Aasimar: m_SBInfos.Add(new SBCobbler()); break;
// case Race.Elfe: m_SBInfos.Add(new SBCobblerElfe()); break;
// case Race.ElfeNoir: m_SBInfos.Add(new SBCobblerDrow()); break;
// case Race.Capiceen: m_SBInfos.Add(new SBCobbler()); break;
// case Race.Nain: m_SBInfos.Add(new SBCobblerNain()); break;
// case Race.Nomade: m_SBInfos.Add(new SBCobblerNomade()); break;
// case Race.Nordique: m_SBInfos.Add(new SBCobblerNordique()); break;
// case Race.Orcish: m_SBInfos.Add(new SBCobblerOrcish()); break;
// case Race.Tieffelin: m_SBInfos.Add(new SBCobblerTieffelin()); break;
// default: m_SBInfos.Add(new SBCobbler()); break;
//}
//m_SBInfos.Add( new SBCobbler() );
}
public override VendorShoeType ShoeType
{
get{ return Utility.RandomBool() ? VendorShoeType.Sandals : VendorShoeType.Shoes; }
}
public Cobbler( Serial serial ) : base( serial )
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
}
|
Java
|
UTF-8
| 3,282 | 2.3125 | 2 |
[] |
no_license
|
package fr.aumjaud.antoine.services.synology.chatbot.service;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.junit.Test;
import fr.aumjaud.antoine.services.common.security.WrongRequestException;
import fr.aumjaud.antoine.services.synology.chatbot.model.TravisPayload;
import fr.aumjaud.antoine.services.synology.chatbot.model.TravisRepository;
public class TravisServiceTest {
private TravisService travisService = new TravisService();
@Test
public void getTravisPayload_should_parse_an_docker_webhook_info() throws IOException, URISyntaxException {
// Given
String msg = new String(Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource("travis_webhook.json").toURI())));
// When
TravisPayload dpd = travisService.extractTravisPayload(msg);
// Then
assertNotNull(dpd.getRepository());
assertEquals("minimal", dpd.getRepository().getName());
assertEquals("https://travis-ci.org/svenfuchs/minimal/builds/1", dpd.getBuildUrl());
assertEquals("the commit message", dpd.getMessage());
assertEquals(0, dpd.getStatus());
assertEquals("Passed", dpd.getStatusMessage());
assertEquals("Sven Fuchs", dpd.getAuthorName());
}
@Test
public void getTravisPayload_should_return_a_success_message_is_payoff_says_it_is_a_sucess()
throws IOException, URISyntaxException {
// Given
TravisPayload payload = new TravisPayload() {
public String getMessage() { return "commit message"; };
public TravisRepository getRepository() {
return new TravisRepository() {
public String getName() { return "repo_name"; };
};
}
public String getAuthorName() { return "aa"; };
public int getStatus() { return 0;};
public String getStatusMessage() { return "status";};
public String getBuildUrl() { return "http://repo_url";};
};
// When
String msg = travisService.buildTravisMessage(payload);
// Then
assertEquals("Build success of repo_name", msg);
}
@Test
public void getTravisPayload_should_return_a_failed_message_is_payoff_says_it_is_a_failed()
throws IOException, URISyntaxException {
// Given
TravisPayload payload = new TravisPayload() {
public String getMessage() { return "commit message"; };
public TravisRepository getRepository() {
return new TravisRepository() {
public String getName() { return "repo_name"; };
};
}
public String getAuthorName() { return "aa"; };
public int getStatus() { return 1;};
public String getStatusMessage() { return "status";};
public String getBuildUrl() { return "http://repo_url";};
};
// When
String msg = travisService.buildTravisMessage(payload);
// Then
assertEquals("Build <http://repo_url|status> of repo_name: [aa] commit message", msg);
}
@Test(expected = WrongRequestException.class)
public void getTravisPayload_should_throw_an_exception_if_missing_values_in_payoff()
throws IOException, URISyntaxException {
// Given
TravisPayload payload = new TravisPayload();
// When
travisService.buildTravisMessage(payload);
// Then
fail("should has thrown an exception");
}
}
|
TypeScript
|
UTF-8
| 4,515 | 2.828125 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
import { Option, Some, None } from 'space-lift';
import { Effect } from '../effects/Effect';
import { LogEvent } from '../logging/LogEvent';
import clone = require("clone");
import { CanvasState } from "../effects/CanvasState";
export class Scope {
private _varBindings: Map<string, Option<any>>;
private _parent: Scope;
private _latestScope: Scope = null;
private _canvas: HTMLCanvasElement;
private _canvasState : CanvasState
private _effects: Effect<any>[];
private _eventLog: LogEvent<any>[] = []; // The event log
private _mulSelArray: Effect<any>[]; // The array of selected objects
/**
* Constructor for Scope, an object keeping track of objects within a particular context
* @param parent The parent Scope
* @param canvas The canvas for the effects
* @param effects The array of effects
* @param eventLog The log of events that occurred
*/
constructor(
parent: Scope, canvas: HTMLCanvasElement = null, canvasState : CanvasState = null,
effects: Effect<any>[] = null, eventLog: LogEvent<any>[] = null
) {
this._varBindings = new Map();
this._latestScope = this;
this._parent = parent;
this._canvas = canvas;
this._effects = effects;
this._eventLog = eventLog;
this._canvasState = canvasState;
}
/**
* Returns a copy of the current scope
*/
copy(): Scope {
let s: Scope = new Scope(this.parent, this.canvas, this._canvasState, this.effects, this.eventLog);
s.varBindings = new Map(this.varBindings);
return s;
}
/**
* Returns a child scope with the current scope as parent.
*/
createChildScope(): Scope {
let s: Scope = new Scope(this, this.canvas, this._canvasState, this.effects, this.eventLog);
s.varBindings = new Map(this.varBindings);
return s;
}
/**
* Assigns a value to a variable in this Context
* @param name The name of the variable
* @param val The value of the variable
*/
assign(name: string, val: any): void {
let scopeOpt = this.exists(name);
if(scopeOpt.isDefined()){
scopeOpt.get().varBindings.set(name, Some(val));
} else {
this.varBindings.set(name, Some(val));
}
}
/**
* Looks up the value of the variable with the given name
* in the current scope and ancestor scopes
* @param name The name of the value
*/
lookup(name: string): any {
if (this.varBindings.has(name) && this.varBindings.get(name).isDefined()) {
return (this.varBindings.get(name).get()); //extra get to manage Some()
}
if (this.parent != null) {
return this.parent.lookup(name);
}
throw new Error(`Identifier "${name}" could not be found.`);
}
/**
* Returns the scope of the variable if the variable exists
* including parent scopes
* @param name
*/
exists(name: string): Option<Scope> {
if (this.varBindings.has(name)){
return Some(this);
} else if (this.parent == null) {
return None;
} else {
return this.parent.exists(name);
}
}
get varBindings(): Map<string, Option<any>> {
return this._varBindings;
}
set varBindings(m: Map<string, Option<any>>) {
this._varBindings = m;
}
get parent(): Scope {
return this._parent;
}
get latestScope(): Scope {
return this._latestScope;
}
set latestScope(scope: Scope) {
this._latestScope = scope;
}
get canvas(): HTMLCanvasElement {
return this._canvas;
}
get effects(): Effect<any>[] {
return this._effects;
}
get eventLog(): LogEvent<any>[] {
return this._eventLog;
}
set eventLog(update: LogEvent<any>[]) {
this._eventLog = update;
}
get mulSelArray(): Effect<any>[] {
return this._mulSelArray;
}
get canvasState() : CanvasState {
return this._canvasState;
}
toString() : string {
let s : string = "{ ";
this._varBindings.forEach((value: Option<any>, key: string) => {
s += key + " -> " + value;
})
s += " }"
return s;
}
}
|
C++
|
UTF-8
| 8,745 | 3.03125 | 3 |
[] |
no_license
|
//
// Created by zhang on 2018/10/10.
//
/*
* dfs方法有误
#include <iostream>
#include <cmath>
#include <cstdio>
#include <iomanip>
using namespace std;
#define MaxSize 10000
int Graph[MaxSize][MaxSize], N, M, DFS_Visited[MaxSize]; // N结点数 M边数
int DFS(int start, int distance, int count){
DFS_Visited[start] = 1;
for(int i=0; i<N; i++){
if(Graph[i][start]==1&&!DFS_Visited[i]){
distance = i-start;
if (distance>6){
exit(1);
}
else{
count++;
DFS(i, distance, count);
}
}
}
return count;
}
int main(){
cin>>N>>M;
int v1, v2;
for(int i=0; i<M; i++){
cin>>v1>>v2;
Graph[v1][v2] = 1;
Graph[v2][v1] = 1;
}
for(int i=1; i<=N; i++){
if(!DFS_Visited[i]){
int qualified = DFS(i, 0, 1); // 自己本身的点也要包括进去
double ratio = qualified / (double)N;
cout<<i<<':'<<" "<<setprecision(2)<<ratio*100<<'%'<<endl;
}
}
}
*/
// https://blog.csdn.net/flx413/article/details/53256980
// https://www.cnblogs.com/ranjiewen/p/6771945.html
/*
#include <cstdio>
#include <queue>
#include <vector>
#include <string.h>
using namespace std;
#define MAX 10001
int MGraph[MAX][MAX];
int visit[MAX] = {0};
void InitGraph(int n){
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
MGraph[i][j] = 0;
}
void InsertEdge(int i, int j){
MGraph[i][j] = 1;
MGraph[j][i] = 1;
}
double BFS(int currNode, int n){
queue<int> q;
q.push(currNode);
visit[currNode] = 1;
int count = 1;
for(int level=0; level<6; level++){
vector<int> vec = {0};
while(!q.empty()){
int node = q.front();
vec.push_back(node);
q.pop();
}
for(int i=0; i<vec.size(); i++){
int node = vec[i];
for(int j=1; j<=n; j++){
if(!visit[j]&&MGraph[node][j]==1){
q.push(j);
visit[j] = 1;
count++;
}
}
}
}
double rate = (double)count / (double) n;
return rate * 100.0;
}
int main(){
int N, E;
scanf("%d%d", &N, &E);
InitGraph(N);
int a, b;
for(int i=0; i<E; i++){
scanf("%d%d", &a, &b);
InsertEdge(a, b);
}
for(int i=1; i<=N; i++){
memset(visit, 0, sizeof(visit[0])*(N+1));
double r = BFS(i, N);
printf("%d: %.2lf%%\n", i, r);
}
return 0;
}
*/
/* 这题顶点的数量很大,边较少,所以采用邻接表来实现了。
* */
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <queue>
using namespace std;
#define MaxVertexNum 10000 // 最大顶点数
typedef int Vertex; // 用顶点下标表示顶点
typedef int WeightType; // 边的权值设为整型
typedef char DataType; // 顶点存储的数据类型设为字符型
/*边的定义*/
typedef struct ENode *PtrToENode;
struct ENode{
Vertex V1, V2; // 有向边<V1, V2>
};
typedef PtrToENode Edge;
/*邻接点的定义*/
typedef struct AdjVNode *PtrToAdjVNode;
struct AdjVNode{
Vertex AdjV; // 邻接点下标
PtrToAdjVNode Next; // 指向下一个邻接点的指针
};
/*顶点表头结点的定义*/
typedef struct Vnode{
PtrToAdjVNode FirstEdge; // 边表头指针
}AdjList[MaxVertexNum]; // AdjList是邻接表类型
/*图结点的定义*/
typedef struct GNode *PtrToGNode;
struct GNode{
int Nv; /*顶点数*/
int Ne; /*边数*/
AdjList G; /*邻接表*/
};
typedef PtrToGNode LGraph; // 以邻接表方式存储的图类型
bool Visited[MaxVertexNum] = {false};
LGraph CreateGraph(int VertexNum);
void InsertEdge(LGraph Graph, Edge E);
LGraph BuildGraph();
void Visit(Vertex V);
void InitVisited();
int BFS(LGraph Graph, Vertex V, void (*Visit)(Vertex));
LGraph CreateGraph(int VertexNum)
{
// 初始化一个有VertexNum个顶点但没有边的图
Vertex V;
LGraph Graph;
Graph = (LGraph)malloc(sizeof(struct GNode)); // 建立图
Graph->Nv = VertexNum;
Graph->Ne = 0;
/*初始化邻接表头指针*/
/*注意:这里默认顶点编号从0开始,到(Graph->Nv-1)*/
for(V=0; V<Graph->Nv; V++)
Graph->G[V].FirstEdge = NULL;
return Graph;
}
void InsertEdge(LGraph Graph, Edge E)
{
PtrToAdjVNode NewNode;
/*插入边<V1, V2>*/
/*为V2建立新的邻接点*/
NewNode = (PtrToAdjVNode)malloc(sizeof(struct AdjVNode));
NewNode->AdjV = E->V2;
/*将V2插入V1的表头*/
NewNode->Next = Graph->G[E->V1].FirstEdge;
Graph->G[E->V1].FirstEdge = NewNode; // 这里还是有点难理解的,可以看下我的专栏里的图
/*若是无向图,还要插入边<V2, V1>*/
/*为V1建立新的邻接点*/
NewNode = (PtrToAdjVNode)malloc(sizeof(struct AdjVNode));
NewNode->AdjV = E->V1;
/*将V1插入V2的表头*/
NewNode->Next = Graph->G[E->V2].FirstEdge;
Graph->G[E->V2].FirstEdge = NewNode;
}
LGraph BuildGraph()
{
LGraph Graph;
Edge E;
Vertex V;
int Nv, i;
scanf("%d", &Nv); // 读入顶点个数
Graph = CreateGraph(Nv); // 初始化有Nv个顶点但没有边的图
scanf("%d", &(Graph->Ne)); // 读入边数
if(Graph->Ne != 0){ // 如果有边,即输入的边数不为0
E = (Edge)malloc(sizeof(struct ENode)) // 建立边节点
// 读入边,格式为"起点 终点" 插入邻接矩阵
for(i=0; i<Graph->Ne; i++){
scanf("%d %d", &E->V1, &E->V2);
InsertEdge(Graph, E);
}
}
return Graph;
}
// 初始化Visited[] = false
void InitVisited()
{
for(int i=0; i<MaxVertexNum; i++)
Visit[i] = false;
}
/* 本题的关键在于 如何记录节点当前的层数
* 引入2个变量 last tail 分别指向 当前层数的最后一个元素 和 下一层的最后一个元素
* 若当前出队的元素与last相等 则说明即将进入下一层 将last更新为tail 更新tail 重复~~直到level=6或者队列空
* 用tail记录最后进队的元素,last = tail记录该层tail的值。当last出队时代表层数++
* */
int BFS(LGraph Graph, Vertex V)
{
queue<Vertex> Q;
Vertex W;
int count = 1;
int level = 0;
Vertex last = V, tail; // last与V的值相等, tail值为1
Visited[V] = true; // 标记V已访问
Q.push(V);
while(!Q.empty()){
W = Q.front();
Q.pop();
for(PtrToAdjVNode tempV = Graph->G[W].FirstEdge; tempV; tempV=tempV->Next) /*对W的每个邻接点tempV->AdjV*/
if(!Visited[tempV->AdjV]){
Visited[tempV->AdjV] = true;
Q.push(tempV->AdjV);
count++;
tail = tempV->AdjV; // tail是下一层的最后一个元素
}
if(W == last) {
level++;
last = tail;
}
if(level == 6)
break;
}
return count;
}
int main()
{
LGraph graph;
graph = BuildGraph();
for(int i=1; i<=graph->Nv; i++){
InitVisited();
int count = BFS(graph, i);
printf("%d: %.2f%%\n", i, count*100.0/graph->Nv);
}
return 0;
}
// 邻接矩阵实现
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
bool map[10001][10001] = {false};
int n, m;
int Count;
void bfs(int x){
bool visited[10001] = {false};
queue<int> q;
q.push(x);
visited[x] = true;
int level = 0; // 记录层数
int last = x; // 记录当前层数的最后一个元素
int tail; // 指向下一层最后一个元素
while(!q.empty()){
x = q.front();
q.pop();
for(int i=1; i<=n; i++){
if(!visited[i] && map[x][i] == 1){
q.push(i);
Count++;
visited[i] = true;
tail = i; // 我的理解是,在图中,每个当前层的节点与下一个节点有连接时,都是在下一层的节点,在头脑中想象一下图是怎么画的
}
}
if(last == x){ // x为当前遍历的结点,当遍历到当前层的最后一个元素时,记录下一层
level++;
last = tail;
}
if(level == 6)
break;
}
}
int main(){
cin>>n>>m;
for(int i=0; i<m; i++){
int k, l;
cin>>k>>l;
map[k][l] = 1;
map[l][k] = 1;
}
for(int i=1; i<=n; i++){ /*对于所有节点做bfs()*/
Count = 1; // 全局变量
bfs(i);
cout << i << ": ";
float answer = (float)Count / n * 100;
printf("%.2f%%\n", answer);
}
return 0;
}
|
Python
|
UTF-8
| 1,346 | 3.125 | 3 |
[] |
no_license
|
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QPixmap
class Window(QWidget):
def __init__(self):
super().__init__()
# 화면의 (x : 150, y: 50) 위치에서 (width : 1000, height : 500) 크기의 윈도우가 생성됩니다.
self.setGeometry(150, 50, 1000, 500)
# Window의 Title을 지정합니다.
self.UI()
def UI(self):
# 이미지를 삽일 할 때에도 QLabel을 이용합니다.
self.image = QLabel(self)
# QLabel의 속성에 보면 setPixmap이 있는데 이 값을 통하여 이미지를 지정합니다.
self.image.setPixmap(QPixmap("image.png"))
self.image.move(50, 50)
remove_button = QPushButton("remove", self)
remove_button.move(380, 450)
remove_button.clicked.connect(self.Remove)
show_button = QPushButton("show", self)
show_button.move(500, 450)
show_button.clicked.connect(self.Show)
self.checkbox = QCheckBox("체크박스", self)
self.checkbox.move(100,450)
# Window를 띄웁니다.
self.show()
def Remove(self):
self.image.close()
def Show(self):
self.image.show()
def main():
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec_())
if __name__ == "__main__":
main()
|
PHP
|
UTF-8
| 6,898 | 2.8125 | 3 |
[] |
no_license
|
<?php
/*****************************************************
*
* phpMyCalendar
* Author: Balazs Bezeczky
* phpMyCalendar@gmx.net
* http://phpmycalendar.sourceforge.net/
*
* Last Modified: April 23, 2003
* Version: 1.1.2
*
* Please read the README file for more information
* to install see INSTALL
*
*****************************************************/
//********************************************
// You'll need to fill these things in
$myID="root"; //your username for the MySQL database
$myPwd=""; //your password for the MySQL database
$myHost="localhost"; //the host you're allowed to connect from
$myDB="myCalendar"; //the name of the db phpMyCalendar runs
$myUserTable="user"; //the table where the user infos are stored
$myDataTable="data"; //the table where the appointments are stored
$myAnnivTable="anniversaries"; //the table where the anniversaries are stored
//*******************************************
//leave these as they are
$resultat="";
$dataExists=false;
//require($languageFile);
//*** myUser object definition
class myUser
{
var $ID;
var $username;
var $pwd;
var $email;
var $lang;
//*** object constructor
function myUser($ID,$username,$pwd,$email,$lang)
{
$this->ID=$ID;
$this->username=$username;
$this->pwd=$pwd;
$this->email=$email;
$this->lang=$lang;
}//end myUser
}//end myUser
//*** myDay object definition
class myDay
{
var $user;
var $appointments;
var $day;
var $weekDay;
var $weekDayNum;
var $month;
var $monthOfYear;
var $year;
/*
//*** object constructor
function myDay($times, $date)
{
$this->$appointments=$times;
$this->$date=$date;
}//end myDay
*/
//*** inserts an appointment into today's todo-list
function add_appointment($time, $toDo)
{
$this->appointments[$time]=$toDo;
}//end addAppointment
//***
function show_appointments($CSSclass)
{
$k=8;
if (sizeof($this->appointments)==0)
$this->appointments=array("eEight"=>"", "eNine"=>"", "eTen"=>"", "eEleven"=>"", "eTwelve"=>"", "eThirteen"=>"", "eFourteen"=>"", "eFifteen"=>"", "eSixteen"=>"", "eSeventeen"=>"", "eEighteen"=>"", "eNineteen"=>"", "eTwenty"=>"", "eTwentyone"=>"", "eTwentytwo"=>"");
while (list($key,$value) = each($this->appointments))
{
if ($k < 10)
$t="0".$k;
else
$t=$k;
if (strcmp($value,"")==0)
$value=" ";
echo "
<tr><td class=\"$CSSclass\" width=40 valign=top>
<font class=black>$t:00</font></td><td class=\"$CSSclass\" width=160 valign=top>\n
$value</td></tr>\n
";
$k++;
}//end while
}//end showAppointments
//***
function get_date()
{
return $this->day."-".$this->month."-".$this->year;
}//end get_date
//***
function get_appointments()
{
return $this->appointments;
}//end get_appointments
}//end myDay
//*** db_class object definition
class db_class
{
var $connection;
var $DB;
var $sqlError;
var $sqlErrNo;
var $host;
var $pwd;
var $result;
var $result_num;
var $table;
var $user;
//*** object constructor
function db_class($DB,$host,$pwd,$table,$user)
{
$this->DB=$DB;
$this->host=$host;
$this->pwd=$pwd;
$this->table=$table;
$this->user=$user;
}//end
//*** connects to the db
function db_connect()
{
if (!$this->connection = mysql_connect($this->host,$this->user,$this->pwd))
{
$this->sqlErrNo=mysql_errno();
$this->sqlError=mysql_error();
return false;
}
else
{
return true;
}//end if
}//end db_connect
//*** closes connection to the db
function db_disconnect()
{
if (mysql_close($this->connection))
return true;
else
return false;
}//end db_disconnect
//*** runs an sql-query
function db_query($query)
{
if (!$this->result=mysql_query($query))
{
$this->sqlErrNo=mysql_errno();
$this->sqlError=mysql_error();
return false;
}
else
{
if (strstr($query, "SELECT")!=false)
$this->result_num=mysql_num_rows($this->result);
return true;
}//end if
}//end db_query
//*** selects a db
function db_select_db()
{
if (mysql_select_db($this->DB,$this->connection))
{
return true;
}
else
{
$this->sqlErrNo=mysql_errno();
$this->sqlError=mysql_error();
return false;
}//end if
}//end db_select_db
//*** returns the next row from the last query's result
function db_next_result($type)
{
if (!$this->result)
{
$this->sqlErrNo=99;
$this->sqlError="Result set is empty";
return false;
}
else
{
if (strcmp($type, "")==0)
return mysql_fetch_array($this->result);
else
return mysql_fetch_array($this->result, $type);
}
}//end db_next_result
}//end db_class
//*** logs some text into a logfile - used just for testing
function exec_log($text)
{
$fp=fopen("/tmp/php_log.txt", "a");
fwrite($fp,$text);
}//end exec_log
//*** sends username/password promt
function authenticate()
{
header("WWW-Authenticate: Basic realm=\"phpMyCalendar Login\"");
header( "HTTP/1.0 401 Unauthorized");
echo "You must enter a valid login ID and password to access this resource\n";
exit;
}//end authenticate
//*** creates an instance of the user object
function createUser($userName)
{
global $user, $db_com, $myUserTable;
$db_com->db_query("SELECT * FROM ".$myUserTable." WHERE user='".$userName."'");
if ($db_com->result_num==1)
{
$login=$db_com->db_next_result('');
$user=new myUser($login[0],$login[1],$login[2],$login[3],$login[4]);
}
}//end
//*** checks the database for the entered username/password combination
function checkDB($userName,$pwd)
{
global $user;
createUser($userName);
if ($user->username==$userName and $user->pwd == $pwd)
{
$cookieInfo=$user->username."_".$user->pwd;
header ("Set-Cookie: phpMyCalendar=$cookieInfo; expires=Friday, 16-Jan-2037 00:00:00 GMT; path=/;");
return true;
}
else
{
return false;
}//end if
}//end checkDB
//*** check whether there is a cookie with stored username/password
function checkCookie()
{
global $user, $HTTP_SERVER_VARS, $HTTP_COOKIE_VARS;
$PHP_AUTH_PW=$HTTP_SERVER_VARS['PHP_AUTH_PW'];
$PHP_AUTH_USER=$HTTP_SERVER_VARS['PHP_AUTH_USER'];
$phpMyCalendar=$HTTP_COOKIE_VARS['phpMyCalendar'];
//no cookie:
if (strcmp($phpMyCalendar, "")==0)
{
if (checkDB($PHP_AUTH_USER, md5($PHP_AUTH_PW))==false)
return false;
else
return true;
}
//cookie found:
else
{
$login=explode("_", $phpMyCalendar);
if (
(strcmp($login[0], $PHP_AUTH_USER)!=0 or strcmp($login[1], md5($PHP_AUTH_PW))!=0) and
(checkDB($login[0], $login[1])==false)
)
{
return false;
}
else
{
createUser($PHP_AUTH_USER);
return true;
}
}//end if
}//end checkCookie
?>
|
Markdown
|
UTF-8
| 1,721 | 2.921875 | 3 |
[] |
no_license
|
# WEB DEVELOP STANDARD
1. API standard ([restful style](http://www.ruanyifeng.com/blog/2014/05/restful_api.html))
* back-end => front-end:
get (query info):
```js
// request successed
// /api/v1/areas/info/areas
{
"code": 200,
"data": [
{
"id": "027",
"name": "武汉",
"details": "武汉"
},
{
"id": "010",
"name": "北京",
"details": "北京"
}
]
}
// /api/v1/areas/info/areas/:areaId
{
"code": 200,
"data": {
"id": "010",
"name": "北京",
"details": "北京"
}
}
// request failed
{
"code": 400,
"message": "xxxxxxx failed"
}
```
put | post (modify record info | add new record info)
```js
// request successed
{
"code": 203,
"data": {
"info": "xxxxxx successed"
}
}
// request failed
{
"code": 403,
"message": "xxxxxx failed"
}
```
delete (delete some record info)
```js
// request successed
{
"code": 204,
"data": {
"info": "xxxxxx successed"
}
}
// request failed
{
"code": 404,
"message": "xxxxxxx failed"
}
```
|
PHP
|
UTF-8
| 2,558 | 2.5625 | 3 |
[] |
no_license
|
<?php
require 'function.php';
// if(empty($_POST['nama']) || empty($_POST['keterangan']) || empty($_POST['harga']) || empty($_POST['jumlah'])){
// $error = "<h3 style='color:red;'> Data tidak boleh kosong</h3>";
// return false;
// }
if(isset($_POST["tambah"])){
if(tambah($_POST) == 1){
echo "<script>
alert ('Produk Berhasil Ditambah')
document.location.href = 'index.php'
</script>";
}else{
"<script>
alert ('Produk Gagal Ditambah')
document.location.href = 'index.php'
</script>";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- BOOTSTRAP -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<style>
form{
width:500px;
}
</style>
<title>Edit</title>
</head>
<body>
<div class="row justify-content-center ">
<form method="post" action="" class="card m-5 p-5 bg-success text-light">
<h3 class="row justify-content-center text-light mb-5">TAMBAH DATA PRODUK</h3>
<input type="hidden" value="<?= $produk['id'] ?>" name="id">
<div class="row mt-3">
<label for="nama" class="col-4" col-form-label" >Nama Produk</label>
<input type="text" class="form-control col-8 col-form-label" name="nama" id="nama" autocomplete="off" required>
</div>
<div class="row mt-3">
<label for="keterangan" class="col-4" col-form-label" >Keterangan produk</label>
<input type="text" class="form-control col-8 col-form-label" name="keterangan" id="keterangan" autocomplete="off" required>
</div>
<div class="row mt-3">
<label for="harga" class="col-4" col-form-label" >Harga Produk</label>
<input type="number" class="form-control col-8 col-form-label" name="harga" id="harga" required>
</div>
<div class="row mt-3">
<label for="jumlah" class="col-4" col-form-label" >Jumlah Produk</label>
<input type="number" class="form-control col-8 col-form-label" name="jumlah" id="jumlah" required>
</div>
<div class="row justify-content-center mt-5">
<button name="tambah" class="btn btn-outline-light col-6 col-form-label center mr-3">Tambah Data produk</button>
<a href="index.php" class="btn btn-outline-light col-4 col-form-label center">Kembali</a>
</div>
</form>
</div>
</body>
</html>
|
Markdown
|
UTF-8
| 7,020 | 3.234375 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
# node-netbios-name
A utility module for working with NetBIOS names as defined in [RFC1001][],
[RFC1002][], and [RFC883][].
[](https://travis-ci.org/wanderview/node-netbios-name)
## Example
``` javascript
var NBName = require('netbios-name');
// The following two statements are equivalent
var nbname = new NBName({fqdn: 'foobar.example.com', suffix: 0x20});
var nbname = new NBName({name: 'foobar', scopeId: 'example.com',
suffix: 0x20});
if (nbname.error) {
throw nbname.error;
}
nbname.name === 'foobar'; // true
nbname.paddedName === 'foobar '; // true
nbname.scopeId === 'example.com'; // true
nbname.fqdn === 'foobar.example.com'; // true
nbname.suffix === 0x20; // true
nbname.usage === 'File Server Service'; // true
nbname.toString() === 'foobar<20>.example.com'; // true
var buf = new Buffer(128);
var res = nbname.write(buf, 0, {});
if (res.error) {
throw res.error;
}
var nbname2 = NBName.fromBuffer(buf, 0);
if (nbname2.error) {
throw nbname2.error;
}
nbname2.bytesRead === res.bytesWritten; // true
nbname2.name === nbname.name; // true
nbname2.scopeId === nbname.scopeId; // true
nbname2.fqdn === nbname.fqdn; // true
nbname2.suffix === nbname.suffix; // true
nbname2.usage === nbname.usage; // true
```
## Class: NetbiosName
This class represents the name of a single NetBIOS node or service. It
consists of the following properties:
* `name` {String} The short NetBIOS name. This is equivalent to the first
label in a fully qualified domain name. The NetBIOS name is restricted
to a maximum length of 15 characters.
* `scopeId` {String} The scope identifier or domain name that the node
belongs to. For example, if the fully qualified domain name is
`host.example.com`, then the `scopeId` property will be `example.com`
and the `name` property above will be `host`.
* `suffix` {Number} The trailing suffix byte that combines with the NetBIOS
name above to create a 16-byte fixed width field. Microsoft popularized
the use of this byte for indicating the type or usage of the node.
Typically suffix byte values will be defined and displayed in hex; e.g.
`0x00` for workstations or `0x20` for file servers.
In addition to the basic properties, the class also derives the following
values as a convenience:
* `paddedName` {String} The same as the `name` field space padded out to
15 characters.
* `fqdn` {String} The combination of the `name` field and the `scopeId` field.
* `usage` {Sring} A human readable string describing the typical usage for
the given `suffix` byte. If the `suffix` does not match a typical value,
then `usage` will be set to `'unknown'`. These usage values are taken
from the Microsoft [NetBIOS Suffixes][] knowledge base article.
Finally, instances of NetbiosName can also have additional properties based
on how the object was created:
* `error` {Error Object} This property will be set if the constructor or
`fromBuffer()` method encounter an error while creating the NetbiosName
object. This property should always be checked before using the instance
or any of its other properties.
* `bytesRead` {Number} This property indicates how many bytes were read from
the buffer passed to `fromBuffer()` in order to create this instance.
Note, all properties are set in the constructor or the `fromBuffer()` factory
method. If you write to one of the properties, don't expect any other values
to get updated to reflect the change.
### new NetbiosName(opts)
Construct a new NetbiosName instance for a given name and suffix.
* `opts` {Object} A hash of named parameters. Accepted options are:
* `fqdn` {String} The fully qualified domain name to use.
* `name` {String} The short NetBIOS name to use. This is only referenced
if `fqdn` is not present.
* `scopeId` {String} The trailing domain name to be combined with the `name`
property. This should not include a leading dot. This is only
referenced if `fqdn` is not present.
* `suffix` {Number} The suffix byte value to use. If this is not present
then the suffix defaults to 0x00 which typically represents a workstation
service.
* Returns a new NetbiosName instance. Note that if there are any problems
the `error` property of the NetbiosName object will be set. Typically
errors only occur if a name is not provided or if its illegal due to length,
etc.
### NetbiosName.fromBuffer(buf, offset)
Construct a new NetbiosName object from a binary buffer.
* `buf` {Buffer Object} The buffer to read the name from. Note, if this name
is being read from a message that uses name pointers, the first byte of the
buffer must correspond to the start of the message. So don't just `slice()`
to the start of the name since the pointer offsets will be meaningless.
* `offset` {Number} The offset from the start of the buffer indicating where
to begin reading.
* Returns a new NetbiosName object instance. Make sure to check the `error`
property on the returned object before using any other properties. Also,
see the `bytesRead` property to determine how much of the buffer was
processed by this method.
### nbname.write(buf, offset, nameMap)
Write the NetbiosName object instance out to the given buffer.
* `buf` {Buffer Object} The buffer to write the name to. Again, if name
pointers are going to be used, the start of the buffer must match the
start of the overall NetBIOS message.
* `offset` {Number} Where to begin writing the name within the buffer.
* `nameMap` {Object | null} If provided the location of the name within the
buffer will be stored in the `nameMap`. If the same `nameMap` is used to
write the same name again or a portion of the name, then a name pointer
will used to compress the name within the buffer. Passing `null` will
disable the use of name pointers.
* Returns an Object containing two properties.
* `error` {Error Object} If an error occurred during writing this property
will be set. The buffer may have been partially modified even if an
error occurs.
* `bytesWritten` {Number} The number of bytes written to the buffer.
### nbname.toString()
Return a string representation of the NetBIOS name. The format matches the
style used by wireshark. For example, a name of `foobar`, a scope ID of
`example.com`, and suffix of `0x20` would be returned as the string
`'foobar<20>.example.com'`.
The string returned contains all of the unique information in the name, so
it can be reasonably used as the key for a hash.
[RFC1001]: http://tools.ietf.org/rfc/rfc1001.txt
[RFC1002]: http://tools.ietf.org/rfc/rfc1002.txt
[RFC883]: http://tools.ietf.org/rfc/rfc883.txt
[NetBIOS Suffixes]: http://support.microsoft.com/kb/163409
|
C++
|
UTF-8
| 7,332 | 3.0625 | 3 |
[] |
no_license
|
#include "doughnutmode.h"
DoughnutMode::DoughnutMode(int height, int width, float density, int outputType, string outputFile) : Game(height, width, density, outputType, outputFile){
}
DoughnutMode::DoughnutMode(string file, int outputType, string outputFile) : Game(file, outputType, outputFile){
}
DoughnutMode::~DoughnutMode(){
}
// Checks boundaries depending on the qualifications of Doughnut Mode
int DoughnutMode::checkBoundaries(char** arrayGrid, int heightIndex, int widthIndex, int maxHeight, int maxWidth) {
int neighbors = 0;
if (heightIndex == 0) { // Top row
if (widthIndex == 0) { // Left corner
if (arrayGrid[heightIndex+1][widthIndex] == 'X') { // Lower middle
neighbors++;
}
if (arrayGrid[heightIndex+1][widthIndex+1] == 'X') { // Lower right
neighbors++;
}
if (arrayGrid[heightIndex][widthIndex+1] == 'X') { // Middle right
neighbors++;
}
if (arrayGrid[0][maxWidth] == 'X') { // Top right corner
neighbors++;
}
if (arrayGrid[1][maxWidth] == 'X') { // Diagonal lower left
neighbors++;
}
if (arrayGrid[maxHeight][maxWidth] == 'X') { // Bottom right corner
neighbors++;
}
if (arrayGrid[maxHeight][0] == 'X') { // Bottom left corner
neighbors++;
}
if (arrayGrid[maxHeight][1] == 'X') { // Diagonal upper left
neighbors++;
}
}
else if (widthIndex == maxWidth) { // Right corner
if (arrayGrid[heightIndex+1][widthIndex-1] == 'X') { // Lower left
neighbors++;
}
if (arrayGrid[heightIndex+1][widthIndex] == 'X') { // Lower middle
neighbors++;
}
if (arrayGrid[heightIndex][widthIndex-1] == 'X') { // Middle left
neighbors++;
}
if (arrayGrid[0][0] == 'X') { // Top left corner
neighbors++;
}
if (arrayGrid[1][0] == 'X') { // Diagonal lower left
neighbors++;
}
if (arrayGrid[maxHeight][maxWidth] == 'X') { // Bottom right corner
neighbors++;
}
if (arrayGrid[maxHeight][0] == 'X') { // Bottom left corner
neighbors++;
}
if (arrayGrid[maxHeight][maxWidth-1] == 'X') { // Diagonal upper left
neighbors++;
}
}
else if (widthIndex != 0 && widthIndex != maxWidth) { // Top row non-corners
if (arrayGrid[heightIndex+1][widthIndex-1] == 'X') { // Lower left
neighbors++;
}
if (arrayGrid[heightIndex+1][widthIndex] == 'X') { // Lower middle
neighbors++;
}
if (arrayGrid[heightIndex+1][widthIndex+1] == 'X') { // Lower right
neighbors++;
}
if (arrayGrid[heightIndex][widthIndex+1] == 'X') { // Middle right
neighbors++;
}
if (arrayGrid[heightIndex][widthIndex-1] == 'X') { // Middle left
neighbors++;
}
if (arrayGrid[maxHeight][widthIndex] == 'X') { // Upper middle
neighbors++;
}
if (arrayGrid[maxHeight][widthIndex-1] == 'X') { // Upper left
neighbors++;
}
if (arrayGrid[maxHeight][widthIndex+1] == 'X') { // Upper right
neighbors++;
}
}
} else if (heightIndex == maxHeight) { // Bottom row
if (widthIndex == 0) { // Left corner
if (arrayGrid[heightIndex-1][widthIndex+1] == 'X') { // Upper right
neighbors++;
}
if (arrayGrid[heightIndex-1][widthIndex] == 'X') { // Upper middle
neighbors++;
}
if (arrayGrid[heightIndex][widthIndex+1] == 'X') { // Middle right
neighbors++;
}
if (arrayGrid[0][maxWidth] == 'X') { // Top right corner
neighbors++;
}
if (arrayGrid[0][0] == 'X') { // Top left corner
neighbors++;
}
if (arrayGrid[0][1] == 'X') { // Diagonal lower right
neighbors++;
}
if (arrayGrid[maxHeight][maxWidth] == 'X') { // Bottom right corner
neighbors++;
}
if (arrayGrid[maxHeight-1][maxWidth] == 'X') { // Diagonal upper left
neighbors++;
}
}
else if (widthIndex == maxWidth) { // Right corner
if (arrayGrid[heightIndex-1][widthIndex-1] == 'X') { // Upper left
neighbors++;
}
if (arrayGrid[heightIndex-1][widthIndex] == 'X') { // Upper middle
neighbors++;
}
if (arrayGrid[heightIndex][widthIndex-1] == 'X') { // Middle left
neighbors++;
}
if (arrayGrid[0][0] == 'X') { // Top left corner
neighbors++;
}
if (arrayGrid[0][maxWidth] == 'X') { // Top right corner
neighbors++;
}
if (arrayGrid[0][maxWidth-1] == 'X') { // Diagonal lower left
neighbors++;
}
if (arrayGrid[maxHeight][0] == 'X') { // Bottom left corner
neighbors++;
}
if (arrayGrid[maxHeight-1][0] == 'X') { // Diagonal upper right
neighbors++;
}
}
else if (widthIndex != 0 && widthIndex != maxWidth) { // Bottom row non-corners
if (arrayGrid[heightIndex-1][widthIndex-1] == 'X') { // Upper left
neighbors++;
}
if (arrayGrid[heightIndex-1][widthIndex+1] == 'X') { // Upper right
neighbors++;
}
if (arrayGrid[heightIndex-1][widthIndex] == 'X') { // Upper middle
neighbors++;
}
if (arrayGrid[heightIndex][widthIndex+1] == 'X') { // Middle right
neighbors++;
}
if (arrayGrid[heightIndex][widthIndex-1] == 'X') { // Middle left
neighbors++;
}
if (arrayGrid[0][widthIndex+1] == 'X') { // Lower right
neighbors++;
}
if (arrayGrid[0][widthIndex-1] == 'X') { // Lower left
neighbors++;
}
if (arrayGrid[0][widthIndex] == 'X') { // Lower middle
neighbors++;
}
}
} else if (widthIndex == 0) {
if (arrayGrid[heightIndex+1][widthIndex] == 'X') { // Lower middle
neighbors++;
}
if (arrayGrid[heightIndex+1][widthIndex+1] == 'X') { // Lower right
neighbors++;
}
if (arrayGrid[heightIndex-1][widthIndex+1] == 'X') { // Upper right
neighbors++;
}
if (arrayGrid[heightIndex-1][widthIndex] == 'X') { // Upper middle
neighbors++;
}
if (arrayGrid[heightIndex][widthIndex+1] == 'X') { // Middle right
neighbors++;
}
if (arrayGrid[heightIndex-1][maxWidth] == 'X') { // Upper left
neighbors++;
}
if (arrayGrid[heightIndex][maxWidth] == 'X') { // Middle left
neighbors++;
}
if (arrayGrid[heightIndex+1][maxWidth] == 'X') { // Lower left
neighbors++;
}
} else if (widthIndex == maxWidth) {
if (arrayGrid[heightIndex+1][widthIndex-1] == 'X') { // Lower left
neighbors++;
}
if (arrayGrid[heightIndex+1][widthIndex] == 'X') { // Lower middle
neighbors++;
}
if (arrayGrid[heightIndex][widthIndex-1] == 'X') { // Middle left
neighbors++;
}
if (arrayGrid[heightIndex-1][widthIndex-1] == 'X') { // Upper left
neighbors++;
}
if (arrayGrid[heightIndex-1][widthIndex] == 'X') { // Upper middle
neighbors++;
}
if (arrayGrid[heightIndex][0] == 'X') { // Middle right
neighbors++;
}
if (arrayGrid[heightIndex-1][0] == 'X') { // Upper right
neighbors++;
}
if (arrayGrid[heightIndex+1][0] == 'X') { // Lower right
neighbors++;
}
}
return neighbors;
}
|
Java
|
UTF-8
| 3,548 | 1.765625 | 2 |
[] |
no_license
|
package com.rfchina.community.service;
import com.rfchina.community.component.PlatformGlobalComponent;
import com.rfchina.community.persistence.mapper.SysSmsTemplateMapper;
import com.rfchina.community.persistence.model.SysSmsTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.stream.Stream;
@Service
public class SmsGlobalService {
private static Logger logger = LoggerFactory.getLogger(SmsGlobalService.class);
@Autowired
private SysSmsTemplateMapper sysSmsTemplateMapper;
@Autowired
private PlatformGlobalComponent platformGlobalComponent;
public String getSmsTemplate(String smsType) {
SysSmsTemplate temp = sysSmsTemplateMapper.selectByPrimaryKey(smsType);
return temp.getSmsTemp();
}
public String formatSms(SmsType smsType, Object... args) {
String temp = getSmsTemplate(smsType.name());
if (args == null || args.length == 0) {
return temp;
}
String[] st = {""};
return MessageFormat.format(temp, Stream.concat(Arrays.stream(st), Arrays.stream(args)).toArray());
// return MessageFormat.format(temp,stooges.toArray());
}
public int sendSms(String phone, SmsType smsType, Object... args) {
String msgContent = formatSms(smsType, args);
return platformGlobalComponent.sendSms(phone, msgContent, null, null);
}
public int sendSms4Encrypt(String phone, SmsType smsType, String regex, String targetContent, Object... args) {
String msgContent = formatSms(smsType, args);
return platformGlobalComponent.sendSms(phone, msgContent, regex, targetContent);
}
public enum SmsType {
zizai_comm_passwd, zizai_3f_interview, zizai_vernue_ok, zizai_parking_bind, zizai_parking_bind_ok, zizai_api_visit, zizai_api_visit4,zizai_api_2visit,zizai_api_2visit_ok,zizai_api_2visit_refuse, zizai_3f_phone_check,
//
zizai_api_acc_1, zizai_api_acc_2, zizai_api_acc_3, zizai_api_acc_4, zizai_api_acc_6,
zizai_parking_yueka,
zizai_parking_yueka_unbind,
biz_apply_vcode,
zizai_lucky_draw,
zizai_bp_exchange,
zizai_invitation_1,
zizai_invitation_2,
/**
* 会员认证相关
*/
zizai_member_cert_bind,
zizai_member_cert_forbidden,
zizai_member_cert_invitation,
zizai_member_cert_unbind_byo,
zizai_member_cert_unbind_byp,
zizai_member_cert_unbind_byt,
/**
* 会员认证相关
*/
zizai_bonus_point_activity,
/**
* 收楼相关
*/
zizai_repossession_tips,
/**
* 阈值告警
*/
zizai_threshold_alert,
/**
* 抽奖活动相关
*/
zizai_activity_lottery_ele_normal,
zizai_activity_lottery_ele_5,
zizai_activity_lottery_ele_10,
zizai_activity_lottery_ele_30,
zizai_activity_lottery_physic,
zizai_activity_lottery_point,
zizai_activity_lottery_dawang_card,
/**
* 抽奖虚拟券
*/
zizai_act_virtual_card_tips,
/**
* 车场相关
*/
zizai_parking_month_expire,
zizai_parking_month_audit,
/**
* 物业缴费相关
*/
zizai_prop_payment_notify
}
}
|
JavaScript
|
UTF-8
| 2,640 | 2.53125 | 3 |
[] |
no_license
|
/**
* Extended Webix AJAX (http://docs.webix.com/helpers__ajax_operations.html)
* so that can work with server security constraints.
*
* Created by Phuttipong on 19/5/2559.
*/
var domain = '//localhost:8080/';
webix.extend(webix.ajax, {
/**
* helper method for create Webix general, non-secure GET ajax.
* @param url path relative to domain name. no need to start with '/'
* @param params obj of params
* @param callbacks array of callbacks, can use object if single callback
* @returns {*}
*/
restGet: function (url, params, callbacks) {
return webix.ajax().headers({
"X-Requested-With": "XMLHttpRequest"
}).get(domain + url, params, callbacks);
},
/**
* helper method for create Webix general, non-secure POST ajax.
* @param url path relative to domain name. no need to start with '/'
* @param body
* @param callbacks array of callbacks, can use object if single callback
* @returns {*}
*/
restPost: function (url, body, callbacks) {
return webix.ajax().headers({
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/json"
}).post(domain + url, body, callbacks);
},
/**
* helper method for create Webix general, non-secure DELETE ajax.
* @param url
* @param body
* @param callbacks
* @returns {*}
*/
restDel: function (url, body, callbacks) {
return webix.ajax().headers({
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/json"
}).del(domain + url, body, callbacks);
},
/**
* helper method for create Webix general, secure GET ajax.
* @param url path relative to domain name. no need to start with '/'
* @param params obj of params
* @param callbacks array of callbacks, can use object if single callback
* @returns {*}
*/
sRestGet: function (url, params, callbacks) {
return webix.ajax().headers({
"X-Requested-With": "XMLHttpRequest"
}).get(domain + url, params, callbacks);
},
/**
* helper method for create Webix general, secure POST ajax.
* @param url path relative to domain name. no need to start with '/'
* @param body
* @param callbacks array of callbacks, can use object if single callback
* @returns {*}
*/
sRestPost: function (url, body, callbacks) {
return webix.ajax().headers({
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/json"
}).post(domain + url, body, callbacks);
}
});
|
Python
|
UTF-8
| 910 | 3.875 | 4 |
[] |
no_license
|
# python3
def max_pairwise_product(numbers):
n = len(numbers)
max_product = 0
for first in range(n):
for second in range(first + 1, n):
max_product = max(max_product,
numbers[first] * numbers[second])
return max_product
def max_pairwise_product_fast(numbers):
first = 0
second = 0
for number in numbers:
if number > first:
first, second = number, first
elif second < number <= first:
second = number
return first * second
def test_result():
assert max_pairwise_product([1, 2, 3]) == 6
assert max_pairwise_product([9, 1, 9]) == 81
assert max_pairwise_product([100000, 90000]) == 9000000000
if __name__ == '__main__':
test_result()
input_n = int(input())
input_numbers = [int(x) for x in input().split()]
print(max_pairwise_product_fast(input_numbers))
|
Java
|
UTF-8
| 631 | 2.4375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.six.dove.common;
/**
* @author sixliu
* @date 2018年1月17日
* @email 359852326@qq.com
* @Description 服务接口
*/
public interface Service {
/**
* 服务状态
*
* @author Administrator
*
*/
public enum State {
INIT,START, STOP, FAILED;
}
/**
* 获取服务名称
*
* @return
*/
String getName();
/**
* 获取服务状态
*
* @return
*/
State getState();
/**
* 服务是否正在运行
* @return
*/
boolean isRunning();
/**
* 启动服务
*/
void start();
/**
* 停止服务
*/
void stop();
}
|
SQL
|
UTF-8
| 632 | 3.8125 | 4 |
[] |
no_license
|
select vmt.vehicle_id,plt.lead_name,plt.phone_number,vmt.vehicle_no,emt.first_name,
CONCAT(date(pvdt.owned_on),' ',TIME_FORMAT(pvdt.owned_on, '%h:%i:%s %p')) as updated_on
from purchased_vehicle_details_tbl pvdt inner join vehicle_master_tbl vmt on vmt.vehicle_id=pvdt.vehicle_id and vmt.is_active='Y'
and pvdt.is_active='Y'
inner join purchase_lead_tbl plt on plt.purchase_lead_id=vmt.purchase_lead_id
inner join evaluator_vehicle_assignment_tbl evat on evat.vehicle_id=vmt.vehicle_id and evat.is_active='Y'
inner join employee_master_tbl emt on emt.employee_id=evat.evaluator_id
where pvdt.onboard_id=3
group by pvdt.vehicle_id;
|
SQL
|
UTF-8
| 26,385 | 3.09375 | 3 |
[
"MIT"
] |
permissive
|
-- phpMyAdmin SQL Dump
-- version 4.5.5.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Jun 24, 2018 at 03:50 PM
-- Server version: 5.7.11
-- PHP Version: 5.6.19
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `complaint`
--
-- --------------------------------------------------------
--
-- Table structure for table `admin`
--
CREATE TABLE `admin` (
`a_id` int(11) NOT NULL,
`name` varchar(60) NOT NULL,
`email` varchar(40) NOT NULL,
`password` varchar(14) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `admin`
--
INSERT INTO `admin` (`a_id`, `name`, `email`, `password`) VALUES
(1, 'Admin', 'admin@admin.com', 'admin');
-- --------------------------------------------------------
--
-- Table structure for table `category`
--
CREATE TABLE `category` (
`cate_id` int(11) NOT NULL,
`category` varchar(20) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `category`
--
INSERT INTO `category` (`cate_id`, `category`) VALUES
(1, 'Electrical'),
(2, 'Civil'),
(3, 'Plumbaring'),
(4, 'Carpenter'),
(5, 'Drainage'),
(6, 'biogas');
-- --------------------------------------------------------
--
-- Table structure for table `complaint`
--
CREATE TABLE `complaint` (
`co_id` int(11) NOT NULL,
`cate_id` int(11) DEFAULT NULL,
`c_level` int(1) DEFAULT NULL,
`description` longtext
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `complaint`
--
INSERT INTO `complaint` (`co_id`, `cate_id`, `c_level`, `description`) VALUES
(2, 1, 1, 'Tube Light Not Working'),
(3, 3, 2, 'Pipe Leakage'),
(4, 1, 1, 'Fan Not Working'),
(5, 1, 1, 'Power Cut'),
(6, 2, 1, 'Fan Not Working'),
(7, 1, 1, 'Switch Board Not Working'),
(8, 2, 1, 'Wall Damage'),
(9, 2, 1, 'Toles Broken'),
(10, 3, 1, 'Tap Leakage'),
(11, 4, 1, 'Door damaged'),
(12, 4, 1, 'Window broken'),
(13, 5, 1, 'Cleaning'),
(14, 1, 1, 'wire damaged'),
(15, 1, 1, 'fan regulator broken'),
(16, 2, 1, 'silling damaged'),
(17, 2, 1, 'Tiles damaged'),
(18, 3, 1, 'Water Tank broken'),
(19, 3, 1, 'washbasin pipe jammed'),
(20, 2, 1, 'washbasin broken'),
(22, 5, 1, 'Drain full ');
-- --------------------------------------------------------
--
-- Table structure for table `complaint_location`
--
CREATE TABLE `complaint_location` (
`loc_id` int(11) NOT NULL,
`c_id` varchar(20) NOT NULL,
`location` varchar(100) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `complaint_location`
--
INSERT INTO `complaint_location` (`loc_id`, `c_id`, `location`) VALUES
(1, '2018-06-04-001', 'Computer Science Office No 3'),
(2, '2018-06-04-002', 'Residance 3,\r\nBuilding No. 1,\r\nRoom No 5'),
(3, '2018-06-04-003', 'Computer Science Office No 3'),
(4, '2018-06-04-004', 'Residance 3,\r\nBuilding No. 1,\r\nRoom No 5'),
(5, '2018-06-04-005', 'Computer Science Office No 3'),
(6, '2018-06-04-006', 'Residance 3,\r\nBuilding No. 1,\r\nRoom No 5'),
(7, '2018-06-04-007', 'Social Work Office No 1'),
(8, '2018-06-04-008', 'Social Work Office No 1'),
(9, '2018-06-04-009', 'Residance 5,\r\nBuilding No 3,\r\nRoom No 10'),
(10, '2018-06-04-010', 'Social Work Office No 1'),
(11, '2018-06-04-011', 'Residance 5,\r\nBuilding No 3,\r\nRoom No 10'),
(12, '2018-06-04-012', 'Social Work Office No 1'),
(13, '2018-06-04-013', 'Gujrati Vibhag Office No 2'),
(14, '2018-06-04-014', 'Gujrati Vibhag Office No 2'),
(15, '2018-06-04-015', 'Gujrati Vibhag Office No 2'),
(16, '2018-06-04-016', 'Residence 1,\r\nBuilding No 6,\r\nRoom No 1'),
(17, '2018-06-06-001', 'Social Work Office No 1'),
(18, '2018-06-06-002', 'Social Work Office No 1'),
(19, '2018-06-06-003', 'Residance 5,\r\nBuilding No 3,\r\nRoom No 10'),
(20, '2018-06-06-004', 'Social Work Office No 1'),
(21, '2018-06-06-005', 'Residance 5,\r\nBuilding No 3,\r\nRoom No 10'),
(22, '2018-06-06-006', 'Social Work Office No 1'),
(23, '2018-06-06-007', '116,Girls hostel'),
(24, '2018-06-06-008', '116,Girls hostel'),
(25, '2018-06-06-009', '116, girls hostel'),
(26, '2018-06-06-010', 'Computer Science MCA computer science department.'),
(27, '2018-06-06-011', '12,Post graduation Boys hostel'),
(28, '2018-06-06-012', '12,Post graduation Boys hostel'),
(29, '2018-06-06-013', 'USIC department Usic department'),
(30, '2018-06-06-014', 'USIC department Usic department'),
(31, '2018-06-06-015', 'Post Graduation Hostel'),
(32, '2018-06-06-016', 'Post Graduation Hostel'),
(33, '2018-06-06-017', 'Post Graduation Hostel'),
(34, '2018-06-06-018', 'USIC department Usic department'),
(35, '2018-06-06-019', 'Post Graduation Hostel'),
(36, '2018-06-06-020', 'Post Graduation Hostel'),
(37, '2018-06-06-021', 'USIC department Usic department'),
(38, '2018-06-06-022', 'USIC department Usic department'),
(39, '2018-06-06-023', '116,Girls hostel'),
(40, '2018-06-06-024', '116,Girls hostel'),
(41, '2018-06-06-025', '116,Girls hostel'),
(42, '2018-06-06-026', 'Computer Science MCA computer vibhag,gujarat vidya'),
(43, '2018-06-06-027', '116,Girls hostel'),
(44, '2018-06-06-028', '116,Girls hostel'),
(45, '2014-01-01-001', 'Residance 3,\r\nBuilding No. 1,\r\nRoom No 5'),
(46, '2018-06-20-001', 'Residance 3,\r\nBuilding No. 1,\r\nRoom No 5'),
(47, '2018-06-20-002', 'Computer Science Office No 3'),
(48, '2018-06-21-001', 'Residance 3,\r\nBuilding No. 1,\r\nRoom No 5'),
(49, '2014-01-01-002', 'Residance 3,\r\nBuilding No. 1,\r\nRoom No 5'),
(50, '2018-06-22-001', 'Residance 3,\r\nBuilding No. 1,\r\nRoom No 5'),
(51, '2018-06-22-002', 'Residance 3,\r\nBuilding No. 1,\r\nRoom No 5');
-- --------------------------------------------------------
--
-- Table structure for table `complaint_register`
--
CREATE TABLE `complaint_register` (
`c_id` varchar(20) NOT NULL,
`cate_id` int(11) NOT NULL,
`u_id` varchar(10) NOT NULL,
`c_description` longtext NOT NULL,
`c_date` date NOT NULL DEFAULT '1996-05-02',
`s_date` date DEFAULT NULL,
`c_status` int(1) DEFAULT NULL,
`solution_duration` int(11) DEFAULT NULL,
`w_id` int(11) DEFAULT NULL,
`f_date` date DEFAULT NULL,
`satisfaction_level` int(1) DEFAULT NULL,
`f_status` tinyint(1) NOT NULL,
`f_available` tinyint(1) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `complaint_register`
--
INSERT INTO `complaint_register` (`c_id`, `cate_id`, `u_id`, `c_description`, `c_date`, `s_date`, `c_status`, `solution_duration`, `w_id`, `f_date`, `satisfaction_level`, `f_status`, `f_available`) VALUES
('2018-06-04-001', 1, '101', 'Fan Stop Working', '2017-05-04', '2018-06-04', 5, NULL, 1, '2018-06-05', 2, 1, 0),
('2018-06-04-002', 1, '101', 'Power Cut', '2017-02-04', '2014-01-01', 5, NULL, 1, NULL, NULL, 0, 1),
('2018-06-04-003', 2, '101', 'Wall Damaged', '2018-03-04', '2018-06-04', 5, NULL, 10, '2018-06-05', 1, 1, 0),
('2018-06-04-004', 3, '101', 'Tap Leakage', '2018-06-04', '2018-06-05', 5, NULL, 2, '2014-01-01', 3, 1, 0),
('2018-06-04-005', 4, '101', 'Window broken', '2018-06-04', '2018-06-06', 5, NULL, 9, '2014-01-01', 2, 1, 0),
('2018-06-04-006', 5, '101', 'Cleaning', '2018-06-04', '2018-06-22', 4, NULL, 3, NULL, NULL, 0, 1),
('2018-06-04-007', 2, '102', 'Wall Damaged', '2018-06-04', NULL, 2, NULL, 1, NULL, NULL, 0, 0),
('2018-06-04-008', 1, '102', 'Switch Board Problem', '2017-11-04', '2018-06-05', 5, NULL, 1, '2018-06-06', 1, 1, 0),
('2018-06-04-009', 1, '102', 'Fan Stop Working', '2017-03-04', '2014-01-01', 4, NULL, 1, NULL, NULL, 0, 1),
('2018-06-04-010', 1, '102', 'Fan Stop Working', '2017-06-04', '2017-06-26', 4, NULL, 1, NULL, NULL, 0, 1),
('2018-06-04-011', 3, '102', 'Tap Leakage', '2017-06-04', '2017-06-15', 2, NULL, 2, NULL, NULL, 0, 0),
('2018-06-04-012', 4, '102', 'Window broken', '2017-07-04', NULL, 2, NULL, 9, NULL, NULL, 0, 0),
('2018-06-04-013', 1, '103', 'Tube Light Not Working', '2017-02-04', '2014-01-01', 4, NULL, 1, NULL, NULL, 0, 1),
('2018-06-04-014', 2, '103', 'Wall Damaged', '2017-08-04', '2018-06-06', 4, NULL, 10, NULL, NULL, 0, 1),
('2018-06-04-015', 4, '103', 'Window broken', '2017-01-04', '2018-06-06', 4, NULL, 9, NULL, NULL, 0, 1),
('2018-06-04-016', 1, '103', 'Power Cut', '2017-06-04', NULL, 2, NULL, 1, NULL, NULL, 0, 0),
('2018-06-06-001', 3, '102', 'Tap Leakage', '2017-03-06', NULL, 3, NULL, 2, NULL, NULL, 0, 0),
('2018-06-06-002', 2, '102', 'Wall Damaged', '2017-02-15', '2017-02-18', 5, NULL, 10, NULL, NULL, 0, 1),
('2018-06-06-003', 2, '102', 'Toles Broken', '2017-03-06', '2014-01-01', 4, NULL, 10, NULL, NULL, 0, 1),
('2018-06-06-004', 4, '102', 'Door damaged', '2017-06-24', NULL, 4, NULL, 9, NULL, NULL, 0, 1),
('2018-06-06-005', 4, '102', 'Window broken', '2018-06-06', NULL, 2, NULL, 9, NULL, NULL, 0, 0),
('2018-06-06-006', 5, '102', 'Cleaning', '2018-06-06', NULL, 2, NULL, 3, NULL, NULL, 0, 0),
('2018-06-06-007', 1, '106', 'Tube Light Not Working', '2017-07-06', NULL, 2, NULL, 1, NULL, NULL, 0, 0),
('2018-06-06-008', 3, '106', 'Pipe Leakage', '2017-09-06', '2014-01-01', 5, NULL, 2, NULL, NULL, 0, 1),
('2018-06-06-009', 4, '225', 'bed damaged', '2018-08-06', '2014-01-01', 5, NULL, 9, NULL, NULL, 0, 1),
('2018-06-06-010', 2, '225', 'Wall Damaged', '2018-06-06', NULL, 3, NULL, 10, NULL, NULL, 0, 0),
('2018-06-06-011', 3, '104', 'Tap Leakage', '2018-06-06', '2018-06-06', 4, NULL, 2, NULL, NULL, 0, 1),
('2018-06-06-012', 5, '104', 'Cleaning', '2018-06-06', '2018-06-06', 5, NULL, 3, NULL, NULL, 0, 1),
('2018-06-06-013', 3, '201', 'Pipe Leakage', '2018-06-06', '2018-06-06', 5, NULL, 2, NULL, NULL, 0, 1),
('2018-06-06-014', 2, '201', 'Wall Damaged', '2018-06-06', NULL, 2, NULL, 10, NULL, NULL, 0, 0),
('2018-06-06-015', 1, '201', 'Tube Light Not Working', '2018-06-06', NULL, 2, NULL, 1, NULL, NULL, 0, 0),
('2018-06-06-016', 4, '201', 'Door damaged', '2018-06-06', NULL, 3, NULL, 9, NULL, NULL, 0, 0),
('2018-06-06-017', 1, '201', 'Power Cut', '2018-06-06', '2018-06-06', 5, NULL, 1, NULL, NULL, 0, 1),
('2018-06-06-018', 1, '201', 'Tube Light Not Working', '2018-06-06', NULL, 2, NULL, 1, NULL, NULL, 0, 0),
('2018-06-06-019', 1, '201', 'Wiring Problem', '2018-06-06', NULL, 2, NULL, 1, NULL, NULL, 0, 0),
('2018-06-06-020', 1, '201', 'Switch Board Problem', '2018-06-06', NULL, 3, NULL, 1, NULL, NULL, 0, 0),
('2018-06-06-021', 1, '201', 'fan regulator broken', '2018-06-06', '2018-06-06', 4, NULL, 1, NULL, NULL, 0, 1),
('2018-06-06-022', 1, '201', 'fan regulator broken', '2018-06-06', '2018-06-06', 5, NULL, 1, NULL, NULL, 0, 1),
('2018-06-06-023', 1, '106', 'Power Cut', '2018-06-06', NULL, 2, NULL, 1, NULL, NULL, 0, 0),
('2018-06-06-024', 3, '106', 'washbasin pipe jammed', '2018-06-06', NULL, 2, NULL, 2, NULL, NULL, 0, 0),
('2018-06-06-025', 3, '106', 'Water Tank broken', '2018-06-06', NULL, 3, NULL, 2, NULL, NULL, 0, 0),
('2018-06-06-026', 2, '106', 'silling damaged', '2018-06-06', NULL, 2, NULL, 10, NULL, NULL, 0, 0),
('2018-06-06-027', 4, '106', 'Window broken', '2018-06-06', NULL, 3, NULL, 9, NULL, NULL, 0, 0),
('2018-06-06-028', 5, '106', 'Drain full ', '2018-06-06', '2018-06-06', 4, NULL, 3, NULL, NULL, 0, 1),
('2014-01-01-001', 5, '101', 'Cleaning', '2014-01-01', '2018-06-22', 5, NULL, 3, NULL, NULL, 0, 1),
('2018-06-20-001', 3, '101', 'washbasin pipe jammed', '2018-06-20', '2014-01-01', 5, NULL, 2, NULL, NULL, 0, 1),
('2018-06-20-002', 1, '101', 'Power Cut', '2018-06-20', '2014-01-01', 4, NULL, 1, NULL, NULL, 0, 1),
('2018-06-21-001', 1, '101', 'fan regulator broken', '2018-06-21', '2014-01-01', 5, NULL, 1, NULL, NULL, 0, 1),
('2014-01-01-002', 1, '101', 'Tube Light Not Working', '2014-01-01', '2018-06-22', 5, NULL, 1, NULL, NULL, 0, 1),
('2018-06-22-001', 4, '101', 'Door damaged', '2018-06-22', '2018-06-22', 4, NULL, 9, NULL, NULL, 0, 1),
('2018-06-22-002', 1, '101', 'wire damaged', '2018-06-22', NULL, 0, NULL, NULL, NULL, NULL, 0, 0);
-- --------------------------------------------------------
--
-- Table structure for table `deptmst`
--
CREATE TABLE `deptmst` (
`deptid` int(11) NOT NULL,
`Dept_Name` varchar(100) NOT NULL,
`HOD` varchar(50) NOT NULL,
`Pho_No` varchar(20) NOT NULL,
`Email` varchar(40) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `deptmst`
--
INSERT INTO `deptmst` (`deptid`, `Dept_Name`, `HOD`, `Pho_No`, `Email`) VALUES
(1, 'Computer Science', 'Ajaybhai Parikh', '9874563210', 'csdept.gvp@gujaratvidyapith.org'),
(3, 'Social Work', 'Anandiben', '9876541230', 'msw.gvp@gujratvidyapith.org'),
(4, 'Gujrati Vibhag', 'gujrati hod', '9635255852', 'gujrati,gvp@Gmail.com'),
(5, 'Yoga ', 'pal sir', '6369632520', 'yoga@gmail.com'),
(6, 'B.Ed', 'bed hod', '9685321450', 'bed@gmail.com'),
(7, 'Library Science', 'library hod', '96985236210', 'library@gmail.com'),
(8, 'USIC department', 'DharmendraBhai Kadiya', '5656565656', 'usic@gmail.com');
-- --------------------------------------------------------
--
-- Stand-in structure for view `monthly_report`
--
CREATE TABLE `monthly_report` (
`cate_id` int(11)
,`c_date` date
,`c_description` longtext
,`c_status` int(1)
,`w_id` int(11)
);
-- --------------------------------------------------------
--
-- Stand-in structure for view `quarterly_report`
--
CREATE TABLE `quarterly_report` (
`c_status` int(1)
,`c_date` date
,`c_description` longtext
,`cate_id` int(11)
,`w_id` int(11)
);
-- --------------------------------------------------------
--
-- Table structure for table `remark`
--
CREATE TABLE `remark` (
`c_id` varchar(20) NOT NULL,
`w_id` int(11) NOT NULL,
`comment` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `remark`
--
INSERT INTO `remark` (`c_id`, `w_id`, `comment`) VALUES
('2014-01-01-001', 3, 'Some Message to Worker'),
('2014-01-01-002', 1, 'Tube Light'),
('2018-06-04-001', 1, 'Capecitors'),
('2018-06-04-002', 1, 'solve immediately'),
('2018-06-04-003', 10, 'Cement'),
('2018-06-04-004', 2, 'Bring New Tap'),
('2018-06-04-005', 9, 'Urgently Repair'),
('2018-06-04-006', 3, 'complete immediately'),
('2018-06-04-007', 1, 'solve'),
('2018-06-04-008', 1, 'Bring Some Switches'),
('2018-06-04-009', 1, 'solve immediate'),
('2018-06-04-010', 1, 'Bring Some Capecitors'),
('2018-06-04-011', 2, 'solve fast'),
('2018-06-04-012', 9, 'solve fast'),
('2018-06-04-013', 1, 'fhgbfvc'),
('2018-06-04-014', 10, 'Hello Mahesh'),
('2018-06-04-015', 9, 'solve fast'),
('2018-06-04-016', 1, 'solve fast'),
('2018-06-06-001', 2, 'solve fast'),
('2018-06-06-002', 10, 'solve fast'),
('2018-06-06-003', 10, 'solve fast'),
('2018-06-06-004', 9, 'solve fast'),
('2018-06-06-005', 9, 'solve fast'),
('2018-06-06-006', 3, 'solve fast'),
('2018-06-06-007', 1, 'solve fast'),
('2018-06-06-008', 2, 'solve within two days'),
('2018-06-06-009', 9, 'solve fast'),
('2018-06-06-010', 10, 'solve fast'),
('2018-06-06-011', 2, 'solve fast'),
('2018-06-06-012', 3, 'solve fast'),
('2018-06-06-013', 2, 'solve fast and take needy materials from me'),
('2018-06-06-014', 10, 'solve fast'),
('2018-06-06-015', 1, 'solve fast'),
('2018-06-06-016', 9, 'solve fast'),
('2018-06-06-017', 1, 'solve fast'),
('2018-06-06-018', 1, 'solve fast'),
('2018-06-06-019', 1, 'solve fast'),
('2018-06-06-020', 1, 'solve fast'),
('2018-06-06-021', 1, 'solve fast'),
('2018-06-06-022', 1, 'solve fast'),
('2018-06-06-023', 1, 'solve fast'),
('2018-06-06-024', 2, 'solve fast'),
('2018-06-06-025', 2, 'solve fast'),
('2018-06-06-026', 10, 'solve fast'),
('2018-06-06-027', 9, 'dsfsdfds'),
('2018-06-06-028', 3, 'solve fast'),
('2018-06-20-001', 2, 'sfddsfd'),
('2018-06-20-002', 1, 'Power kit'),
('2018-06-21-001', 1, 'Regulator'),
('2018-06-22-001', 9, 'door');
-- --------------------------------------------------------
--
-- Stand-in structure for view `six_monthly_report`
--
CREATE TABLE `six_monthly_report` (
`c_status` int(1)
,`c_date` date
,`c_description` longtext
,`cate_id` int(11)
,`w_id` int(11)
);
-- --------------------------------------------------------
--
-- Table structure for table `studmst`
--
CREATE TABLE `studmst` (
`Stud_ID` varchar(10) NOT NULL,
`Pwd` varchar(20) NOT NULL,
`Stud_Name` varchar(200) NOT NULL,
`stud_name_eng` varchar(200) NOT NULL,
`Email` varchar(40) NOT NULL,
`Add_Yr` varchar(40) NOT NULL,
`Mo` varchar(15) NOT NULL,
`bdate` date NOT NULL,
`Dept_Name` varchar(200) NOT NULL,
`Pro_Name` varchar(20) NOT NULL,
`Loc_Add` varchar(200) NOT NULL,
`Per_Add` varchar(200) NOT NULL,
`Caste` varchar(20) NOT NULL,
`Gender` varchar(20) NOT NULL,
`Grad_Yr` varchar(30) NOT NULL,
`Univ_Name` varchar(150) NOT NULL,
`Campus` varchar(20) NOT NULL,
`user_type` enum('student','department','','') NOT NULL,
`curr_sem` int(2) NOT NULL,
`Repeat_sem` varchar(15) NOT NULL,
`activated` tinyint(1) NOT NULL,
`studImage` blob
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `studmst`
--
INSERT INTO `studmst` (`Stud_ID`, `Pwd`, `Stud_Name`, `stud_name_eng`, `Email`, `Add_Yr`, `Mo`, `bdate`, `Dept_Name`, `Pro_Name`, `Loc_Add`, `Per_Add`, `Caste`, `Gender`, `Grad_Yr`, `Univ_Name`, `Campus`, `user_type`, `curr_sem`, `Repeat_sem`, `activated`, `studImage`) VALUES
('11708118', 'abcd', 'Mehul n zala', 'Mehul n zala', 'mehul@gmail.com', '', '975258745', '0000-00-00', '', '', '', '', '', '', '', '', '', 'student', 0, '', 0, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE `user` (
`u_id` varchar(10) NOT NULL,
`full_name` varchar(60) NOT NULL,
`emp_no` varchar(15) NOT NULL,
`email` varchar(40) NOT NULL,
`pho_no` varchar(13) NOT NULL,
`address` longtext NOT NULL,
`u_type` varchar(10) NOT NULL,
`gender` char(1) NOT NULL,
`user_photo` varchar(45) NOT NULL,
`password` varchar(14) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`u_id`, `full_name`, `emp_no`, `email`, `pho_no`, `address`, `u_type`, `gender`, `user_photo`, `password`) VALUES
('101', 'Shahnawaz Saiyed', '101', 'ssaiyed173@gmail.com', '9726321433', 'Residance 3,\r\nBuilding No. 1,\r\nRoom No 5', 'employee', 'M', 'profile101.jpg', 'Vf2fh2nt7'),
('102', 'Mehul Zala', '102', 'mehulzala245@gmail.com', '9863251432', 'Residance 5,\r\nBuilding No 3,\r\nRoom No 10', 'employee', 'M', 'profile102.jpg', 'mehulzala'),
('103', 'Tarun Patel', '103', 'tarunpatel@gmail.com', '9736975620', 'Residence 1,\r\nBuilding No 6,\r\nRoom No 1', 'employee', 'M', 'profile103.jpg', 'lalupatel'),
('104', 'vipul arvindbhai vohra', '104', 'vipul@gmail.com', '7878787878', '12,Post graduation Boys hostel', 'student', 'M', 'profile104.jpg', 'vipul1234'),
('106', 'megha gopalbhai prajapati', '106', 'megha@gmail.com', '6363636363', '116,Girls hostel', 'student', 'F', 'profile106.jpg', 'megha1234'),
('209', 'pankaj Mathavadiya rameshbhai', '209', 'pankaj@gmail.com', '9696969696', '112,Post graduation hostel', 'student', 'M', 'profile209.png', 'pankaj1234'),
('225', 'Hima Raja Mannar', '225', '11708225.gvp@gujaratvidyapith.org', '9898560296', '116, girls hostel', 'student', 'F', 'profile225.jpg', 'mahi123'),
('203', 'aarti ratanlal prajapati', '203', '11708203.gvp@gujaratvidyapith.org', '9033941949', '116,girls hostel', 'student', 'F', 'profile203.png', 'aarti123'),
('108', 'kajal maheshgiri goswami', '108', 'kajal@gmail.com', '9898675645', '65, girls hostel', 'student', 'F', 'profile.png', 'kajal123'),
('201', 'goswami vishwas kailash', '201', 'vishwas@gmail.com', '9898989898', 'Post Graduation Hostel', 'student', 'M', 'profile201.png', 'vishwas1234');
-- --------------------------------------------------------
--
-- Table structure for table `user_dept`
--
CREATE TABLE `user_dept` (
`u_id` int(11) NOT NULL,
`deptid` int(11) NOT NULL,
`office_location` varchar(50) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `user_dept`
--
INSERT INTO `user_dept` (`u_id`, `deptid`, `office_location`) VALUES
(101, 1, 'Computer Science Office No 3'),
(102, 3, 'Social Work Office No 1'),
(103, 4, 'Gujrati Vibhag Office No 2'),
(104, 1, 'Computer Science HRM department'),
(106, 1, 'Computer Science MCA computer vibhag,gujarat vidya'),
(209, 1, 'Computer Science MCA department,Computer vibhag gu'),
(225, 1, 'Computer Science MCA computer science department.'),
(203, 1, 'Computer Science MCA computer science department'),
(108, 1, 'Computer Science MCA computer science department'),
(201, 8, 'USIC department Usic department');
-- --------------------------------------------------------
--
-- Table structure for table `worker`
--
CREATE TABLE `worker` (
`w_id` int(11) NOT NULL,
`w_name` varchar(60) NOT NULL,
`ph_no` varchar(13) NOT NULL,
`email` varchar(40) NOT NULL,
`address` varchar(100) NOT NULL,
`skill` int(11) NOT NULL,
`w_status` varchar(15) NOT NULL,
`password` varchar(14) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `worker`
--
INSERT INTO `worker` (`w_id`, `w_name`, `ph_no`, `email`, `address`, `skill`, `w_status`, `password`) VALUES
(1, 'Ramesh', '9657452365', 'ramesh@gmail.com', '110,Usmanpura Ahmedabad,\nAhmedabad- 380014', 1, 'Active', ''),
(2, 'Suresh', '9657452366', 'suresh@gmail.com', '92,Incometax Ahmedabad,\nAhmedabad- 380014', 3, 'Active', 'suresh'),
(9, 'Shahnavaz Saiyadmiyan Saiyed', '9726321433', 'ssaiyed173@gmail.com', 'Vansda', 4, 'Active', ''),
(3, 'khushboo', '9786543252', 'khushboo@gmail.com', 'navrangpura', 5, 'Active', '1234567'),
(10, 'Mahesh ', '9874623510', 'mahesh@gmail.com', '92,NavrangpuraAhmedabad, Ahmedabad- 380014 ', 2, 'Active', 'mahesh');
-- --------------------------------------------------------
--
-- Stand-in structure for view `yearly_report`
--
CREATE TABLE `yearly_report` (
`cate_id` int(11)
,`c_date` date
,`c_description` longtext
,`c_status` int(1)
,`w_id` int(11)
);
-- --------------------------------------------------------
--
-- Structure for view `monthly_report`
--
DROP TABLE IF EXISTS `monthly_report`;
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `monthly_report` AS select `complaint_register`.`cate_id` AS `cate_id`,`complaint_register`.`c_date` AS `c_date`,`complaint_register`.`c_description` AS `c_description`,`complaint_register`.`c_status` AS `c_status`,`complaint_register`.`w_id` AS `w_id` from `complaint_register` where ((month(`complaint_register`.`c_date`) = month(curdate())) and (year(`complaint_register`.`c_date`) = year(curdate()))) ;
-- --------------------------------------------------------
--
-- Structure for view `quarterly_report`
--
DROP TABLE IF EXISTS `quarterly_report`;
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `quarterly_report` AS select `complaint_register`.`c_status` AS `c_status`,`complaint_register`.`c_date` AS `c_date`,`complaint_register`.`c_description` AS `c_description`,`complaint_register`.`cate_id` AS `cate_id`,`complaint_register`.`w_id` AS `w_id` from `complaint_register` where ((`complaint_register`.`c_date` >= (now() - interval 2 month)) and (year(`complaint_register`.`c_date`) = year(curdate()))) ;
-- --------------------------------------------------------
--
-- Structure for view `six_monthly_report`
--
DROP TABLE IF EXISTS `six_monthly_report`;
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `six_monthly_report` AS select `complaint_register`.`c_status` AS `c_status`,`complaint_register`.`c_date` AS `c_date`,`complaint_register`.`c_description` AS `c_description`,`complaint_register`.`cate_id` AS `cate_id`,`complaint_register`.`w_id` AS `w_id` from `complaint_register` where ((`complaint_register`.`c_date` >= (now() - interval 5 month)) and (year(`complaint_register`.`c_date`) = year(curdate()))) ;
-- --------------------------------------------------------
--
-- Structure for view `yearly_report`
--
DROP TABLE IF EXISTS `yearly_report`;
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `yearly_report` AS select `complaint_register`.`cate_id` AS `cate_id`,`complaint_register`.`c_date` AS `c_date`,`complaint_register`.`c_description` AS `c_description`,`complaint_register`.`c_status` AS `c_status`,`complaint_register`.`w_id` AS `w_id` from `complaint_register` where (year(`complaint_register`.`c_date`) = year(curdate())) ;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `admin`
--
ALTER TABLE `admin`
ADD PRIMARY KEY (`a_id`),
ADD UNIQUE KEY `email` (`email`);
--
-- Indexes for table `category`
--
ALTER TABLE `category`
ADD PRIMARY KEY (`cate_id`);
--
-- Indexes for table `complaint`
--
ALTER TABLE `complaint`
ADD PRIMARY KEY (`co_id`),
ADD KEY `cate_id` (`cate_id`);
--
-- Indexes for table `complaint_location`
--
ALTER TABLE `complaint_location`
ADD PRIMARY KEY (`loc_id`,`c_id`),
ADD KEY `c_id` (`c_id`);
--
-- Indexes for table `complaint_register`
--
ALTER TABLE `complaint_register`
ADD PRIMARY KEY (`c_id`),
ADD KEY `ct_id` (`cate_id`),
ADD KEY `u_id` (`u_id`),
ADD KEY `w_id` (`w_id`);
--
-- Indexes for table `deptmst`
--
ALTER TABLE `deptmst`
ADD PRIMARY KEY (`deptid`),
ADD UNIQUE KEY `Dept_Name` (`Dept_Name`);
--
-- Indexes for table `remark`
--
ALTER TABLE `remark`
ADD PRIMARY KEY (`c_id`,`w_id`) USING BTREE;
--
-- Indexes for table `studmst`
--
ALTER TABLE `studmst`
ADD PRIMARY KEY (`Stud_ID`);
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`u_id`),
ADD UNIQUE KEY `email` (`email`,`pho_no`);
--
-- Indexes for table `user_dept`
--
ALTER TABLE `user_dept`
ADD PRIMARY KEY (`u_id`,`deptid`),
ADD KEY `deptid` (`deptid`);
--
-- Indexes for table `worker`
--
ALTER TABLE `worker`
ADD PRIMARY KEY (`w_id`),
ADD UNIQUE KEY `ph_no` (`ph_no`),
ADD UNIQUE KEY `email` (`email`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `category`
--
ALTER TABLE `category`
MODIFY `cate_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT for table `complaint`
--
ALTER TABLE `complaint`
MODIFY `co_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23;
--
-- AUTO_INCREMENT for table `complaint_location`
--
ALTER TABLE `complaint_location`
MODIFY `loc_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=52;
--
-- AUTO_INCREMENT for table `deptmst`
--
ALTER TABLE `deptmst`
MODIFY `deptid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT for table `worker`
--
ALTER TABLE `worker`
MODIFY `w_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
JavaScript
|
UTF-8
| 799 | 2.9375 | 3 |
[] |
no_license
|
const puppeteer = require('puppeteer'); //importar pupperteer
puppeteer.launch().then(async browser => { //función en línea que se invoca inmediatamente // se crea el navegador llamndo al método launch
const page = await browser.newPage(); //crea la página de navegador
await page.goto('https://www.mondosonoro.com/') //la pagina creada "visita" la url
await page.screenshot({
path: 'mondosonoro.png'
});
await browser.close();
});
//Creamos el navegador, le decimos vista esta página y devuélveme el contenido
const puppeteer = require('puppeteer');
puppeteer.launch().then(async browser => {
const page = await browser.newPage();
await page.goto('https://www.mondosonoro.com/')
await page.screenshot({
path: 'mondosonoro.png'
});
await browser.close();
});
|
C++
|
UTF-8
| 567 | 2.53125 | 3 |
[] |
no_license
|
#pragma once
#include<iostream>
#include<string>
#include "Player.h"
using namespace std;
/**
*\author Elif GENC (01elifgenc@gmail.com)
*\date 20.12.2017
*/
class VideoPlayer:public Player
{
protected:
/**
\brief Desteklenen bicimler
*/
string* supportedFormats;
public:
/**
\brief Desteklenen format sayilari
*/
int supportedFormatCount;
VideoPlayer(int maxVolumeLevel, string supportedFormats[], int supportedFormatCount);
~VideoPlayer();
void BackWard();
void ForWard();
void EjectMedia();
void MounthMedia(const string& mediaName);
};
|
Markdown
|
UTF-8
| 2,429 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
# The source plugin
The `source` plugin creates a `JAR` file with the project source code. It defines five goals: `aggregate` , `jar` , `test-jar` , `jar-no-fork` , and `test-jar-no-fork` . All these five goals of the source plugin will run under the `package` phase of the `default` lifecycle.
Unlike any of the plugins we discussed before, if you want to execute the `source` plugin with the Maven `default` lifecycle, it has to be defined in the project POM file, shown as follows. **The super POM file** does not define the `source` plugin; it has to be within your Maven project itself:
```xml
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.3</version>
<configuration>
<outputDirectory>
/absolute/path/to/the/output/directory
</outputDirectory>
<finalName>filename-of-generated-jar-file</finalName>
<attach>false</attach>
</configuration>
</plugin>
</plugins>
</build>
...
</project>
```
What is the difference between the `jar` and `source` plugins? Both create JAR files; however, the `jar` plugin creates a `JAR` file from **the binary artifact**, while the `source` plugin creates a `JAR` file from **the source code**.
Small-scale open source projects use this approach to distribute the corresponding source code along with the binary artifacts.
## Practice
经过我的实验,发现:
- (1)需要加上`<executions>`部分的内容,否则无法生成source的JAR包文件。
- (2)生成的source的JAR包,也可以发布到maven的仓库当中去。
```xml
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<id>default-source-jar</id>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
```
|
C
|
UTF-8
| 402 | 3.4375 | 3 |
[] |
no_license
|
#include<stdio.h>
int main(){
int num, soma, hn;
hn=0;
num=1;
while(hn<100){
soma=num;
while(soma!=1 && soma!=4 && soma!=9){
soma=digit(soma);
}
if(soma==1){
printf("%d\n", num);
hn=hn+1;
}num++;
}
return 0;
}
int digit(int v){
int res, sum;
res=0;
sum=0;
while(v>0){
res = v%10;
sum+=(res*res);
v/=10;
}
return sum;
}
|
C++
|
UTF-8
| 5,345 | 3 | 3 |
[
"Apache-2.0"
] |
permissive
|
#ifndef DOCUMENT_CLASS_COMPONENT_H
#define DOCUMENT_CLASS_COMPONENT_H
#include <vector>
#include <string>
#include <tuple>
#include "Atom.hpp"
#include "StringSplitter.hpp"
#include "StringPayload.hpp"
#include "HashFunction.hpp"
#define EDGE_WEIGHT_TYPE float
#define EDGE_WEIGHT_UNIT_VALUE 1.0
/*
* A class that represents a text document and is useful only when updating a class graph with a new document using OpenCL.
* It's key element is a hash table, than can be easily compared in parallel against the hash table of the class graph.
*/
class DocumentClassComponent {
private:
std::size_t hash_table_size;
unsigned int correlation_window;
/* Pointer to the hash table */
EDGE_WEIGHT_TYPE *hash_table;
/* Pointer to unsigned char array, where 1s indicate a new edge that the component brings to the class */
unsigned char *flags;
/* Holds the labels of the edges */
std::vector<std::string> edge_labels;
/* Holds the hash values of the labels */
std::vector<unsigned long> hash_values;
/* Used to split the text document in n-grams */
StringSplitter *splitter;
/* Used to hold the text document in memory */
StringPayload *payload;
/* Hash function to apply on the edges' labels */
HashFunction<std::string, unsigned long> *hash_function;
/*
* Applies the hash function to an edge label.
* \param key The string of the label that is hashed
* \return A pair of the computed hash value and it's corresponding index in the hash table
*/
std::pair<unsigned long, unsigned int> applyHashFunction(std::string key) {
unsigned long hash;
unsigned int index;
hash_function->setArgument(key);
hash = hash_function->apply();
index = hash % hash_table_size;
return {hash, index};
}
/*
* Inserts an new edge in the tables.
* \param index The index of the new edge in the tables
* \param label The label of the new edge
* \param hash The hash value of the label
*/
void insertToTable(unsigned int index, std::string label, unsigned long hash) {
// std::cout << "DocumentClassComponent::insertToTable(): Inserting edge with label '" << label << "'" << std::endl;
if (hash_table[index] == 0) {
edge_labels[index] = label;
hash_values[index] = hash;
hash_table[index] = EDGE_WEIGHT_UNIT_VALUE;
}
else if (label != edge_labels[index]) {
// This is a colllision. Don't update the table in this case. The new edge label won't be inserted.
// TODO Apply a different policy to resolve collisions.
/*
std::cout << "DocumentClassComponent::insertToTable(): Collision for edge "
<< "labels '" << label << "', '" << edge_labels[index] << "' with hash "
<< "value " << index << ". Edge with label '" << label << "' won't be "
<< "inserted in the tables." << std::endl;
*/
}
else {
hash_table[index] += EDGE_WEIGHT_UNIT_VALUE;
}
}
/*
* Creates both direction edges between an atom and every other atom in a vector.
* \param source The atom that participates in all edges
* \param targets A vector containing the atoms to be connected with source
*/
void createEdgesToPrecedingAtoms(Atom<std::string> source, std::vector<Atom<std::string>> targets) {
std::string source_name = source.toString();
std::string label_name, target_name;
unsigned long hash;
unsigned int index;
for (auto& target : targets) {
target_name = target.toString();
label_name = source_name + "___" + target_name;
std::tie(hash, index) = applyHashFunction(label_name);
insertToTable(index, label_name, hash);
label_name = target_name + "___" + source_name;
std::tie(hash, index) = applyHashFunction(label_name);
insertToTable(index, label_name, hash);
}
}
public:
/*
* Constructor.
*/
DocumentClassComponent(std::size_t size, unsigned int win, StringSplitter *split,
StringPayload *payl, HashFunction<std::string, unsigned long> *hf) :
hash_table_size(size), correlation_window(win),
edge_labels(size), hash_values(size),
splitter(split), payload(payl),
hash_function(hf)
{
// () initializes all elements to 0
hash_table = new EDGE_WEIGHT_TYPE[size]();
flags = new unsigned char[size]();
}
/*
* Breaks the payload into atoms (n-grams) and stores the edges between them in the tables. It uses
* the symmetric proximity approach.
*/
void fillTables() {
std::vector<Atom<std::string>> atoms, preceding_atoms;
atoms = splitter->splitPayloadToAtoms(payload);
unsigned int half_win = correlation_window / 2;
for (const auto& atom : atoms) {
createEdgesToPrecedingAtoms(atom, preceding_atoms);
preceding_atoms.push_back(atom);
if (preceding_atoms.size() > half_win) {
preceding_atoms.erase(preceding_atoms.begin());
}
}
}
/*
* Resets the tables so that the same object can be used to represent another document.
*/
void reset() {
for (std::size_t i=0; i<hash_table_size; i++) {
hash_table[i] = 0.0;
flags[i] = (unsigned char)0;
}
}
/*
* Getter functions.
*/
std::size_t getHashTableSize() {
return hash_table_size;
}
EDGE_WEIGHT_TYPE * getHashTable() {
return hash_table;
}
unsigned char * getFlags() {
return flags;
}
std::vector<std::string>& getEdgeLabels() {
return edge_labels;
}
std::vector<unsigned long>& getHashValues() {
return hash_values;
}
};
#endif // DOCUMENT_CLASS_COMPONENT_H
|
Java
|
UTF-8
| 736 | 2.34375 | 2 |
[
"MIT"
] |
permissive
|
package me.shatteredhej.railhack.railhackmod.event.events;
import me.shatteredhej.railhack.railhackmod.event.EventCancellable;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
public class EventDamageBlock extends EventCancellable {
private BlockPos BlockPos;
private EnumFacing Direction;
public EventDamageBlock(BlockPos posBlock, EnumFacing directionFacing) {
this.BlockPos = posBlock;
this.setDirection(directionFacing);
}
public BlockPos getPos() {
return this.BlockPos;
}
public EnumFacing getDirection() {
return this.Direction;
}
public void setDirection(EnumFacing direction) {
this.Direction = direction;
}
}
|
C#
|
UTF-8
| 5,286 | 3.34375 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Native.Csharp.App.Actors
{
/// <summary>
/// 文件操作
/// </summary>
class FileIOActor
{
static string logFile = "log.txt";
/// <summary>
/// 将异常详情写入日志文件
/// </summary>
/// <param name="ex"></param>
public static void log(Exception ex)
{
try
{
log($"{ex.Message}\r\n{ex.StackTrace}");
}
catch { }
}
/// <summary>
/// 写入日志文件
/// </summary>
/// <param name="content"></param>
public static void log(string content)
{
try
{
File.AppendAllText(logFile, $"[{DateTime.Now.ToString("yyyyMMdd HH:mm:ss")}]{content}\r\n", Encoding.UTF8);
}
catch { }
}
/// <summary>
/// 读取单个txt文件内容
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static string readTxtFile(string fileName, Encoding encoding)
{
try
{
using (FileStream file = new FileStream(fileName, FileMode.OpenOrCreate))
{
using (StreamReader reader = new StreamReader(file, encoding))
{
return reader.ReadToEnd();
}
}
}
catch(Exception ex)
{
log(ex);
}
return "";
}
/// <summary>
/// 读取单个txt文件内容,默认utf-8编码
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static string readTxtFile(string fileName)
{
try
{
return readTxtFile(fileName, Encoding.UTF8);
}
catch (Exception ex)
{
log(ex);
}
return "";
}
/// <summary>
/// 读取txt文件中的行字符串,默认utf-8编码
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static ICollection<string> readLines(string fileName)
{
try
{
return readLines(fileName, Encoding.UTF8);
}
catch (Exception ex)
{
log(ex);
}
return null;
}
/// <summary>
/// 读取所有行
/// </summary>
/// <param name="fileName"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static ICollection<string> readLines(string fileName, Encoding encoding)
{
List<string> res = new List<string>();
try
{
using (FileStream file = new FileStream(fileName, FileMode.OpenOrCreate))
{
using (StreamReader r = new StreamReader(file, encoding))
{
string line;
while ((line = r.ReadLine()) != null)
{
line = line.Trim();
if(!string.IsNullOrWhiteSpace(line))
{
res.Add(line);
}
}
}
}
}
catch (Exception ex)
{
log(ex);
}
return res;
}
/// <summary>
/// 用utf-8编码覆盖写入
/// </summary>
/// <param name="fileName"></param>
/// <param name="lines"></param>
public static void writeLines(string fileName, ICollection<string> lines)
{
try
{
File.WriteAllLines(fileName, lines, Encoding.UTF8);
}
catch (Exception ex)
{
log(ex);
}
}
/// <summary>
/// 用utf-8编码覆盖写入
/// </summary>
/// <param name="fileName"></param>
/// <param name="data"></param>
public static void write(string fileName, string data)
{
try
{
File.WriteAllText(fileName, data, Encoding.UTF8);
}
catch (Exception ex)
{
log(ex);
}
}
public static void clearFile(string fileName)
{
try
{
write(fileName, "");
}
catch (Exception ex)
{
log(ex);
}
}
public static void appendLine(string fileName, string line)
{
try
{
File.AppendAllText(fileName, line + "\r\n", Encoding.UTF8);
}
catch (Exception ex)
{
log(ex);
}
}
}
}
|
Markdown
|
UTF-8
| 8,480 | 2.765625 | 3 |
[
"Apache-2.0"
] |
permissive
|
Congenio: Configuration Generation Language
========================================================
The Congenio Configuration Generation Language is a tool
to maintain and generate configuration values (primarily) for experiments
in a reproducible manner.
See [User's guide](https://github.com/tatemura/congenio/wiki/UsersGuide) for details.
Motivation
-----
A configuration management utility tool, such as Puppet, enables us
to deploy and configure a complex system (that consists of multiple
components such as DBMS and application servers) automatically. Once
we describe configuration, we can repeat the same deployment many times.
But what if we need to repeat it with many different combinations of configuration?
In our case, we needed to conduct experiments on the performance of
complex systems (performance evaluation, tuning, capacity planning,...), which
involve a large number of configuration options to explore. Writing scripts
was one approach, which tends to bury important parameters into the script code,
quickly making experiments no longer manageable and repeatable.
The configuration generation language was developed to bring manageability
and reproducibility to such experiments with complex systems.
Usage
-----
It can be used either as a stand-alone command or as a library embedded in
other programs.
### Command-line (use in a script)
A command line tool "congen" converts a config document into a
set of resolved documents (in either XML or JSON format).
% congen --outdir config --format json experiment-001.xml
% less config/out/*.json
A custom script (e.g., shell or python) can use
this tool to generate and use resolved documents as experiment parameters.
(See [wiki](https://github.com/tatemura/congenio/wiki/CommandLineInterface)
on the command line interface.)
### Embedded (use as a library)
The library provides Java API to consume the generated configuration parameters.
In fact, the Congenio language is originally developed as a library within
our experiment platform [Strudel](https://github.com/tatemura/strudel)
(which runs various workloads on the system to be tested).
### Executor (run as a script)
[TODO] In a future release (v0.2.X), we plan to add
features to run a simple executor
that invokes external scripts (e.g. shell or Python scripts, Puppet)
with generated parameters.
Language Features
-----------------
The followings are the main features of the language:
* inheritance (@extends attribute): combining and modifying component
documents.
* document unfolding (foreach element): generating multiple configuration
documents (each of which is used for one experiment setting).
* reference resolution (@ref attribute)
* value expression (@exp attribute)
With @extends attribute, an experiment document can refer to existing templates
(that define various components such as benchmarks and database configuration
parameters) and customize the default values of these templates. With foreach
elements, an experiment document can generate a set of documents, each of
which corresponds to one execution run with a specific set of parameters.
Attributes @ref and @exp are useful to generate component parameters that
are related to each other.
See [wiki](https://github.com/tatemura/congenio/wiki/LanguageFeatures) for details.
### Inheritance (@extends)
Suppose you have a file jpa-mysql.xml:
<database>
<name>test</name>
<params>
<property name="javax.persistence.jdbc.driver">
com.mysql.jdbc.Driver
</property>
<property name="javax.persistence.jdbc.url">
jdbc:mysql://localhost:3306
</property>
</params>
</database>
Another document can refer to this document with an "extends"
attribute to generate a modified version of the original document.
For example, the following XML will extend the jpa-mysql.xml with a new
name:
<database extends="jpa-mysql">
<name>mydb</name>
</database>
After resolution of inheritance the document will become as follows:
<database>
<name>mydb</name>
<params>
<property name="javax.persistence.jdbc.driver">
com.mysql.jdbc.Driver
</property>
<property name="javax.persistence.jdbc.url">
jdbc:mysql://localhost:3306
</property>
</params>
</database>
A special extend reference "." can be used to
extend values that are not direct children:
<database extends="jpa-mysql">
<name>mydb</name>
<params extends=".">
<property name="javax.persistence.jdbc.url">
jdbc:mysql://myserver.example.com:3306
</property>
</params>
</database>
See [ExtendsAttribute](https://github.com/tatemura/congenio/wiki/ExtendsAttribute)
wiki page for more information.
### Reference (@ref)
A reference ("ref" attribute) is provided to refer to a value
(subtree) within the same document. It is useful to describe
configuration that comprises of multiple components that share
the same values.
The following example is a configuration of an experiment that
uses three components (database, workload, startup). Configuration
of these components require the URL of the same database. The value
of URL is described at one place (dbUrl) and these components
use "ref" attributes that refer to it.
<experiment>
<dbUrl>jdbc:mysql://localhost:3306</dbUrl>
<database extends="jpa-mysql">
<name>mydb</name>
<params extends=".">
<property name="javax.persistence.jdbc.url"
ref="dbUrl"/>
</params>
</database>
<workload extends="my-workload">
<database ref="Database"/>
</workload>
<startup extends="start-config">
<db ref="dbUrl"/>
</startup>
</experiment>
Now, in order to run a modified experiment with a new
database URL, a document can extend only one element:
<experiment extends="experiment-templ">
<dbUrl>jdbc:mysql://myserver.example.com:3306</dbUrl>
</experiment>
See [RefAttribute](https://github.com/tatemura/congenio/wiki/RefAttribute)
wiki page for more information.
### Value expression (@exp)
Although a reference enables reuse of the same value in different
components, it does not work when a component needs a slightly
different value. For example, one component
may need a JDBC URL (e.g, "jdbc:mysql://localhost:3306")
while another component needs another URL of some service
on the same host (e.g., "http://localhost:8080/myservice").
We just want
to share the host name of the server used by these components:
<experiment>
<host>localhost</host>
...
</experiment>
By using a value expression (concat), an URL of
JDBC can be generated from a reference:
<property name="javax.persistence.jdbc.url"
exp="concat('')">
<h>jdbc:mysql://</h>
<h ref="host"/>
<h>:3306</h>
</property>
See [ExpAttribute](https://github.com/tatemura/congenio/wiki/ExpAttribute)
wiki page for more information.
### Document unfolding (foreach)
A foreach element is used
to create a series of experiments with slightly different
parameters from one document.
<benchmarkParam>
<foreach name="scale">
<s><clients>10</clients><users>100000</users></s>
<s><clients>20</clients><users>200000</users></s>
<s><clients>40</clients><users>400000</users></s>
<s><clients>80</clients><users>800000</users></s>
</foreach>
<foreach name="servers" sep=",">5,10</foreach>
<benchmarkParam>
The above document is unfolded into 8 documents (4 x 2), the one
of which is as follows:
<benchmarkParam>
<scale><clients>10</clients><users>100000</users></scale>
<servers>5</servers>
</benchmarkParam>
See [ForeachElement](https://github.com/tatemura/congenio/wiki/ForeachElement)
wiki page for more information.
Installation
------------
Use Maven to install an artifact to your local repository in order to
use Congenio as a library:
% git checkout v0.1.0
% mvn -DskipTests install
To use a command line tool, running "mvn -DskipTests package" is enough to generate
what is required. The distribution package is in the "target" directory:
% ls target/congenio-*-dist.tar.gz
Unpack the package at an appropriate location and set up your path to
bin/congen. You can also use a symbolic link to this file:
% sudo ln -s /usr/local/share/congenio/congenio-0.1.0/bin/congen /usr/local/bin
Requirements
------------
Java >= 1.6
License
-------
Code licensed under the Apache License Version 2.0.
|
C#
|
UTF-8
| 3,118 | 2.8125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Threading;
namespace Lab6
{
public class Bartender
{
private Action<string> Callback;
private ConcurrentQueue<Patron> PatronQueue;
private ConcurrentQueue<Patron> BartenderQueue;
private ConcurrentStack<Glass> DirtyGlassStack;
private ConcurrentStack<Glass> CleanGlassStack;
private ConcurrentStack<Chair> FreeChairStack;
public bool BarIsOpen { get; set; }
private int bartenderSpeed = 1;
public void Work(ConcurrentQueue<Patron> patronQueue, ConcurrentQueue<Patron> bartenderQueue, Action<string> callback, Action<string> PatronListCallback,
ConcurrentStack<Glass> cleanGlassStack, ConcurrentStack<Glass> dirtyGlassStack,
bool bartenderIsWorking, ConcurrentStack<Chair> freeChairStack, ConcurrentQueue<string> uiPatronCountDequeue)
{
this.Callback = callback;
this.PatronQueue = patronQueue;
this.BartenderQueue = bartenderQueue;
this.DirtyGlassStack = dirtyGlassStack;
this.CleanGlassStack = cleanGlassStack;
this.FreeChairStack = freeChairStack;
this.BarIsOpen = bartenderIsWorking;
Task.Run(() =>
{
while (BarIsOpen || !uiPatronCountDequeue.IsEmpty)
{
if (!PatronQueue.IsEmpty && !BartenderQueue.IsEmpty)
{
if (!cleanGlassStack.IsEmpty)
{
cleanGlassStack.TryPop(out Glass g);
Thread.Sleep(1000 / bartenderSpeed);
Callback($"The Bartender is fetching {BartenderQueue.First().Name} a glass.");
Thread.Sleep(3000 / bartenderSpeed);
Callback($"The Bartender is pouring {BartenderQueue.First().Name} a beer.");
Thread.Sleep(3000 / bartenderSpeed);
PatronQueue.FirstOrDefault().SitDown(PatronListCallback, DirtyGlassStack, FreeChairStack, PatronQueue, uiPatronCountDequeue, bartenderSpeed);
BartenderQueue.TryDequeue(out Patron p);
}
else
{
Callback("The Bartender is waiting for Glasses.");
Thread.Sleep(5000);
}
}
else
{
Callback("The Bartender is waiting for Patrons.");
Thread.Sleep(5000);
}
}
Callback("The Bartender goes home.");
});
}
public void StopServing()
{
BarIsOpen = false;
}
public void ChangeSpeed(int speed)
{
this.bartenderSpeed = speed;
}
}
}
|
Python
|
UTF-8
| 1,293 | 3.078125 | 3 |
[] |
no_license
|
import pickle
_phon_dicts = pickle.load(open('./resources/phon-dicts.pydb','rb'))
def translate(form,source_alpha='jm',target_alpha='elp',cmu_delim='.'):
"""
Accepts a phonological transcription/form and converts it from one phonetic
encoding to another.
form: string, required
source_alpha: string, optional
name of the source alphabet/encoding
target_alpha: string, optional
name of the target encoding
cmu_delim: string, optional
CMU transcriptions need a delimiter because they use two-letter codes;
cmu_delim is the input/output delimiter when 'cmu' is source/target
Currently supported encodings: 'jm','elp','cmu'
NOTE: These source -> target -> source may not return the same form, as some
codes ('elp','jm') make finer distinctions than other; for example, 'cmu' has
only one schwa and 'jm' and 'elp' have two.
"""
if target_alpha is 'cmu':
return cmu_delim.join([_phon_dicts[(source_alpha,target_alpha)][x] for x in form])
if source_alpha is 'cmu':
return ''.join([_phon_dicts[(source_alpha,target_alpha)][x] for x in form.split(cmu_delim)])
# no delimiters necessary in input or output
return ''.join([_phon_dicts[(source_alpha,target_alpha)][x] for x in form])
|
Python
|
UTF-8
| 157 | 3.515625 | 4 |
[] |
no_license
|
import math
x = 2
print(math.pi)
if x >= -math.pi and x <= math.pi:
y = math.cos(3*x)
print(y)
elif x < -math.pi or x > math.pi:
y = x
print(y)
|
Java
|
UTF-8
| 657 | 3.265625 | 3 |
[] |
no_license
|
package vista;
import app.InputController;
public class Menu implements Vista {
private String[] options;
private int seleccion = 1;
public Menu (String... options)
{
this.options = options;
}
@Override
public void mostrar()
{
System.out.println("/ ------------------------- \\");
for (int i = 0; i < options.length; i++) {
System.out.println(" "+(i+1) + " - " + options[i]);
}
System.out.println("\\ ------------------------- /");
seleccion = InputController.readInteger(1, options.length);
}
/**
* Elemento seleccionado tras la llamada a mostrar()
*/
public int seleccionado()
{
return seleccion;
}
}
|
PHP
|
UTF-8
| 1,985 | 2.75 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
<?php
class Pagination_model extends CI_Model
{
function __construct() {
parent::__construct();
}
private $total;
private $offset;
private $search_data;
private $pre_url;
private $num_page;
private $limit;
public function create_link($config)
{
$this->initialize($config);
$total_page = ceil($this->total/$this->limit);
$current_page = $this->offset/$this->limit + 1;
$links = array();
if($total_page > 1)
{
if($current_page != 1)
{
$links['First'] = '<li>'.anchor($this->url_maker(0),'First').'</li>';
$links['Prev'] = '<li>'.anchor($this->url_maker($this->offset - $this->limit),'Prev').'</li>';
}
$i = (($current_page - $this->num_page) < 0)?0:($current_page - $this->num_page);
$end = (($current_page + $this->num_page) > $total_page)?$total_page:($current_page + $this->num_page);
for(;$i < $end;++$i)
{
if(($i+1) == $current_page)
{
$links[$i+1] = '<li class="active">'.anchor($this->url_maker($this->limit*$i),$i+1).'</li>';
}
else
{
$links[$i+1] = '<li>'.anchor($this->url_maker($this->limit*$i),$i+1).'</li>';
}
}
if($current_page != $total_page)
{
$links['Last'] = '<li>'.anchor($this->url_maker($this->limit*($total_page-1)),'Last').'</li>';
$links['Next'] = '<li>'.anchor($this->url_maker($this->offset+$this->limit),'Next').'</li>';
}
}
return $links;
}
private function initialize($config) {
$this->total = $config['total'];
$this->offset = isset($config['offset'])?$config['offset']:0;
$this->search_data = $config['search_data'];
$this->pre_url = $config['pre_url'];
$this->limit = isset($config['limit'])?$config['limit']:10;
$this->num_page = isset($config['limit'])?$config['limit']:4;
}
private function url_maker($offset)
{
$data = $this->search_data ;
foreach ($data as $key => $value) {
if(empty($value))
unset($data[$key]);
}
$data['offset']=$offset;
return $this->pre_url.'?'.http_build_query($data);
}
}
|
Java
|
UTF-8
| 418 | 1.695313 | 2 |
[] |
no_license
|
package org.densyakun.forge.japanpack;
import org.densyakun.forge.japanpack.tileentity.TileEntityTataraFurnace;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.world.World;
public class JapanPackCommonProxy {
public World getClientWorld() {
return null;
}
public void registerTileEntity() {
GameRegistry.registerTileEntity(TileEntityTataraFurnace.class, "TileEntityTataraFurnace");
}
}
|
Java
|
UTF-8
| 7,629 | 2.25 | 2 |
[] |
no_license
|
/*
* Copyright (C) 2019 DBC A/S (http://dbc.dk/)
*
* This is part of ee-remote-admin-access
*
* ee-remote-admin-access is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ee-remote-admin-access is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package dk.dbc.remoteadminaccess;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.ejb.LocalBean;
import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.util.Collections.EMPTY_LIST;
/**
* Bean that exposes remote access verification methods based upon the
* environment variables $X_FORWARDED_FOR and $ADMIN_IP
* <p>
* Currently only supports IPv4
*
* @author Morten Bøgeskov (mb@dbc.dk)
*/
@Singleton
@LocalBean
@Startup
@Lock(LockType.READ)
public class RemoteAccessRules {
private static final Logger log = LoggerFactory.getLogger(RemoteAccessRules.class);
private static final long IPV4_MAX = 0xffffffffL;
private static final long IPV4_BAD = 0x10DEADBEEFL;
private List<IPRange> allowedProxyIpRanges;
private List<IPRange> allowedAdminIpRanges;
@PostConstruct
public void init() {
this.allowedProxyIpRanges = listFromEnv("X_FORWARDED_FOR");
log.trace("allowedProxyIpRanges = " + allowedProxyIpRanges);
this.allowedAdminIpRanges = listFromEnv("ADMIN_IP");
log.trace("allowedAdminIpRanges = " + allowedAdminIpRanges);
}
/**
* Resolve a remote ip address from a request processing optional
* x-forwarded-for headers
*
* @param peer ipv4 peer address
* @param xForwardedFor request header for proxy resolve. X-Forwarded-For
* syntax is client-ip[, proxy-ip ...]
* @return peer ip address
*/
public String remoteIp(String peer, String xForwardedFor) {
log.trace("resolve remote ip for: {}, (forwarded-for) {}", peer, xForwardedFor);
long peerIp = ipOf(peer);
if (peerIp == IPV4_BAD)
return peer;
if (xForwardedFor != null && !xForwardedFor.isEmpty() &&
inIpRange(peerIp, allowedProxyIpRanges)) {
// Proxy connected to us, and has x-forwarded-for set
String[] xForwardedFors = xForwardedFor.split(",");
// Ensure (optional) proxies are in our allowed list
int pos = xForwardedFors.length;
while (--pos > 0) {
String proxy = xForwardedFors[pos].trim();
long proxyIp = ipOf(proxy);
// if proxy isnt
if (proxyIp == IPV4_BAD)
return peer;
if (!inIpRange(proxyIp, allowedProxyIpRanges)) {
return proxy; // Proxy is not in allowed list - proxy is our peer
}
}
return xForwardedFors[pos].trim();
}
return peer;
}
/**
* Check if an ip (from
* {@link #remoteIp(java.lang.String, java.lang.String)} is in the admin ip
* list
*
* @param peer ip number as string
* @return if admin access is allowed
*/
public boolean isAdminIp(String peer) {
long ip = ipOf(peer);
return ip != IPV4_BAD && inIpRange(ip, allowedAdminIpRanges);
}
/**
* Convert a comma separated list of ip(-ranges) to an {@link IpRange} list
*
* @param env environment variable value
* @return List of IpRanges that are in the input
*/
private List<IPRange> listFromEnv(String env) {
String xForwardedFor = getEnv(env);
if (xForwardedFor == null || xForwardedFor.trim().isEmpty())
return EMPTY_LIST;
return Arrays.stream(xForwardedFor.split(","))
.map(String::trim)
.filter(s -> !s.isEmpty())
.map(RemoteAccessRules::ipRange)
.filter(m -> m != null)
.collect(Collectors.toList());
}
/**
* System getenv wrapper for unittest
*
* @param env name of environment variable
* @return env value
*/
String getEnv(String env) {
return System.getenv(env);
}
/**
* Check if an ip address is in a list of ranges
*
* @param ip ip to test for
* @param ranges ip ranges
* @return if ip is covered by any range
*/
private static boolean inIpRange(long ip, List<IPRange> ranges) {
return ranges.stream().anyMatch(i -> i.isInRange(ip));
}
/**
* Convert a string of host/net/ranges to a list
*
* @param hosts ip(-range)/net list
* @return List of ranges
*/
private static IPRange ipRange(String hosts) {
if (hosts.contains("-")) {
String[] parts = hosts.split("-", 2);
long ipMin = ipOf(parts[0]);
long ipMax = ipOf(parts[1]);
if (ipMin == IPV4_BAD || ipMax == IPV4_BAD) {
log.error("Invalid ipv4 range: " + hosts);
return null;
}
return new IPRange(ipMin, ipMax);
} else if (hosts.contains("/")) {
String[] parts = hosts.split("/", 2);
long ip = ipOf(parts[0]);
if (ip == IPV4_BAD) {
log.error("Invalid ipv4 net: " + hosts);
return null;
}
int mask = Integer.parseInt(parts[1], 10);
if (mask < 0 || mask > 32 || !parts[1].replaceAll("[0-9]", "").isEmpty()) {
log.error("Invalid ipv4 net: " + hosts);
return null;
}
long net = ( IPV4_MAX << ( 32 - mask ) ) & IPV4_MAX;
return new IPRange(ip & net, ( ip | ~net ) & IPV4_MAX);
} else {
long ip = ipOf(hosts);
if (ip == IPV4_BAD) {
log.error("Invalid ipv4 address: " + hosts);
return null;
}
return new IPRange(ip, ip);
}
}
/**
* Convert a ipv4 address into a long value
*
* @param addr ipv4 address
* @return 32-bit in a long
*/
private static long ipOf(String addr) {
if (addr.replaceAll("[0-9.]", "").isEmpty()) {
String[] parts = addr.split("\\.");
if (parts.length != 4)
return IPV4_BAD;
return Arrays.stream(parts).mapToInt(Integer::parseUnsignedInt).reduce(0, (l, r) -> ( l << 8 ) + r) & IPV4_MAX;
} else {
return IPV4_BAD;
}
}
/**
* Class that represents an ipv4 range
*/
private static class IPRange {
private final long min;
private final long max;
private IPRange(long min, long max) {
this.min = min;
this.max = max;
}
private boolean isInRange(long ip) {
return ip >= min && ip <= max;
}
@Override
public String toString() {
return String.format("(%08x-%08x)", min, max);
}
}
}
|
Shell
|
UTF-8
| 1,008 | 3.390625 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"OpenPBS-2.3"
] |
permissive
|
#!/bin/sh
# This file is bilingual. The following shell code finds our preferred python.
# Following line is a shell no-op, and starts a multi-line Python comment.
# See https://stackoverflow.com/a/47886254
""":"
# preferred pythons for running buildtest
PREFERRED_PYTHONS="python3 python"
# Find a suitable python interpreter (adapt for your specific needs)
for cmd in "${BUILDTEST_PYTHON:-}" ${PREFERRED_PYTHONS} ; do
if command -v > /dev/null "$cmd"; then
export BUILDTEST_PYTHON="$(command -v "$cmd")"
exec "${BUILDTEST_PYTHON}" "$0" "$@"
fi
done
echo "==> Error: buildtest could not find a python interpreter!" >&2
exit 1
":"""
import os
import sys
buildtest_file=os.path.realpath(os.path.expanduser(__file__))
prefix=os.path.dirname(os.path.dirname(buildtest_file))
sys.path.insert(0, prefix)
if sys.version_info[:3] < (3, 8, 0):
sys.exit("buildtest requires Python 3.8.0 or higher.")
from buildtest.main import main
if __name__ == "__main__":
sys.exit(main())
|
PHP
|
UTF-8
| 2,490 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace Shaparak\Service\Requests;
use Carbon\Carbon;
use Exception;
use Shaparak\Database\models\Merchant;
use Shaparak\Database\models\Response;
use Shaparak\Service\Requests\WriteRequest\ShopProviderRegister;
use Shaparak\Service\Requests\WriteRequest\TerminalRegister;
class Shaparak
{
public $request;
public function make($requestType)
{
$this->request = $requestType;
return $this;
}
public function getRequest()
{
return $this->request;
}
public function readRequest(Response $response)
{
$request = resolve($this->request);
$response = $request->callRequest($response);
$responses = json_decode($response, true);
if (!$responses) {
throw new Exception("shaparak error:" . $response);
}
$shaparakResponse = [];
foreach ($responses as $response) {
$responseModel = Response::where('tracking_number', $response["trackingNumber"])->first();
$responseModel->update([
'request_date' => Carbon::createFromTimestamp($response['requestDate'] / 1000),
'request_rejection_reasons' => serialize($response["requestRejectionReasons"]),
'status' => $response['status'],
]);
$shaparakResponse[] = $responseModel;
}
return $shaparakResponse;
}
public function sendRequest($merchant, $shops, $contracts = null)
{
$requestClass = resolve($this->request);
$response = $requestClass->callRequest($merchant, $shops, $contracts);
$responses = json_decode($response, true);
if (!$responses) {
throw new Exception("shaparak error:" . $response);
}
foreach ($responses as $response) {
$response = Response::create([
'data' => serialize(json_decode(json_encode($requestClass->getData()))),
'request_type' => $requestClass->getRequestTypeCode(),
'merchant_id' => $requestClass->getMerchantId(),
'tracking_number_psp' => $response["trackingNumberPsp"],
'tracking_number' => $response["trackingNumber"],
'request_rejection_reasons' => serialize($response["requestRejectionReasons"]),
]);
}
return $response;
}
}
|
Java
|
UTF-8
| 709 | 3.09375 | 3 |
[] |
no_license
|
package br.com.treinaweb.projeto.classes;
public class Cliente {
private String nome;
private String nomeMae;
private String cpf;
private String rg;
public void cadastroCliente(String nome, String cpf,
String rg, String nomeMae){
this.nome = nome;
this.cpf = cpf;
this.rg = rg;
this.nomeMae = nomeMae;
}
public String exibirDados(){
String dados = "\n\t ----- Dados Pessoais -----\n";
dados += "Nome: " + this.nome + "\n";
dados += "CPF: " + this.cpf + "\n";
dados += "RG: " +this.rg + "\n";
dados += "Nome da mãe: " + this.nomeMae;
return dados;
}
}
|
Python
|
UTF-8
| 406 | 4.4375 | 4 |
[] |
no_license
|
# Bubble Sort
def bubbleSort(arr):
for i in range(len(arr)-1):
for j in range(len(arr)-1-i):
if arr[j] > arr[j+1]:
swap(arr,j,j+1)
return arr
def swap(arr, x, y):
temp = arr[x]
arr[x] = arr[y]
arr[y] = temp
# Driven Program
if __name__ == "__main__":
array = [2,5,6,1,4,7,9,3]
print("Unsorted Array: ", array)
print(bubbleSort(array))
|
C++
|
UTF-8
| 1,321 | 3.6875 | 4 |
[] |
no_license
|
using namespace std;
#include <iostream>
#include <limits>
#include <vector>
class CoinChange {
public:
int countChange(const vector<int> &denominations, int total) {
// minimum number of coins needed to make a change of T
int n = (int)(denominations.size());
// minimum number of coins needed to make a sum
vector<int> dp(total + 1, 0);
for(int i = 0; i <= total; i++)
dp[i] = (1<<25);
// base case
dp[0] = 0;
// here we have to minimize
for(int i = 0; i < n; i++) {
for(int w = 0; w <= total; w++) {
int prev = w - denominations[i];
// 2 choices here ....
// either you are going to take the ith element
// or you are not going to take the ith element
// note: you are taking the element again
// item = 2
// w = 4, dp[2] = 1
dp[w] = min(dp[w], dp[prev] + 1);
}
}
return dp[total];
}
};
int main(int argc, char *argv[]) {
CoinChange *cc = new CoinChange();
vector<int> denominations = {1, 2, 3};
cout << cc->countChange(denominations, 5) << endl;
cout << cc->countChange(denominations, 11) << endl;
cout << cc->countChange(denominations, 7) << endl;
denominations = vector<int>{3, 5};
cout << cc->countChange(denominations, 7) << endl;
delete cc;
}
|
PHP
|
UTF-8
| 1,045 | 2.921875 | 3 |
[] |
no_license
|
<?php
namespace Chap;
use Chap\DB;
class Chapter
{
public function createDB()
{
$parsed = explode(';', file_get_contents('parse_file'));
DB::insertIntoDB($parsed);
}
public function getResult(){
$to_obj = array_unique((new DB)->getToObjectFromDB(), SORT_REGULAR);
if (empty($to_obj))
return;
foreach ($to_obj as $obj)
{
$active_dates[$obj['TO_OBJECT']] = (new DB)->getActiveDateFromDB($obj['TO_OBJECT']);
}
foreach($active_dates as $date)
{
$generator = $this->getTime($date);
foreach ($generator as $gen)
{
$result = $gen;
}
$val[] = $result;
}
$keys = array_keys($active_dates);
$final = array_combine($keys, $val);
return $final;
}
private function getTime($date)
{
foreach ($date as $d){
$val = (strtotime($time ?? 0) < strtotime($d['ACTIVATION_DATE']));
if ($val){
$new_time = $d['ACTIVATION_DATE'];
} else {
$new_time = $time;
}
$time = date("Y-m-d H:i:s", strtotime($new_time . " + 60 days"));
yield $time;
}
}
}
|
Python
|
UTF-8
| 446 | 4.0625 | 4 |
[] |
no_license
|
# Volume of circle
from math import pi
def volume_of_circle(radius, pi):
return 4 / 3 * pi * radius ** 3
r = int(input('Enter the radius : '))
result = volume_of_circle(r,pi)
print(result)
'''
# lohit's answer
def area(radius):
return 3.142 * radius * radius
def volume(area, length):
print(area*length)
radius = int(input('Enter the radius :'))
length = int(input('Enter the length :'))
volume(area(radius), length)
'''
|
PHP
|
UTF-8
| 558 | 2.75 | 3 |
[] |
no_license
|
<?php
use PHPUnit\Framework\TestCase;
class UserTest extends TestCase {
public function testReturnsFullName() {
// set to autoload
//require("User.php");
$user = new User;
$user->firstName = "John";
$user->lastName = "Tiger";
$this->assertEquals('John Tiger', $user->GetFullName());
}
public function testFullNameEmptyByDefault() {
$user = new User;
$this->assertEquals('', $user->GetFullName());
}
public function testTrueIsTrue() {
$trueFalse = true;
$this->assertTrue(true,$trueFalse);
}
}
|
Python
|
UTF-8
| 7,184 | 2.984375 | 3 |
[] |
no_license
|
import numpy as np
from dtw import *
import matplotlib.pyplot as plt
import argparse
import os
def dtw_find_seq(path_A=None, path_B=None):
# 动态规划对齐两个序列
# path_A='ATCGGGGGTACACCTTT'
# path_B='AAAAAAAATTTTTCGGGGGGGGGGGGTAAAACCCA'
mat_path = np.zeros([len(path_B), len(path_A)])
print('path_A len:{}'.format(len(path_A)))
sum_loss = 0
B_start = 0
A_corr = 0
for A_inx in range(len(path_A)):
A = path_A[A_inx]
B_corr = B_start
for B_inx in range(B_corr, len(path_B)):
B = path_B[B_inx]
if np.abs(ord(B)-ord(A)) < 1:
sum_loss += np.abs(ord(B)-ord(A))
mat_path[B_inx][A_inx] = 1
B_start = B_inx
try:
if path_A[A_inx+1] == path_B[B_inx+1]:
A_corr += 1
print('next equal {}:{}'.format(B_inx+1, A_inx+1))
break
else:
pass
except:
pass
else:
pass
if B_inx+1 == len(path_B) and path_A[A_inx+1] != path_B[B_inx]:
break
print(A_corr)
# print(mat_path)
if A_corr >= len(path_A)//2:
# A,B具有相关性,A可视为B的子序列
return (A_corr+1)/len(path_A), True
if sum_loss < 1:
return mat_path, True
else:
return mat_path, False
# 动态规划寻找两个相似序列,相似率大于阈值视为相似
# 该函数使用递归寻找,调用对其函数
# 仅适用于无跳过,且开始序列相同
def dtw_find_ralative_seq(path_A, path_B):
ret = dtw_find_seq(path_A, path_B)
print(ret)
pass
def test1():
path_A = 'ATCGGGGGTACACCTT'
path_B = 'ATCGGGG'
dtw_find_ralative_seq(path_A, path_B)
# 序列信号动态时间规整
path_A = 'ATCGGAG'
path_B = 'ATCGGGGGTACACCTT'
def dynamic_find_sub_seq(path_A, path_B):
loss_mat = np.zeros((len(path_A)+1, len(path_B)+1))
for i in range(1, len(path_A)+1):
for j in range(1, len(path_B)+1):
mki = loss_mat[i-1][j]
mkj = loss_mat[i][j-1]
if path_A[i-1] == path_B[j-1]:
mij = loss_mat[i-1][j-1]+1
else:
mij = loss_mat[i-1][j-1]-1
loss_mat[i][j] = max(mki, mkj, mij, 0)
return loss_mat
def mat_trace_back(ref_seq, find_seq, loss_mat):
x, y = np.where(np.max(loss_mat) == loss_mat)
print(x[0], y[0])
def test2():
loss_mat = dynamic_find_sub_seq(path_A, path_B)
mat_trace_back(path_A, path_B, loss_mat)
# 电平信号动态时间扭曲,信号
def dynamic_find_pass(ref_seq, find_seq):
INF = 100000000
loss_mat = np.zeros([len(ref_seq), len(find_seq)])*INF
# 花费矩阵,cost
for row in range(len(ref_seq)):
for column in range(len(find_seq)):
current_level_sub = np.abs(ref_seq[row]-find_seq[column])
if row == 0 and column == 0:
loss_mat[row][column] = current_level_sub
elif row == 0 and column != 0:
loss_mat[row][column] = current_level_sub + \
loss_mat[row][column-1]
elif row != 0 and column == 0:
loss_mat[row][column] = current_level_sub + \
loss_mat[row-1][column]
else:
loss_mat[row][column] = current_level_sub+min(
loss_mat[row-1][column-1], loss_mat[row-1][column], loss_mat[row][column-1])
# print(loss_mat)
return loss_mat
def trace_back_pass_path(ref_seq, find_seq, loss_mat):
# 回溯找路径
# 最右下角即为最小距离,根据它反推途径
INF = 100
path_min = []
min_cost = []
row = len(ref_seq)-1
column = len(find_seq)-1
min_cost.append(loss_mat[row][column])
# path_min.append((row,column))
path_min = [[row, column]]+path_min
while(row != 0 or column != 0):
Mij = loss_mat[row-1][column-1]
Mki = loss_mat[row-1][column]
Mkj = loss_mat[row][column-1]
if min(Mij, Mki, Mkj) == Mij:
# min_cost=Mij
min_cost.append(Mij)
# path_min.append((row-1,column-1))
path_min = [[row-1, column-1]]+path_min
row = row-1
column = column-1
elif min(Mij, Mki, Mkj) == Mki:
# min_cost=Mki
min_cost.append(Mki)
# path_min.append((row-1,column))
path_min = [[row-1, column]]+path_min
row = row-1
column = column
elif min(Mij, Mki, Mkj) == Mkj:
# min_cost=Mkj
min_cost.append(Mkj)
# path_min.append((row,column-1))
path_min = [[row, column-1]]+path_min
row = row
column = column-1
else:
# min_cost=min(Mij,Mki,Mkj)
min_cost.append(Mij)
# path_min.append(((row-1,column-1),(row-1,column),(row,column-1)))
path_min = [[row-1, column-1]]+path_min
row = row-1
column = column-1
# print(min_cost)
# print(path_min)
# ref
x = np.array(path_min)[:, 1]
# find
y = np.array(path_min)[:, 0]
# print(x,y)
plt.plot(x, y, color='black', linewidth=0.5)
plt.ylabel('ref seq')
plt.xlabel('find seq')
plt.title('dynamic programing to align reference and find sequence')
plt.annotate('min trace cost is:'+str(min_cost[0]), xy=(50, 250))
plt.savefig(
'/mnt/raid5/lijin/Hectobio/testcode/DynamicPrograming/path_example.png', dpi=300)
return path_min
def align_ref_find(ref_seq, find_seq, path_min):
align_ref = []
align_find = []
for ref_inx, find_inx in path_min:
align_ref.append(ref_seq[ref_inx])
align_find.append(find_seq[find_inx])
print('ref原始信号长度:{},find原始信号长度:{}'.format(len(ref_seq), len(find_seq)))
print('ref_align长度:{},find_align长度:{}'.format(
len(align_ref), len(align_find)))
pass
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='dynamic programing for sequence or signal')
parser.add_argument('--ref-seq', help='reference sequence or signal')
parser.add_argument('--find-seq', help='perparing find sequence or signal')
args = parser.parse_args()
ref_seq_path = args.ref_seq
find_seq_path = args.find_seq
# print(ref_seq_path, find_seq_path)
ref_seq_path = os.path.abspath(str(ref_seq_path))
find_seq_path = os.path.abspath(str(find_seq_path))
print('current reference sequence is:\n{}\nfind sequence is:\n{}\n'.format(ref_seq_path, find_seq_path))
ref_seq = []
find_seq = []
with open(ref_seq_path, 'r') as fid:
for value in fid:
ref_seq.append((float(value.split()[0])))
with open(find_seq_path, 'r') as fid:
for value in fid:
find_seq.append(float(value))
path_pass = trace_back_pass_path(
ref_seq, find_seq, dynamic_find_pass(ref_seq, find_seq))
align_ref_find(ref_seq, find_seq, path_pass)
pass
|
Ruby
|
UTF-8
| 982 | 2.6875 | 3 |
[] |
no_license
|
class Statistics < ActiveRecord::Base
belongs_to :user
class << self
def user_added(user)
Statistics.create(:user => user, :action => "added")
end
def user_removed(user)
Statistics.create(:user => user, :action => "removed")
end
def get_number_of_users(date)
result=Statistics.where("action = 'added' and created_at < ?", date).count -
Statistics.where("action = 'removed' and created_at < ?", date).count
Rails.logger.debug result
result
end
def get_chart_data
data = []
@statistics=Statistics.where("created_at >= ? and created_at <= ?",
3.weeks.ago, Time.now).all
number_of_users=Statistics.get_number_of_users(3.weeks.ago)
@statistics.each do |record|
number_of_users += record.action == 'added' ? 1 : -1
data.push [record.created_at.to_i * 1000, number_of_users]
end
data
end
end
end
|
Shell
|
UTF-8
| 241 | 2.65625 | 3 |
[] |
no_license
|
#!/bin/bash
echo "Updating Sub Repos"
if [ ! -d "./drupal" ]; then
git clone --branch 8.x http://git.drupal.org/project/drupal.git
fi
if [ ! -d "./pages" ]; then
git clone --branch gh-pages git@github.com:ericduran/drupalcores.git pages
fi
|
Python
|
UTF-8
| 2,622 | 3.03125 | 3 |
[] |
no_license
|
''' Detect human skin tone and draw a boundary around it.
Useful for gesture recognition and motion tracking.
Inspired by: http://stackoverflow.com/a/14756351/1463143
Date: 08 June 2013
'''
# Required moduls
import cv2
import numpy
import serial
s = serial.Serial(port='/dev/ttyUSB0', baudrate=9600)
# Constants for finding range of skin color in YCrCb
min_YCrCb = numpy.array([0,133,77],numpy.uint8)
max_YCrCb = numpy.array([255,173,127],numpy.uint8)
# Create a window to display the camera feed
cv2.namedWindow('UI')
# Get pointer to video frames from primary device
videoFrame = cv2.VideoCapture(0)
# Process the video frames
keyPressed = -1 # -1 indicates no key pressed
bw = 150
bh = 75
lbx= 50
lby= 50
rbx= 430
rby= 50
while(keyPressed < 0): # any key pressed has a value >= 0
# Grab video frame, decode it and return next video frame
_, img = videoFrame.read()
cv2.flip(img,1,img)
rbdetected=False
lbdetected=False
roil= img[lby:lby+bh,lbx:lbx+bw];
imageYCrCb = cv2.cvtColor(roil,cv2.COLOR_BGR2YCR_CB)
skinRegion = cv2.inRange(imageYCrCb,min_YCrCb,max_YCrCb)
contours, hierarchy = cv2.findContours(skinRegion, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for i, c in enumerate(contours):
area = cv2.contourArea(c)
if area > 500 and area < 1000:
#cv2.drawContours(img, contours, i, (0, 255, 0), 3)
lbdetected=True
roir= img[rby:rby+bh, rbx:rbx+bw];
imageYCrCb = cv2.cvtColor(roir,cv2.COLOR_BGR2YCR_CB)
skinRegion = cv2.inRange(imageYCrCb,min_YCrCb,max_YCrCb)
contours, hierarchy = cv2.findContours(skinRegion, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for i, c in enumerate(contours):
area = cv2.contourArea(c)
if area > 500 and area < 1000:
#cv2.drawContours(img, contours, i, (0, 255, 0), 3)
rbdetected=True
if lbdetected:
cv2.rectangle(img,(lbx,lby),(lbx+bw, lby+bh),[255,200,200],3)
s.write(str(1))
else:
cv2.rectangle(img,(lbx,lby),(lbx+bw, lby+bh),[200,200,200],1)
if rbdetected:
cv2.rectangle(img,(rbx,rby),(rbx+bw, rby+bh),[255,200,200],3)
s.write(str(3))
else:
cv2.rectangle(img,(rbx,rby),(rbx+bw, rby+bh),[200,200,200],1)
if rbdetected or lbdetected:
s.write(str(0))
#dst = img;
#cv2.flip(img,1,dst)
cv2.imshow('UI',img)
# Check for user input to close program
keyPressed = cv2.waitKey(1) # wait 1 milisecond in each iteration of while loop
# Close window and camera after exiting the while loop
cv2.destroyWindow('UI')
videoFrame.release()
|
C#
|
UTF-8
| 1,159 | 2.734375 | 3 |
[] |
no_license
|
// -----------------------------------------------------------------------
// This code is part of the Alexandria project (https://github.com/ahlec/Alexandria).
// Written and maintained by Alec Deitloff.
// Archive of Our Own (https://archiveofourown.org) is owned by the Organization for Transformative Works (http://www.transformativeworks.org/).
// -----------------------------------------------------------------------
namespace Alexandria.Model
{
/// <summary>
/// An enum for the different classifications that a tag could have, as indicated
/// by the website that the data came from.
/// </summary>
public enum TagType
{
/// <summary>
/// A tag that cannot be categorized. This might be a freeform tag (such as an
/// author's dialogue tag) or a standard tag for something such as a trope or
/// something which hasn't been categorized on that website yet.
/// </summary>
Miscellaneous,
/// <summary>
/// A character.
/// </summary>
Character,
/// <summary>
/// A relationship.
/// </summary>
Relationship
}
}
|
JavaScript
|
UTF-8
| 1,632 | 3.09375 | 3 |
[] |
no_license
|
function shoppingTime(memberId, money) {
// you can only write your code here!
var hasil ={};
var belanja = [
["Sepatu Stacattu", 1500000],
["Baju Zoro", 500000],
["Baju H&N", 250000],
["Sweater Uniklooh", 175000],
["Casing Handphone", 50000]
];
var listPurchased=[];
var changeMoney=money;
if(memberId===''||memberId===undefined && money===undefined){
return "Mohon maaf, toko X hanya berlaku untuk member saja";
}else if(money<50000){
return "Mohon maaf, uang tidak cukup";
}else{
for (var i=0; i<belanja.length; i++){
if(belanja[i][1]<=money){
changeMoney-=belanja[i][1];
listPurchased.push(belanja[i][0]);
}
}
}
hasil.memberId=memberId;
hasil.money=money;
hasil.listPurchased=listPurchased;
hasil.changeMoney=changeMoney;
return hasil;
}
// TEST CASES
// console.log(shoppingTime('1820RzKrnWn08', 2475000));
//{ memberId: '1820RzKrnWn08',
// money: 2475000,
// listPurchased:
// [ 'Sepatu Stacattu',
// 'Baju Zoro',
// 'Baju H&N',
// 'Sweater Uniklooh',
// 'Casing Handphone' ],
// changeMoney: 0 }
console.log(shoppingTime('82Ku8Ma742', 170000));
//{ memberId: '82Ku8Ma742',
// money: 170000,
// listPurchased:
// [ 'Casing Handphone' ],
// changeMoney: 120000 }
// console.log(shoppingTime('', 2475000)); //Mohon maaf, toko X hanya berlaku untuk member saja
// console.log(shoppingTime('234JdhweRxa53', 15000)); //Mohon maaf, uang tidak cukup
// console.log(shoppingTime()); ////Mohon maaf, toko X hanya berlaku untuk member saja
|
Python
|
UTF-8
| 1,218 | 4.53125 | 5 |
[] |
no_license
|
# 문제: 알파벳 소문자로만 이루어진 단어 S가 주어진다. 각각의 알파벳에 대해서, 단어에 포함되어 있는 경우에는 처음 등장하는 위치를, 포함되어 있지 않은 경우에는 -1을 출력하는 프로그램
# 입력: 첫째 줄에 단어 S가 주어진다. 단어의 길이는 100을 넘지 않으며, 알파벳 소문자로만 이루어져 있다.
# 출력: 각각의 알파벳에 대해서, a가 처음 등장하는 위치, b가 처음 등장하는 위치, ... z가 처음 등장하는 위치를 공백으로 구분해서 출력한다. 만약, 어떤 알파벳이 단어에 포함되어 있지 않다면 -1을 출력한다. 단어의 첫 번째 글자는 0번째 위치이고, 두 번째 글자는 1번째 위치이다.
import string # 모듈
ASCII = list(string.ascii_lowercase) # 아스키코드를 이용해 알파벳 소문자를 리스트로 받는다.
S = input() # 문자열 입력
for i in range(len(ASCII)):
# .find(): 문자열 내부에 특정 문자가 어디에 위치하는지 확인한다. (왼쪽부터 찾아서 처음 등장하는 위치를 찾는다.)
print(S.find(ASCII[i]), end= " ") # end= " "를 이용하여 한 줄에 출력한다.
|
Shell
|
UTF-8
| 780 | 2.96875 | 3 |
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env bats
load bats-workaround
runtime_os=$(uname -s | tr '[:upper:]' '[:lower:]')
runtime_arch=$(go env GOARCH | tr '[:upper:]' '[:lower:]')
exe="dist/kubectl-neat_${runtime_os}_${runtime_arch}"
rootDir="./test/fixtures"
@test "invalid args 1" {
echo $exe >&3
run2 "$exe" --foo
[ $status -eq 1 ]
[[ "$stderr" == "Error: unknown flag: --foo"* ]]
}
@test "invalid args 2" {
run2 "$exe" get --foo
[ $status -eq 1 ]
[[ "$stderr" == "Error: Error invoking kubectl"* ]]
}
@test "invalid args 3" {
run2 "$exe" foo
[ $status -eq 1 ]
[[ "$stderr" == 'Error: unknown command "foo" for "kubectl-neat"'* ]]
}
@test "local file" {
run2 "$exe" -f - <"$rootDir/pod1-raw.yaml"
[ $status -eq 0 ]
[[ "$stdout" == "apiVersion"* ]]
}
|
C#
|
UTF-8
| 1,400 | 2.6875 | 3 |
[] |
no_license
|
using System;
namespace Mongeral.Provisao.V2.DTO
{
public class ChaveProduto : IEquatable<ChaveProduto>
{
public int ItemProdutoId { get; }
public int TipoFormaContratacaoId { get; }
public int? TipoRendaId { get; }
public DateTime DataVigencia { get; }
private DateTime _inicioVigencia;
private DateTime _fimVigencia;
public ChaveProduto(int itemProdutoId, int tipoFormaContratacaoId, int? tipoRendaId, DateTime data)
{
ItemProdutoId = itemProdutoId;
TipoFormaContratacaoId = tipoFormaContratacaoId;
DataVigencia = data;
TipoRendaId = tipoRendaId;
}
public bool Equals(ChaveProduto other)
{
var result = this.ItemProdutoId == other.ItemProdutoId
&& TipoFormaContratacaoId == other.TipoFormaContratacaoId
&& TipoRendaId == other.TipoRendaId
&& other.EhVigente(this.DataVigencia);
return result;
}
private bool EhVigente(DateTime dataVigencia)
{
return dataVigencia >= _inicioVigencia && dataVigencia <= _fimVigencia;
}
public void SetVigencia(DateTime dataInicioVigencia, DateTime dataFimVigencia)
{
_inicioVigencia = dataInicioVigencia;
_fimVigencia = dataFimVigencia;
}
}
}
|
Java
|
UTF-8
| 761 | 2.671875 | 3 |
[] |
no_license
|
import java.util.List;
import java.util.Observable;
/**
*
* @author adri
*/
abstract public class Operation extends Observable{
private float progress;
private boolean necessaryLicense;
public float getProgress() {
return progress;
}
protected void setProgress(float p){
this.progress = p;
this.setChanged();
this.notifyObservers();
}
public boolean isNecessaryLicense() {
return necessaryLicense;
}
public void setNecessaryLicense(boolean necessaryLicense) {
this.necessaryLicense = necessaryLicense;
}
abstract public String getName();
abstract public List<String> getParams();
abstract public String execute(List<String> paramsValues);
}
|
Python
|
UTF-8
| 11,018 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
import sys
import os
import argparse
import subprocess
import fnmatch
from Bio import SeqIO
### Version 5, created 27 August 2020 by Nicole S Paulat ###
### Compare MELT-DELETION output to its input RepeatMasker file to append orientation
### into the MELT-DELETION hits, and check for inconsistencies in MELT-DEL output
### Input format is CHROM, POS, END, SVTYPE
def get_args():
#What this script does
parser = argparse.ArgumentParser(description="Adding reference genome reference TE orientation to MELT-Deletion hits", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
required = parser.add_argument_group('required arguments')
#Give input coordinate file of MELT hits (CHROM# + POS + END + SVTYPE)
parser.add_argument('-i', '--input', help='MELT-Deletion results (in BED format to use as input file in the given directory', required=True)
#Argument of directory containing MSA scaffolds (need full path)
parser.add_argument('-r', '--rmfile', type=str, help='RepeatMasker out.bed file to use as reference input file in the given directory', required=True)
#Argument of directory containing the list of formatted MELT hits (need full path)
parser.add_argument('-d', '--dir', type=str, help='Location of directory of input MELT-Deletion file', default=".")
#Argument of directory containing MSA scaffolds (need full path)
parser.add_argument('-od', '--outdir', type=str, help='Location of directory for the output file', default=".")
args = parser.parse_args()
MDEL = args.input
RMFILE = args.rmfile
DIR = args.dir
OUTDIR = args.outdir
return MDEL, RMFILE, DIR, OUTDIR
MDEL, RMFILE, DIR, OUTDIR = get_args()
if DIR == ".":
DIR = os.getcwd()
if OUTDIR == ".":
OUTDIR = os.getcwd()
#argument sanity checks
#if not args.rmfile:
# sys.exit('You must provide the RepeatMasker file containing the reference TE insertions.')
#if not args.input:
# sys.exit('You must provide the list of MELT coordinates.')
print('The input MELT Deletion list is ' + MDEL +'.')
print('The input RepeatMasker file is ' + RMFILE + '.')
#set up access to input file w/ path
INPUT = os.path.join(DIR, MDEL)
#set up access to ouput files w/ path
BASENAME = os.path.basename(MDEL).split(".")[0]
BASE_OUT = os.path.join(OUTDIR, BASENAME)
OUTPUT = BASE_OUT + "_add_melt_orientation.bed"
OUTPUT2 = BASE_OUT + "_no_match_meltd.bed"
#open an ouput file for MELT_DELETION hits with matching RM hits w/n 50 bases
f = open(OUTPUT, "w+")
#open output file for MELT-DELETION hits with no corresponding RepeatMasker hits
#either at all, or none within 50 bases ***50 bases is the max cap for matches***
h = open(OUTPUT2, "w+")
# def read_melt(FILENAME):
# my_dict = {}
# for line in open(FILENAME):
# #for line in open("test_MDEL.txt"):
# line = line.split()
# CHROM1 = line[0]
# START1 = int(line[1])
# STOP1 = int(line[2])
# TYPE1 = line[3]
# #if the chromosome is already in the dictionary, add base pos only
# #if the chromosome is not in the dictionary, add entire entry
# #if line[0] in my_dict:
# try:
# my_dict[line[0]].append((START1,STOP1,TYPE1))
# #else:
# except KeyError:
# my_dict[CHROM1] = [(START1,STOP1,TYPE1)]
# return my_dict
def read_melt(FILENAME):
my_dict = {}
for line in open(FILENAME):
line = line.split()
CHROM = line[0]
START = int(line[1])
STOP = int(line[2])
TYPE = line[3]
LENGTH = int(line[4])
GTYPE1 = line[5]
GTYPE2 = line[6]
GTYPE3 = line[7]
GTYPE4 = line[8]
GTYPE5 = line[9]
GTYPE6 = line[10]
GTYPE7 = line[11]
GTYPE8 = line[12]
GTYPE9 = line[13]
GTYPE10 = line[14]
GTYPE11 = line[15]
MODULE = line[16]
#if the chromosome is already in the dictionary, add base pos only
#if the chromosome is not in the dictionary, add entire entry
try:
my_dict[line[0]].append((START,STOP,TYPE,LENGTH,GTYPE1,GTYPE2,GTYPE3,GTYPE4,GTYPE5,GTYPE6,GTYPE7,GTYPE8,GTYPE9,GTYPE10,GTYPE11,MODULE))
except KeyError:
my_dict[CHROM] = [(START,STOP,TYPE,LENGTH,GTYPE1,GTYPE2,GTYPE3,GTYPE4,GTYPE5,GTYPE6,GTYPE7,GTYPE8,GTYPE9,GTYPE10,GTYPE11,MODULE)]
return my_dict
my_dict = read_melt(INPUT)
print('Made first dictionary.')
def read_rmout(FILENAME):
second_dict = {}
for line in open(FILENAME):
#for line in open("test_rmfile.txt"):
line = line.split()
CHROM2 = line[0]
START2 = int(line[1])
STOP2 = int(line[2])
TYPE2 = line[3]
ORIENTATION2 = line[5]
#if line[0] in second_dict:
try:
second_dict[line[0]].append((START2,STOP2,TYPE2,ORIENTATION2))
#else:
except KeyError:
second_dict[CHROM2] = [(START2,STOP2,TYPE2,ORIENTATION2)]
return second_dict
second_dict = read_rmout(RMFILE)
print('Made second dictionary.')
#for every key in the dictionary, compare to every line in RMFILE
#need sorted MDEL list
#edit to list
for CHROM in my_dict:
print('Looking at scaffold ' + CHROM + '.')
if CHROM in second_dict:
print('Scaffold is in RepeatMasker file.')
#print(my_dict[CHROM])
#print(second_dict[CHROM])
for INSERTION1 in range(len(my_dict[CHROM])):
INSERTION_CANDIDATES = []
for INSERTION2 in range(len(second_dict[CHROM])):
if my_dict[CHROM][INSERTION1][2] == second_dict[CHROM][INSERTION2][2]:
if abs(my_dict[CHROM][INSERTION1][0] - second_dict[CHROM][INSERTION2][0]) <= 50:
#If insertion meets the criteria, add the insertion (tuple) to a list
INSERTION_CANDIDATES.append(second_dict[CHROM][INSERTION2])
if len(INSERTION_CANDIDATES) == 1:
#Only one candidate, write it out
#f.write("{}\t{}\t{}\t{}\t{}\n".format(CHROM,my_dict[CHROM][INSERTION1][0],my_dict[CHROM][INSERTION1][1],my_dict[CHROM][INSERTION1][2],second_dict[CHROM][INSERTION2][3]))
f.write("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format(CHROM,my_dict[CHROM][INSERTION1][0],my_dict[CHROM][INSERTION1][1],my_dict[CHROM][INSERTION1][2], my_dict[CHROM][INSERTION1][3], second_dict[CHROM][INSERTION2][3], my_dict[CHROM][INSERTION1][4], my_dict[CHROM][INSERTION1][5], my_dict[CHROM][INSERTION1][6], my_dict[CHROM][INSERTION1][7], my_dict[CHROM][INSERTION1][8], my_dict[CHROM][INSERTION1][9], my_dict[CHROM][INSERTION1][10], my_dict[CHROM][INSERTION1][11], my_dict[CHROM][INSERTION1][12], my_dict[CHROM][INSERTION1][13], my_dict[CHROM][INSERTION1][14], my_dict[CHROM][INSERTION1][15]))
#sys.stdout.write("{}\t{}\t{}\t{}\t{}\n".format(CHROM,my_dict[CHROM][INSERTION1][0],my_dict[CHROM][INSERTION1][1],my_dict[CHROM][INSERTION1][2],second_dict[CHROM][INSERTION2][3]))
elif len(INSERTION_CANDIDATES) > 1:
#Code for choosing among insertion candidates
INSERTION_START = my_dict[CHROM][INSERTION1][0]
# list comprehension to calculate difference between MELT start and RM start for all candidates
START_DIFFS = [abs(INSERTION_START - I[0]) for I in INSERTION_CANDIDATES]
# This is a way to get the index of the minimum in a list
# NOTE: It will always return the first instance of the minimum
MIN_START_DIFF = START_DIFFS.index(min(START_DIFFS))
BEST_CANDIDATE = INSERTION_CANDIDATES[MIN_START_DIFF]
#f.write("{}\t{}\t{}\t{}\t{}\n".format(CHROM,my_dict[CHROM][INSERTION1][0],my_dict[CHROM][INSERTION1][1],my_dict[CHROM][INSERTION1][2],BEST_CANDIDATE[3]))
f.write("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format(CHROM,my_dict[CHROM][INSERTION1][0],my_dict[CHROM][INSERTION1][1],my_dict[CHROM][INSERTION1][2], my_dict[CHROM][INSERTION1][3], BEST_CANDIDATE[3], my_dict[CHROM][INSERTION1][4], my_dict[CHROM][INSERTION1][5], my_dict[CHROM][INSERTION1][6], my_dict[CHROM][INSERTION1][7], my_dict[CHROM][INSERTION1][8], my_dict[CHROM][INSERTION1][9], my_dict[CHROM][INSERTION1][10], my_dict[CHROM][INSERTION1][11], my_dict[CHROM][INSERTION1][12], my_dict[CHROM][INSERTION1][13], my_dict[CHROM][INSERTION1][14], my_dict[CHROM][INSERTION1][15]))
else:
#INSERTION_CANDIDATES is empty, so write to different file
#h.write("{}\t{}\t{}\t{}\t{}\n".format(CHROM,my_dict[CHROM][INSERTION1][0],my_dict[CHROM][INSERTION1][1],my_dict[CHROM][INSERTION1][2],"NONE"))
h.write("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format(CHROM,my_dict[CHROM][INSERTION1][0],my_dict[CHROM][INSERTION1][1],my_dict[CHROM][INSERTION1][2], my_dict[CHROM][INSERTION1][3], "NONE", my_dict[CHROM][INSERTION1][4], my_dict[CHROM][INSERTION1][5], my_dict[CHROM][INSERTION1][6], my_dict[CHROM][INSERTION1][7], my_dict[CHROM][INSERTION1][8], my_dict[CHROM][INSERTION1][9], my_dict[CHROM][INSERTION1][10], my_dict[CHROM][INSERTION1][11], my_dict[CHROM][INSERTION1][12], my_dict[CHROM][INSERTION1][13], my_dict[CHROM][INSERTION1][14], my_dict[CHROM][INSERTION1][15]))
#else:
# print("Unable to read input list. Try again.")
#close output files
f.close()
h.close()
#Combine the two files
CAT_FILE = BASE_OUT + "_all_hits_orient.bed"
CONCATENATE = "cat " + OUTPUT + " " + OUTPUT2 + " > " + CAT_FILE
os.system(CONCATENATE)
def read_catout(FILENAME):
final_dict = {}
#for line in open("all_hits_orient.bed"):
for line in open(FILENAME):
line = line.split()
CHROM = line[0]
START = int(line[1])
STOP = int(line[2])
TYPE = line[3]
LENGTH = int(line[4])
ORIENTATION = line[5]
GTYPE1 = line[6]
GTYPE2 = line[7]
GTYPE3 = line[8]
GTYPE4 = line[9]
GTYPE5 = line[10]
GTYPE6 = line[11]
GTYPE7 = line[12]
GTYPE8 = line[13]
GTYPE9 = line[14]
GTYPE10 = line[15]
GTYPE11 = line[16]
MODULE = line[17]
#if the chromosome is already in the dictionary, add base pos only
#if the chromosome is not in the dictionary, add entire entry
try:
final_dict[line[0]].append((START,STOP,TYPE,LENGTH,ORIENTATION,GTYPE1,GTYPE2,GTYPE3,GTYPE4,GTYPE5,GTYPE6,GTYPE7,GTYPE8,GTYPE9,GTYPE10,GTYPE11,MODULE))
except KeyError:
final_dict[CHROM] = [(START,STOP,TYPE,LENGTH,ORIENTATION,GTYPE1,GTYPE2,GTYPE3,GTYPE4,GTYPE5,GTYPE6,GTYPE7,GTYPE8,GTYPE9,GTYPE10,GTYPE11,MODULE)]
return final_dict
# line = line.split()
# CHROM = line[0]
# START = int(line[1])
# STOP = int(line[2])
# TYPE = line[3]
# ORIENTATION = line[4]
#if line[0] in final_dict:
# try:
# final_dict[line[0]].append((START,STOP,TYPE,ORIENTATION))
# #else:
# except KeyError:
# final_dict[CHROM] = [(START,STOP,TYPE,ORIENTATION)]
# return final_dict
#Read file3 back in as a dictionary
final_dict = read_catout(CAT_FILE)
#open final file for writing
final_file = open(CAT_FILE,"w+")
#Loop over the sorted chromosomes and write sorted coordinates
for CHROM in sorted(final_dict.keys()):
SORTED_COORDS = sorted(final_dict[CHROM], key = lambda x: x[1])
for INSERTION in SORTED_COORDS:
#final_file.write("{}\t{}\t{}\t{}\t{}\n".format(CHROM,INSERTION[0],INSERTION[1],INSERTION[2],INSERTION[3]))
final_file.write("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format(CHROM,INSERTION[0],INSERTION[1],INSERTION[2],INSERTION[3], INSERTION[4], INSERTION[5], INSERTION[6], INSERTION[7], INSERTION[8], INSERTION[9], INSERTION[10], INSERTION[11], INSERTION[12], INSERTION[13], INSERTION[14], INSERTION[15], INSERTION[16]))
final_file.close()
|
JavaScript
|
UTF-8
| 1,739 | 3.265625 | 3 |
[] |
no_license
|
<!--
function trace(data, type, iteration)
{
var S = [], T = (Boolean(type) || (type === undefined)) ? true : Boolean(type), I = (iteration > 0) ? Number(iteration) : 0;
var repeat = function (t, n) { var s = ''; for (var i = 0; i < n; i++) s += t; return s; }
var s = function (i, s, t) { S[S.length] = repeat(' ', i) + t + s; };
var ss = function (i, ss, t) { s(i, ss, (T && t) ? ('(' + t + ') ') : ''); };
try
{
if (data === null) ss(I, 'NULL', 'null');
else if ((typeof data === 'boolean') || (data instanceof Boolean)) ss(I, data ? 'TRUE' : 'FALSE', 'boolean');
else if ((typeof data === 'string') || (data instanceof String)) ss(I, "'" + String(data) + "'", 'string');
else if ((typeof data === 'number') || (data instanceof Number)) ss(I, "'" + String(data) + "'", 'number');
else if (data instanceof Array)
{
ss(I, '[' + data.length + ']', 'array');
ss(I, '{', false);
for (var O = data, o = 0; o < O.length; o++) ss(0, trace(O[o], T, I + 1), false);
ss(I, '}', false);
}
else if ((typeof data === 'object') && data && (data instanceof Object))
{
var O = data;
ss(I, '', 'object');
ss(I, '{', false);
for (o in O)
{
var oo = trace(O[o], T, I + 1);
oo = String(oo).trim();
ss(I + 1, o + ': ' + oo, false);
}
ss(I, '}', false);
}
else if ((typeof data === 'function') || (data instanceof Function))
{
var O = String(data).replace(/^function[\s]*/i, ''), L = 50, l = (O.length > L), o = O.replace(/[\s]+/g, ' ').substr(0, L).trim();
o = "'" + ((l) ? (o + ' ...') : o) + "'";
ss(I, o, 'function');
}
else ss(I, '', 'unknowen');
}
catch (e) { ss(I, '', 'exception'); }
return S.join("\n");
}
//-->
|
Markdown
|
UTF-8
| 988 | 3.046875 | 3 |
[] |
no_license
|
# Build Infrastructure
Here we will have our first infrastructure created, i.e, provision an EC2 instance on Amazon Web Services (AWS).
## Prerequisites
- The Terraform CLI installed.
- The AWS CLI installed.
- An AWS account.
- Your AWS credentials.
## Steps to follow:
- Configure the AWS CLI from your terminal
`aws configure`
- Write configuration
1. `mkdir learn-terraform-aws-instance`
2. `cd learn-terraform-aws-instance`
3. `touch main.tf`
4. Edit the configuration in main.tf file
- Initialize the directory
1. `terraform init`
This will download the aws provider and installs it in a hidden subdirectory of your current working directory.
- Format and validate the configuration
1. `terraform fmt`
2. `terraform validate`
- Create infrastructure
1. `terraform apply`
Now, infrastructure using Terraform has been created. Just visit the EC2 console and find your new EC2 instance.
- Inspect state
1. Inspect the current state using:
`terraform show`
|
C#
|
UTF-8
| 1,634 | 2.609375 | 3 |
[] |
no_license
|
using ShoppingCartDataLayer.Repositories;
using ShoppingCartLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShoppingCartSystem
{
public class OrderManager : ShoppingSystemManager
{
public OrderManager(IDataSource dataSource) : base(dataSource) { }
public Order GetOrder(Guid userId, Guid orderId)
{
return DataSource.Orders.GetUserOrder(userId, orderId);
}
public List<Order> GetOrders(Guid userId)
{
var orders = DataSource.Orders.GetUserOrders(userId);
if (orders == null) {
return new List<Order>();
}
return orders.ToList();
}
public bool ModifyOrder(Guid userId, Guid orderId)
{
var order = DataSource.Orders.GetUserOrder(userId, orderId);
if (order == null)
{
return false;
}
order.Modify();
DataSource.SaveChanges();
return true;
}
public bool OrderItemDelivered(Guid userId, Guid orderId, Guid itemId) {
var order = DataSource.Orders.Find(new Order { Id = orderId});
if (order == null || !order.User.Id.Equals(userId)) {
return false;
}
var orderItem = order.OrderItems.FirstOrDefault(oi => oi.ItemId.Equals(itemId));
if (orderItem == null) {
return false;
}
orderItem.Status = ItemStatus.DELIVERED;
return true;
}
}
}
|
SQL
|
UTF-8
| 6,746 | 3.109375 | 3 |
[] |
no_license
|
-- phpMyAdmin SQL Dump
-- version 4.9.5
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Dec 04, 2020 at 04:22 AM
-- Server version: 5.7.24
-- PHP Version: 7.4.1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `wdl`
--
-- --------------------------------------------------------
--
-- Table structure for table `answers`
--
CREATE TABLE `answers` (
`sr_no` int(11) NOT NULL,
`ans` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `answers`
--
INSERT INTO `answers` (`sr_no`, `ans`) VALUES
(0, 'a'),
(1, 'b'),
(2, 'a'),
(3, 'd'),
(4, 'c'),
(5, 'a'),
(6, 'c'),
(7, 'd'),
(8, 'b'),
(9, 'b'),
(10, 'a'),
(11, 'c'),
(12, 'd'),
(13, 'a'),
(14, 'b'),
(15, 'a');
-- --------------------------------------------------------
--
-- Table structure for table `dashboard`
--
CREATE TABLE `dashboard` (
`username` varchar(100) NOT NULL,
`snake_game` int(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `dashboard`
--
INSERT INTO `dashboard` (`username`, `snake_game`) VALUES
('Danish_123', 10),
('neha_123', 0),
('nikis', 10),
('nikita_sarode', 35);
-- --------------------------------------------------------
--
-- Table structure for table `questions`
--
CREATE TABLE `questions` (
`sr_no` int(5) NOT NULL,
`ques` text NOT NULL,
`a` text NOT NULL,
`b` text NOT NULL,
`c` text NOT NULL,
`d` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `questions`
--
INSERT INTO `questions` (`sr_no`, `ques`, `a`, `b`, `c`, `d`) VALUES
(0, 'Ready !!?', 'Yes', 'yayayay', 'yup', 'Yesssss'),
(1, 'Name Disney’s first film?', 'Cinderella', 'Snow White', 'The Incredible Journey', 'Mary Poppins'),
(2, 'What was the most-watched series on Netflix in 2019?', 'Stranger Things', 'You', 'Friends', 'Big Bang Theory'),
(3, 'What is the name of the coffee shop in the sitcom Friends?', 'Farm Cafe', 'Coffee Shop', 'Central Farm', 'Central Perk'),
(4, 'What is the all-time most-streamed song on Spotify to date?', 'Tusa', 'All Night', 'The Shape of You', 'Despacito'),
(5, 'In Game of Thrones, what does Arya Stark call her sword?', 'Needle', 'Pen', 'Light', 'Star'),
(6, 'Who among the following Cricketer was the winner of Orange Cap in the IPL 2020?', 'Virat Kohli', 'Rohit Sharma', 'K L Rahul', 'Kieron Pollard'),
(7, 'Hitler party which came into power in 1933 is known as', 'Labour Party', 'Ku-Klux-Klan', 'Democratic Party', 'Nazi Party'),
(8, 'INDIA HAS LARGEST DEPOSITS OF ____ IN THE WORLD.', 'gold', 'mica', 'copper', 'None of the above'),
(9, 'India\'s first atomic reactor was', 'Kamini', 'Apsara', 'Dhruva', 'Zerlina'),
(10, 'Satellite launching station is located at', 'Sriharikotta (Andhra Pradesh)', 'Salem (Tamilnadu)', 'Solapur (Maharashtra)', 'Warangal (Telangana)'),
(11, 'Logarithm tables were invented by', 'John Doe', 'John Harrison', 'John Napier', 'John Douglas'),
(12, 'Entomology is the science that studies', 'Behavior of Elephants', 'The origin and history of technical and scientific terms', 'The formation of rocks', 'Insects'),
(13, 'When is the International Workers\' Day?', '1st May', '15th April', '12th December', '1st August'),
(14, 'Which country operationalized world’s largest radio telescope?', 'India', 'China', 'USA', 'Japan'),
(15, ' Which state has the largest population?', 'Uttar Pradesh', 'Bihar', 'Maharastra', 'Andra Pradesh');
-- --------------------------------------------------------
--
-- Table structure for table `reviews`
--
CREATE TABLE `reviews` (
`name` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`phone_no` int(10) NOT NULL,
`review` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `reviews`
--
INSERT INTO `reviews` (`name`, `email`, `phone_no`, `review`) VALUES
('Nidhi', 'rnsxdcd', 908932022, 'Noice'),
('Nikita', 'nikita@nothing.com', 12312312, 'This is a very great website !! Very amazing stuff and good games and also very unique !! I love it ....'),
('Amruta ', 'amruta@why.com', 787877878, 'Ta bong👍🏻'),
('Rakesh', 'Rakesh@panmasala.com', 0, 'Awesome Panmasal khaike!! 🍃');
-- --------------------------------------------------------
--
-- Table structure for table `snakegame`
--
CREATE TABLE `snakegame` (
`id` int(11) NOT NULL,
`username` varchar(50) NOT NULL,
`score` int(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `snakegame`
--
INSERT INTO `snakegame` (`id`, `username`, `score`) VALUES
(1, 'nikita_sarode', 20),
(2, 'nikita_sarode', 20),
(3, 'nikita_sarode', 30),
(4, 'nikita_sarode', 30),
(5, 'nikita_sarode', 10),
(6, 'nikita_sarode', 10),
(7, 'nikita_sarode', 10),
(8, 'nikita_sarode', 15),
(9, 'nikita_sarode', 25);
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`name` varchar(20) NOT NULL,
`username` varchar(20) NOT NULL,
`password` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`name`, `username`, `password`) VALUES
('nikita', 'nikita_sarode', '123456'),
('Nidhi', 'nidhi_vanjare', '123456'),
('Nidhi V', 'nidhi_v', '123456'),
('Rakshita', 'rak', '123'),
('nikita', 'nikis', '123456'),
('nhfdkbj ', 'nikita_sarode', 'ehuvj12hS'),
('Nikita Sarode', 'nikita_sarode', '54854hsdA'),
('Nikita Sarode', 'nikita_sarode', '54854hsdA'),
('Danish', 'Danish_123', 'Danish123'),
('Neha ', 'neha_123', 'Neha123');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `answers`
--
ALTER TABLE `answers`
ADD PRIMARY KEY (`sr_no`);
--
-- Indexes for table `dashboard`
--
ALTER TABLE `dashboard`
ADD PRIMARY KEY (`username`);
--
-- Indexes for table `questions`
--
ALTER TABLE `questions`
ADD PRIMARY KEY (`sr_no`);
--
-- Indexes for table `snakegame`
--
ALTER TABLE `snakegame`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `snakegame`
--
ALTER TABLE `snakegame`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `answers`
--
ALTER TABLE `answers`
ADD CONSTRAINT `answers_ibfk_1` FOREIGN KEY (`sr_no`) REFERENCES `questions` (`sr_no`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Java
|
UTF-8
| 613 | 2.40625 | 2 |
[] |
no_license
|
package com.roadioapp.roadioappuser.mModels;
import android.app.Activity;
import android.widget.Toast;
import com.roadioapp.roadioappuser.mObjects.AuthObj;
public class DriverBid {
public String amount;
private Activity activity;
public DriverBid(){
}
public DriverBid(Activity activity){
this.activity = activity;
}
public void bidAccept(){
AuthObj mAuth = new AuthObj(activity);
mAuth.updateUser();
if(mAuth.isLoginUser()){
}else{
Toast.makeText(activity, "No User Found!", Toast.LENGTH_SHORT).show();
}
}
}
|
Python
|
UTF-8
| 542 | 4.5 | 4 |
[] |
no_license
|
# 定义类名 首字母大写(大驼峰法)
class Person:
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex # 没使用的变量尽量不要定义
def eat(self):
print("我是%s" % self.name)
print("我饿了,我要吃吃吃")
def sleep(self):
print("我是%s" % self.name)
print("我困了,我要睡觉了")
P1 = Person("林均煜", 18, "男")
P2 = Person("李湘梅", 16, "女")
P1.sleep()
P2.eat()
print(P1)
|
Python
|
UTF-8
| 4,391 | 4.25 | 4 |
[
"MIT"
] |
permissive
|
import matplotlib.pyplot as plt
""" The Car class defines a car's movement and keeps track of its state.
The class includes init, move, and display functions.
This class assumes a constant velocity motion model and the state
of the car includes the car's position, and it's velocity.
Attributes:
state: A list of the car's current position [y, x] and velocity [vy, vx]
world: The world that the car is moving within (a 2D list)
"""
class Car(object):
# Car constructor
# Called when you write car.Car(_, _, _)
def __init__(self, position, velocity, world, color = 'r'):
"""Initializes Car with some position, velocity, and a world to traverse."""
# Initialize the state
# Position is a list [y, x] and so is velocity [vy, vx]
self.state = [position, velocity]
self.world = world # world is a 2D list of values that range from 0-1
# Set the default color
self.color = color
# Initalize the path
self.path = []
self.path.append(position)
# Move function
def move(self, dt=1):
""" The move function moves the car in the direction of the velocity and
updates the state.
It assumes a circular world and a default dt = 1 (though dt can be any
non-negative integer).
"""
height = len(self.world)
width = len(self.world[0])
position = self.state[0]
velocity = self.state[1]
# Predict the new position [y, x] based on velocity [vx, vy] and time, dt
predicted_position = [
(position[0] + velocity[0]*dt) % height, # default dt = 1
(position[1] + velocity[1]*dt) % width
]
# Update the state
self.state = [predicted_position, velocity]
# Every time the robot moves, add the new position to the path
self.path.append(predicted_position)
# Turn left function
def turn_left(self):
""" Turning left "rotates" the velocity values, so vy = -vx, and vx = vy.
For example, if a car is going right at 1 world cell/sec this means
vy = 0, vx = 1,
and if it turns left, then it should be moving upwards on the world grid
at the same speed!
And up is vy = -1 and vx = 0
"""
# Change the velocity
velocity = self.state[1]
predicted_velocity = [
-velocity[1],
velocity[0]
]
# Update the state velocity
self.state[1] = predicted_velocity
def turn_right(self):
# Change the velocity
velocity = self.state[1]
predicted_velocity = [velocity[1], -velocity[0]]
# Update the state velocity
self.state[1] = predicted_velocity
# Helper function for displaying the world + robot position
# Assumes the world in a 2D numpy array and position is in the form [y, x]
# path is a list of positions, and it's an optional argument
def display_world(self):
# Store the current position of the car
position = self.state[0]
# Plot grid of values + initial ticks
plt.matshow(self.world, cmap='gray')
# Set minor axes in between the labels
ax=plt.gca()
rows = len(self.world)
cols = len(self.world[0])
ax.set_xticks([x-0.5 for x in range(1,cols)],minor=True )
ax.set_yticks([y-0.5 for y in range(1,rows)],minor=True)
# Plot grid on minor axes in gray (width = 2)
plt.grid(which='minor',ls='-',lw=2, color='gray')
# Create a 'x' character that represents the car
# ha = horizontal alignment, va = verical
ax.text(position[1], position[0], 'x', ha='center', va='center', color=self.color, fontsize=30)
# Draw path if it exists
if(len(self.path) > 1):
# loop through all path indices and draw a dot (unless it's at the car's location)
for pos in self.path:
if(pos != position):
ax.text(pos[1], pos[0], '.', ha='center', va='baseline', color=self.color, fontsize=30)
# Display final result
plt.show()
|
Ruby
|
UTF-8
| 746 | 2.640625 | 3 |
[] |
no_license
|
require_relative 'Bookie.rb'
require_relative 'BookieView.rb'
require_relative '../ObserverPattern/Observer.rb'
class BookieController < Object
include Observer
attr_reader :model
def initialize
super()
@view = BookieView.new
@model = Bookie.new
end
def create
data = @view.createView
@model.setUsername(data[0])
@model.setPassword(data[1])
end
def update
password = @view.updateView
@model.setPassword(password)
end
def updateView
@view.printView(@model.username,@model.password)
end
def createDefaultBookie(name, pass)
@model.setUsername(name)
@model.setPassword(pass)
end
def readAllNotifications
if @notifications != nil
@notifications.each { |msg| @view.showNotification(msg)}
end
end
end
|
Java
|
UTF-8
| 1,041 | 2.0625 | 2 |
[] |
no_license
|
package com.pedrohubner.message.services;
import com.pedrohubner.message.models.Messages;
import com.pedrohubner.message.models.MessagesDAO;
import com.pedrohubner.message.repositories.MessagesRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Service
@AllArgsConstructor
public class MessagesService {
private final MessagesRepository messagesRepository;
public Mono<Messages> mapToMessages(MessagesDAO messagesDAO) {
Messages newMessage = Messages.builder()
.message(messagesDAO.getMessage())
.addressee(messagesDAO.getAddressee())
.sender(messagesDAO.getSender())
.channelId(messagesDAO.getChannelId())
.build();
return messagesRepository.insert(newMessage);
}
public Flux<Messages> findMessagesByChatId(String chatId) {
return messagesRepository.findWithTailableCursorByChannelId(chatId);
}
}
|
Java
|
UTF-8
| 1,343 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mpoop6;
/**
* Clse que hereda de la clase Persona y modela a un alumno
* @author Leal Hernandez Haziel Ivan
*/
public class Alumno extends Persona{
private int numMaterias;
public Alumno() {
}
/**
*
* @param numMaterias Cantidad de materias del alumno
* @param nombre
* @param numTel
*/
public Alumno(int numMaterias, String nombre, int numTel) {
super(nombre, numTel);
this.numMaterias = numMaterias;
}
/**
*
*
* @return numMaterias
*/
public int getNumMaterias() {
return numMaterias;
}
/**
*
*
* @param numMaterias
*/
public void setNumMaterias(int numMaterias) {
this.numMaterias = numMaterias;
}
/**
*
*
* @return cadena coninfromacion del alumno
*/
@Override
public String toString() {
return super.toString() + "Alumno{" + "numMaterias=" + numMaterias + '}';
}
/**
*
*
* @param nuevas
*/
void nuevasMaterias(int nuevas){
numMaterias = nuevas;
}
}
|
Shell
|
UTF-8
| 751 | 2.59375 | 3 |
[] |
no_license
|
_gemname=rvpacker
pkgname=ruby-$_gemname
pkgver=1.2.0
pkgrel=2
pkgdesc="Pack and unpack RPG Maker data files"
arch=(any)
url="https://github.com/akesterson/rvpacker"
license=("MIT")
depends=(ruby-trollop ruby-formatador)
source=("https://rubygems.org/downloads/$_gemname-$pkgver.gem")
noextract=("$_gemname-$pkgver.gem")
provides=("ruby-psych=2.0.0")
conflicts=("ruby-psych=2.0.0")
md5sums=('cb721d32cd56862cab89499b392a5a5f')
package() {
local _gemdir="$(ruby -e'puts Gem.default_dir')"
gem install --no-user-install -i "$pkgdir/$_gemdir" -n "$pkgdir/usr/bin" $_gemname-$pkgver.gem
rm "$pkgdir/$_gemdir/cache/"*.gem
rm -r "$pkgdir/$_gemdir/gems/"{formatador,trollop}-*
rm "$pkgdir/$_gemdir/specifications/"{formatador,trollop}-*.gemspec
}
|
Markdown
|
UTF-8
| 7,527 | 3.65625 | 4 |
[] |
no_license
|
## DATA ANALYSIS FOR COMPANY XYZ
* Company XYZ owns a supermarket in 3 cities across the Country - Lagos, Abuja and Portharcourt. This data analysis is conducted to determine sales trend and Company growth, as there has been an increase in Supermarket competition.
### Loading Datasets
* The process begins with importing the different Libraries.
* The data collected from the 3 different branches are combined using the concatenation method and it's exported to a CSV for easy Data analysis.
*combined_csv = pd.concat([pd.read_csv(f) for f in all_filenames])
*combined_csv.to_csv("combined_csv.csv", index = False, encoding = 'utf-8-sig')
* The pd_read.csv() and head() methods are used to to read and return the first few rows of the combined csv respectively.
### Data Exploration
* The shape attribute determines the number of rows and columns, while the column attributes generates the names of columns.
*df.shape, df.columns
* The describe function generates the statistical summary of the dataframe which includes the count, mean, standard deviation, Minimum, Maximum, 25th, 50th and 75th percetile. From this result, different comparison and deductions could be made.
*df.describe()
* Using df.isnull() and df.notna() method, we can determine wether there are missing values or not. The sum method can be added to get a summary and not a boolean (True/False).
*df.isnull().sum()
*df.notna().sum()
* The info() method is then used to check the information of the DataFrame. This includes the Columns, number of rows and columns, presence of missing values and the Data types of each column.
*df.info()
### Dealing with DateTime Features
* The to_datetime method is used to convert the Date and Time to DateTime data type.
**Date = df['Date'] = pd.to_datetime(df['Date'])
**df['Time'] = pd.to_datetime(df['Time'])
* The dtype method is used to check if the datatype is in DateTime.
**df['Date'].dtype
**df['Time'].dtype
* Extraction of Day, Month, Year and Hour using .dt.day, .dt.mont, .dt.year and .dt.hour.
* The number of unique hours was determined using the nunique method and unique() method to show the unique sales hour.
**df_hour.nunique(dropna = True)
**ser.unique()
### Unique Values in column
* By iterating through the categorical columns, the unique values in the categorical column are determined. The value_counts() method is used to generate the count figure of the categorical column.
**for i in categorical_columns:
if i != 'Invoice ID':
print ("This is for {} columns".format(i))
print (df[i].unique().tolist())
print("Total Number of unique value: {}".format(len(df[i].unique().tolist())))
**df['Gender'].value_counts()
### Aggregation with GroupBy
* The sum and mean of teh City column is determined using the aggregation function.
**gross_income = City['gross income'].sum().reset_index()
* A groupby method also shows the gross income of each city and the city with the highest total gross income is determined using the .max() method.
**gross_income.max().reset_index()
* A table showing the Unit Price, Quantity and gross margin percentage was generated using the GroupBy method.
* Also the product line and gross income are generated with the groupby function.
**other_columns = City['Unit price', 'Quantity', 'gross margin percentage'].sum()
From this, City with the highest Unit price, highest quantity, gross margin percentage was determined, as well as Product line against Gross income to determine the product line with the highest gross income.
### Data Visualization
* The use of countplot to determine the branch with the highest sales record.
* Also, using countplot to determine the highest payment method used.
* The city with the highest sales was also determined using the count plot.
* The sales in different product line was determined using countplot()
* The payment method versus product line was explored to determine the payment method mostly used for each product line.
* The payment method mostly used in each branch was determined using the countplot() method.
* The customer's level of satisfaction in each branch was determined using the boxplot() by plotting the 'Rating column' against 'Branch'.
* It is believed that gender type affects the type of product being purchased at the supermarket. Hence, a catplot of the 'boxen' kind was used to determine what each gender buy most.
* A catplot() method of kind 'point' was used to compare Product line, Unit price and Quantity.
* In further Data analysis, countplot() was used to determine the payment method preferred by each gender.
*sns.countplot(x = 'Payment', data = df, hue = 'Gender').set_title('Gender vs Payment method');
* The plotting of Gender against City also determines the number of each gender that makes more purchase.
*sns.countplot(x = 'City', data = df, hue = 'Gender').set_title('Gender vs City');
* The last part showed a catplot() of the kind 'violiin' that shows the City that pays the highest tax.
*sns.catplot(x = 'City', y = 'Tax 5%', kind = 'violin', data = df, aspect = 4);
### Insight
The standard deviation of the columns are not too low, and hence the values of the datasets does not deviate too much from the mean.
25% of customers made a Total purchase of N44792 and below, while the gross income made from 25% of customers was N2153 and below
Also, 75% of customers made a Total purchase of N169686 and below, while the gross income made from 75% of customers was N8080 and below.
From the Minimum and Maximum, we can say that the total purchase ranges from N3844 - N375354, while the gross income ranges from N183 - N17874.
The minimum and the maximum ratings also ranges from 4 - 10, which denote that the minimum level of satisfaction experienced by customers is 4/10, while the maximum is 10 and the average quantity purchased is 5.5.
Using the isnull() and notna() method, we realized that there were no missing data in the data sets.
With the GroupBy aggregate method, the gross income of Lagos, Abuja and Portharcourt were gotten, and the max() method shows Portharcourt to return the highest gross income of N3,790,927.08
Checking the gross income of the product lines, Food and beverages has the highest gross income, while Health and Beauty experienced the lowest. This may be due to Food being one of the primary human needs of people.
By comparing the different branches A, B, C and quantity, it was realized that Branch A has the highest Quantity purchased while Branch B has the least.Using the countplot() method, Branch A records the highest sales. The countplot() method also shows that the Epay payment is the most used method of Payment across the Branches.
Using the countplot method to check Sales across Lagos, Abuja and Portharcourt, Lagos City rrecorded the highest Sales trend, while Abuja recorded the least.~
### Future Work
Those factors that makes Lagos City to emerge as the City witht hte highest sales, can be explored, and the outcome can be used to drive sales in other Cities.
### Standout section
he groupby method was further used to explore gross income for te different product lines. From the result, Food and beverages has the highest gross income, while Health and Beauty experienced the lowest.
Also, the countplot() method returns Portharcourt to pay the highest Tax whenCity was plotted against Tax at 5%. From previous analysis, we also know that Portharcourt ha sthe highest gross income. There is a relationship between Gross income and Tax.
|
Swift
|
UTF-8
| 2,692 | 2.875 | 3 |
[] |
no_license
|
//
// Provider.swift
// router
//
// Created by agies on 7/3/18.
// Copyright © 2018 agies. All rights reserved.
//
import UIKit
public protocol ControllerProvider {
func get<TController: UIViewController>(byName name: String) -> TController
}
public class StoryboardControllerProvider: ControllerProvider {
static public var shared = StoryboardControllerProvider()
var controllers = [String: WeakWrapper]()
let bundle: Bundle
public init(bundle: Bundle = Bundle.main) {
self.bundle = bundle
}
public func get<TController: UIViewController>(byName name: String) -> TController {
let finder = name.components(separatedBy: ".")
if bundle.path(forResource: finder[0], ofType: "storyboardc") == nil {
fatalError("Cannot find Storyboard \(finder[0])")
}
let strategy = finder.count > 1 ? ViewControllerFactoryStrategy.withIdentifier(finder[1]) : ViewControllerFactoryStrategy.initialViewController
return get(from: UIStoryboard(name: finder[0], bundle: bundle), strategy: strategy)
}
public func get<TController: UIViewController>(from storyboard: UIStoryboard, strategy: ViewControllerFactoryStrategy) -> TController {
let name: String
let instantiate: () -> UIViewController?
switch strategy {
case .initialViewController:
name = storyboard.value(forKey: "name") as! String
instantiate = { storyboard.instantiateInitialViewController() }
break
case .withIdentifier(let identifier):
name = identifier
instantiate = { storyboard.instantiateViewController(withIdentifier: identifier) }
break
}
if let c = controllers[name] {
return c.getObj(TController.self)
} else {
let wrapper = WeakWrapper(factory: {
guard let controller = instantiate() else {
fatalError("Cannot find controller \(name)")
}
return controller
})
controllers[name] = wrapper
return wrapper.getObj(TController.self)
}
}
}
public enum ViewControllerFactoryStrategy {
case initialViewController
case withIdentifier(String)
}
public class WeakWrapper {
let factory: () throws -> AnyObject
weak var _obj: AnyObject?
func getObj<T: AnyObject>(_ class: AnyObject.Type) -> T {
if _obj == nil {
_obj = try! factory()
}
return _obj as! T
}
var exists: Bool {
get { return _obj != nil }
}
init(factory: @escaping () throws -> AnyObject) {
self.factory = factory
}
}
|
Markdown
|
UTF-8
| 7,113 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
# Scratcher.js #
A tiny `scratch off` pluggin based on HTML5 canvas for mobile.
Have only 2.3k after gzip.
<a href="http://xiaoyuze.com/demo/scratcher/index.html" target="_blank">Here's a live demo</a>
## Support ##
IE9+ & all mordern browser & all mobile browser (Android 2.3+).
## Dependence ##
Jquery/Zepto needed.
## Quick Start ##
AMD supported, so you can easily use it like:
```javascript
require(['Scratcher'], function(Scratcher) {
var scratcher = new Scratcher({
selector: '#canvas',
imgUrl: 'cat2.jpg',
onLoadFinish: function() {
console.log("load finish");
},
onScratch: function() {
console.log("scratching");
},
onScratchFinish: function() {
console.log("finish");
}
});
scratcher.start();
})
```
If you're not using AMD, the `Scratcher` function will be set under global `window`.
Use it like:
```javascript
var scratcher = new Scratcher({
selector: '#canvas',
imgUrl: 'cat2.jpg',
onLoadFinish: function() {
console.log("load finish");
},
onScratch: function() {
console.log("scratching");
},
onScratchFinish: function() {
console.log("finish");
}
});
scratcher.start();
```
## Parameters ##
`Scratcher` function accept one parameter `options`
```javascript
options : {
/**
* Your canvas element's css selector, like '#canvas_id'
*/
selector : null,
/**
* The image url you want to scratch
*/
imgUrl : options.imgUrl,
/**
* You can set your canvas element's width and height,
* if not passing this param, we'll get them when initilizing.
*/
width : null,
height : null,
/**
* The scratch's weight, decide how big the scratching pen will be.
* Default to be 80.
*/
weight : 80,
/**
* Whether or not make the canvas ready to scratch
* when NEW the Scrather.
*
* Default to be false.
*
* You can use the `start` Function to set the
* canvas to be ready whenever you needed.
*/
startRightNow : false,
/**
* By default the canvas' size will be set to twice as it's
* original size due to our optimization for retina device,
* you can cancel that by set this option to `true`.
*
* !!NOTICE:
* When you need to optimise for retina, don't forget to set your
* canvas' width/height in your css style!
* If not, every position caculating will be set to twice as it real is.
*/
noRetina : false,
/**
* The rate that how accuracy that we caculate how many pixels are
* lefted on canvas.
* The bigger this value, the less accurate result will come out.
* However, set it to a bigger value you can achieve
* a better performance.
*/
leftCountAccuracy : 64,
/**
* Whether or not to use caculation debouncing.
* When this value is setted to false, you can get more
* accurate on caculating how many pixels are lefted on canvas,
* but it will EXTREMELY slow your app down,
* ESPECIALLY on old Androids.
*/
useDebouncing : true,
/**
* If you're using debouncing, this option will define
* how long the time gap is between we check how many pixels are
* left on canvas. Default to be 500ms.
*/
debouncingTimeGap : 500,
/**
* If you are really concern about the canvas' performance,
* and you do need to detect whether the user has scratched finish or not,
* you can set this option to true.
*
* We will simply caculate how many times that user moved,
* and when the time the user moves is more enough,
* we will trigger your callback when user is click/touch end.
*/
useFakeCaculate : false
```
## Method ##
After you NEW an Scratcher, you will get a Scratcher object, which contains these methods.
```javascript
var scratcher = new Scratcher({
selector : '#canvas',
imgUrl : 'image.jpg'
});
```
###scratcher.start() ###
Initialize the canvas and make it ready to be scratched.
If you don't set the `options.startRightNow = true` when NEW your Scratcher, you need to call this function when your user need to scratch.
###scratcher.clear() ###
Clear the image that drawn on the canvas.
This function will be called when the `scratchFinish` event fired, you can also call it your self when you need to clear the mask.
###scratcher.checkLeft() ###
Caculate how many pixels that are lefted on the canvas.
If you set the `options.onScratchFinish` callback or add an event listener for `scratchFinish` event, this function will be called when the user is scratching the canvas. You can also call it yourself.
`Return`
The percentage of the left area on canvas.
`Example`
If the user has scratched off 90% of the canvas, you will get 10 in return.
When the percentage is less 3%, the `scratchFinish` event will be fired.
###scratcher.resize() ###
Recaculate the canvas' size and position.
We'll caculate the canvas' size and its position when initializing, if your canvas element has changed its size or position, you need to call this function to recaculate them.
###scratcher.on('eventName',callback) ###
Add an event listener for the specific event.
You can call this function repeatedly for different handlers, when the event fired, they will be called one by one in the order of you set them.
###scratcher.off('eventName',[callback]) ###
Remove the event listener's handler.
If you pass the callback parameter, the specific callback function will be removed.
If not passing this paramter, we'll clear all callback functions for this event.
###scratcher.trigger('eventName') ###
Trigger the specific event, all callbacks of this event will be called.
##Events ##
We support three events now, `scratchFinish`,`scratch` and `loadFinish`.
You can use the `on` function to add new callback for them, or you can set the callback when initializing by set `options.onScratchFinish` and so on.
###scratchFinish ###
This event will be fired when you've set a callback function for it.
If the `scratchFinish` event's callback list is empty, we won't caculate the left percentage of the canvas for performance purpose.
###scratch ###
This event will be fired when the user is scratching the canvas.
###loadFinish ###
This event will be fired when the image you want to load and draw it on canvas is load finish.
For example, you can make some notice when the image is load finish and it's ready to be scratched.
## Notice ##
Because when we want to caculate the left percentage that is still on the canvas, we need to load the whole data of the image in memory, and caculate the color of each pixels. The bigger your image is, the bigger cost will take. In some old Android device, this may cost a serious performance problem, even make the browser crash! Please use it carefully when you need to caculate them, or you can use the fake caculation by setting the `options.useFakeCaculate` to `true`. You can simply avoid this problem by not setting any callbacks for the `scratchFinish` event.
If you have any suggestions or find any issues, please feel free to contact me!
My email is xiaoyuze88@gmail.com.
Hope this will help you.
Thanks!
|
C++
|
UTF-8
| 988 | 2.71875 | 3 |
[] |
no_license
|
const int micPin = 0;
const int baseLine = 338;
void setup ()
{
Serial.begin (9600);
pinMode (10, OUTPUT);
pinMode (11, OUTPUT);
pinMode (12, OUTPUT);
pinMode (13, OUTPUT);
}
void oscilloscope (int reading)
{
int x = reading + 175;
Serial.write( 0xff );
Serial.write( (x >> 8) & 0xff );
Serial.write( x & 0xff );
}
void ledOutput (int devRead)
{
if (devRead > 5)
digitalWrite (13, HIGH);
else
digitalWrite (13, LOW);
if (devRead > 55)
digitalWrite (12, HIGH);
else
digitalWrite (12, LOW);
if (devRead > 105)
digitalWrite (11, HIGH);
else
digitalWrite (11, LOW);
if (devRead > 155)
digitalWrite (10, HIGH);
else
digitalWrite (10, LOW);
}
void loop ()
{
int reading = analogRead (micPin);
int devRead = reading - 338;
double time = micros ();
if (reading > 340)
{
Serial.print (time);
Serial.print (": ");
Serial.println (reading);
}
oscilloscope (reading);
ledOutput (devRead);
delay (0);
}
|
TypeScript
|
UTF-8
| 1,950 | 2.78125 | 3 |
[] |
no_license
|
export class Address {
constructor(private _addrId?: number,
private _addrLongitude?: number,
private _addrLatitude?: number,
private _addrCountry?: string,
private _addrCity?: string,
private _addrStreetName?: string,
private _addrStreetNumber?: string,
private _addrPostalCode?: string,
private _addrEmpId?: number) {
}
static emptyAddress() {
return {
addrId: null,
addrLongitude: null,
addrLatitude: null,
addrCountry: "",
addrCity: "",
addrStreetName: "",
addrStreetNumber: "",
addrPostalCode: "",
addrEmpId: null
};
}
get addrId(): number {
return this._addrId;
}
set addrId(value: number) {
this._addrId = value;
}
get addrLongitude(): number {
return this._addrLongitude;
}
set addrLongitude(value: number) {
this._addrLongitude = value;
}
get addrLatitude(): number {
return this._addrLatitude;
}
set addrLatitude(value: number) {
this._addrLatitude = value;
}
get addrCountry(): string {
return this._addrCountry;
}
set addrCountry(value: string) {
this._addrCountry = value;
}
get addrCity(): string {
return this._addrCity;
}
set addrCity(value: string) {
this._addrCity = value;
}
get addrStreetName(): string {
return this._addrStreetName;
}
set addrStreetName(value: string) {
this._addrStreetName = value;
}
get addrStreetNumber(): string {
return this._addrStreetNumber;
}
set addrStreetNumber(value: string) {
this._addrStreetNumber = value;
}
get addrPostalCode(): string {
return this._addrPostalCode;
}
set addrPostalCode(value: string) {
this._addrPostalCode = value;
}
get addrEmpId(): number {
return this._addrEmpId;
}
set addrEmpId(value: number) {
this._addrEmpId = value;
}
}
|
C#
|
UTF-8
| 3,732 | 2.6875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DemoCRUD.Models;
namespace DemoCRUD.Controllers
{
public class ProductController : Controller
{
// GET: Product
public ActionResult Index()
{
var db = new DemoCrudDbContext();
var products = db.Products.ToList();
var categories = db.Categories.ToList();
ViewBag.Categories = new SelectList(categories, "Id", "Name");
return View(products);
}
public ActionResult Create()
{
var db = new DemoCrudDbContext();
var categories = db.Categories.ToList();
ViewBag.Categories = new SelectList(categories, "Id", "Name");
return View();
}
public JsonResult GetProductJson(int id)
{
var db = new DemoCrudDbContext();
var product = db.Products.FirstOrDefault(x => x.Id == id);
if (product != null)
{
return Json(new { status = true, data = product }, JsonRequestBehavior.AllowGet);
}
return Json(new { status = false }, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult CreateProduct(Product data)
{
var db = new DemoCrudDbContext();
try
{
db.Products.Add(data);
db.SaveChanges();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
return RedirectToAction("Index");
}
//Update
public ActionResult Update(int id)
{
var db = new DemoCrudDbContext();
var product = db.Products.FirstOrDefault(x => x.Id == id);
if (product != null)
{
return View(product);
}
else
{
return RedirectToAction("E404", "Home");
}
}
[HttpPost]
public ActionResult UpdateProduct(Product data)
{
//
//
var db = new DemoCrudDbContext();
try
{
var product = db.Products.FirstOrDefault(x => x.Id == data.Id);
if (product != null)
{
//update
product.Amount = data.Amount;
product.Name = data.Name;
product.Price = data.Price;
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return RedirectToAction("E404", "Home");
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public ActionResult Delete(int id)
{
var db = new DemoCrudDbContext();
try
{
var product = db.Products.FirstOrDefault(x => x.Id == id); // Lấy thằng đầu tiên nếu k có thì trả về null
if (product != null)
{
//update
db.Products.Remove(product);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return RedirectToAction("E404", "Home");
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
}
|
C++
|
UTF-8
| 456 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
#include "simple_task.h"
SimpleTask::SimpleTask(char const* n, unsigned et) :
Task(n), executionTime(et), progress(0) {}
void SimpleTask::print(std::ostream& os) const {
os << "Проста ";
Task::print(os);
}
unsigned SimpleTask::work(unsigned t) {
if (isFinished() || t == 0)
return t;
// executionTime > progress
unsigned spentEffort = std::min(t, executionTime - progress);
progress += spentEffort;
return t - spentEffort;
}
|
JavaScript
|
UTF-8
| 1,173 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
import expect from 'expect';
const { split } = require('../../').array;
describe('array.split', () => {
it('should export a function', () => {
expect(split).toBeA('function');
});
describe('called with bad parameters', () => {
it('should throw error(s)', () => {
expect(() => split(null)).toThrow();
expect(() => split([], 'x')).toThrow();
expect(() => split([], 1)).toThrow();
expect(() => split([], -5)).toThrow();
});
});
describe('called with good parameters', () => {
it('should return as expected', () => {
// case 1
const input1 = [[1, 2, 3], 2];
const expected1 = [[1, 2], [3]];
expect(split(...input1)).toEqual(expected1);
// case 2
const input2 = [[1], 2];
const expected2 = [[1]];
expect(split(...input2)).toEqual(expected2);
// case 3
const input3 = [[1, 2, 3, 4, 5, 6, 7, 8, 9], 3];
const expected3 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
expect(split(...input3)).toEqual(expected3);
// case 4
expect(split([], 4)).toEqual([]);
expect(split([], 2)).toEqual([]);
});
});
});
|
Go
|
UTF-8
| 579 | 3.359375 | 3 |
[] |
no_license
|
package main
import "fmt"
// 超时
func climbStairs2(n int) int {
if n == 1 {
return 1
}
if n == 2 {
return 2
}
return climbStairs2(n-1) + climbStairs2(n-2)
}
// 动态规划
func climbStairs(n int) int {
if n == 1 {
return 1
}
var dp []int
if n > 1 {
dp = make([]int, n)
dp[0] = 1
dp[1] = 2
}
for i := 2; i < n; i++ {
dp[i] = dp[i-1] + dp[i-2]
}
return dp[n-1]
}
// 官方题解
func climbStairs3(n int) int {
p, q, r := 0, 0, 1
for i := 1; i <= n; i++ {
p = q
q = r
r = p + q
}
return r
}
func main() {
fmt.Println(climbStairs(6))
}
|
Java
|
UTF-8
| 5,754 | 1.859375 | 2 |
[] |
no_license
|
package com.google.android.gms.internal.maps;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import com.google.android.gms.dynamic.IObjectWrapper;
import com.google.android.gms.dynamic.IObjectWrapper.Stub;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PatternItem;
import java.util.ArrayList;
import java.util.List;
public final class zzj extends zza
implements zzh
{
zzj(IBinder paramIBinder)
{
super(paramIBinder, "com.google.android.gms.maps.model.internal.ICircleDelegate");
}
public final LatLng getCenter()
throws RemoteException
{
Parcel localParcel = zza(4, zza());
LatLng localLatLng = (LatLng)zzc.zza(localParcel, LatLng.CREATOR);
localParcel.recycle();
return localLatLng;
}
public final int getFillColor()
throws RemoteException
{
Parcel localParcel = zza(12, zza());
int i = localParcel.readInt();
localParcel.recycle();
return i;
}
public final String getId()
throws RemoteException
{
Parcel localParcel = zza(2, zza());
String str = localParcel.readString();
localParcel.recycle();
return str;
}
public final double getRadius()
throws RemoteException
{
Parcel localParcel = zza(6, zza());
double d = localParcel.readDouble();
localParcel.recycle();
return d;
}
public final int getStrokeColor()
throws RemoteException
{
Parcel localParcel = zza(10, zza());
int i = localParcel.readInt();
localParcel.recycle();
return i;
}
public final List<PatternItem> getStrokePattern()
throws RemoteException
{
Parcel localParcel = zza(22, zza());
ArrayList localArrayList = localParcel.createTypedArrayList(PatternItem.CREATOR);
localParcel.recycle();
return localArrayList;
}
public final float getStrokeWidth()
throws RemoteException
{
Parcel localParcel = zza(8, zza());
float f = localParcel.readFloat();
localParcel.recycle();
return f;
}
public final float getZIndex()
throws RemoteException
{
Parcel localParcel = zza(14, zza());
float f = localParcel.readFloat();
localParcel.recycle();
return f;
}
public final boolean isClickable()
throws RemoteException
{
Parcel localParcel = zza(20, zza());
boolean bool = zzc.zza(localParcel);
localParcel.recycle();
return bool;
}
public final boolean isVisible()
throws RemoteException
{
Parcel localParcel = zza(16, zza());
boolean bool = zzc.zza(localParcel);
localParcel.recycle();
return bool;
}
public final void remove()
throws RemoteException
{
zzb(1, zza());
}
public final void setCenter(LatLng paramLatLng)
throws RemoteException
{
Parcel localParcel = zza();
zzc.zza(localParcel, paramLatLng);
zzb(3, localParcel);
}
public final void setClickable(boolean paramBoolean)
throws RemoteException
{
Parcel localParcel = zza();
zzc.writeBoolean(localParcel, paramBoolean);
zzb(19, localParcel);
}
public final void setFillColor(int paramInt)
throws RemoteException
{
Parcel localParcel = zza();
localParcel.writeInt(paramInt);
zzb(11, localParcel);
}
public final void setRadius(double paramDouble)
throws RemoteException
{
Parcel localParcel = zza();
localParcel.writeDouble(paramDouble);
zzb(5, localParcel);
}
public final void setStrokeColor(int paramInt)
throws RemoteException
{
Parcel localParcel = zza();
localParcel.writeInt(paramInt);
zzb(9, localParcel);
}
public final void setStrokePattern(List<PatternItem> paramList)
throws RemoteException
{
Parcel localParcel = zza();
localParcel.writeTypedList(paramList);
zzb(21, localParcel);
}
public final void setStrokeWidth(float paramFloat)
throws RemoteException
{
Parcel localParcel = zza();
localParcel.writeFloat(paramFloat);
zzb(7, localParcel);
}
public final void setVisible(boolean paramBoolean)
throws RemoteException
{
Parcel localParcel = zza();
zzc.writeBoolean(localParcel, paramBoolean);
zzb(15, localParcel);
}
public final void setZIndex(float paramFloat)
throws RemoteException
{
Parcel localParcel = zza();
localParcel.writeFloat(paramFloat);
zzb(13, localParcel);
}
public final boolean zzb(zzh paramzzh)
throws RemoteException
{
Parcel localParcel1 = zza();
zzc.zza(localParcel1, paramzzh);
Parcel localParcel2 = zza(17, localParcel1);
boolean bool = zzc.zza(localParcel2);
localParcel2.recycle();
return bool;
}
public final void zze(IObjectWrapper paramIObjectWrapper)
throws RemoteException
{
Parcel localParcel = zza();
zzc.zza(localParcel, paramIObjectWrapper);
zzb(23, localParcel);
}
public final int zzj()
throws RemoteException
{
Parcel localParcel = zza(18, zza());
int i = localParcel.readInt();
localParcel.recycle();
return i;
}
public final IObjectWrapper zzk()
throws RemoteException
{
Parcel localParcel = zza(24, zza());
IObjectWrapper localIObjectWrapper = IObjectWrapper.Stub.asInterface(localParcel.readStrongBinder());
localParcel.recycle();
return localIObjectWrapper;
}
}
/* Location: E:\Study\Tools\apktool2_2\dex2jar-0.0.9.15\classes_viber_2_dex2jar.jar
* Qualified Name: com.google.android.gms.internal.maps.zzj
* JD-Core Version: 0.6.2
*/
|
PHP
|
UTF-8
| 1,197 | 2.703125 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
<?php
namespace Application\Filter\Api;
use Laminas\Filter\AbstractFilter;
use Laminas\Stdlib\ArrayUtils;
use function explode;
use function is_string;
use function strpos;
use function substr;
class FieldsFilter extends AbstractFilter
{
protected array $fields = [];
public function setFields(array $fields): self
{
$this->fields = $fields;
return $this;
}
private function parseValue(string $value): array
{
$dotPos = strpos($value, '.');
if ($dotPos !== false) {
$fieldName = (string) substr($value, 0, $dotPos);
$fieldValue = $this->parseValue(substr($value, $dotPos + 1));
} else {
$fieldName = $value;
$fieldValue = true;
}
return [
$fieldName => $fieldValue,
];
}
/**
* @param mixed $value
*/
public function filter($value): array
{
$value = is_string($value) ? $value : '';
$result = [];
foreach (explode(',', $value) as $field) {
$pair = $this->parseValue($field);
$result = ArrayUtils::merge($result, $pair);
}
return $result;
}
}
|
Python
|
UTF-8
| 2,401 | 2.765625 | 3 |
[
"Apache-2.0"
] |
permissive
|
# -*- coding: utf-8 -*-
"""
Secrets factory.
"""
# Standard imports
import logging
from abc import (
ABC,
abstractmethod,
)
from collections import OrderedDict
from inspect import getdoc
logger = logging.getLogger(__name__)
# pylint: disable=missing-function-docstring
class SecretFactory:
"""
Factory class for generating secrets.
"""
class_map = {}
# def _get_secret_class(self, class_name):
# """
# Return secret class.
# """
# secret_class = self.class_map.get('class_name')
# if not secret_class:
# raise SecretTypeNotFoundError(class_name)
# return secret_class
@classmethod
def register_handler(cls, secret_type):
def wrapper(secret_class):
cls.class_map[secret_type] = secret_class
return secret_class
return wrapper
@classmethod
def get_handler(cls, secret_type):
return cls.class_map[secret_type]()
@classmethod
def get_handler_classes(cls):
return [
secret_class for secret_class
in cls.class_map.values()
]
@classmethod
def add_parser_arguments(cls, parser):
for secret_class in cls.get_handler_classes():
secret_class().add_parser_arguments(parser)
return parser
@classmethod
def describe_secret_classes(cls):
return [
secret_class().describe()
for secret_class in cls.get_handler_classes()
]
class SecretHandler(ABC):
"""
Abstract secrets class.
"""
@abstractmethod
def generate_secret(self, **kwargs):
raise NotImplementedError
def add_parser_arguments(self, parser):
"""
Override this method with argparse arguments specific
to the secret type as necessary.
"""
return parser
def is_generable(self):
result = None
try:
result = self.generate_secret()
except NotImplementedError:
return False
except RuntimeError:
return True
return result not in ['', None]
def describe(self):
return OrderedDict(
{
'Type': self.__module__.split('.')[-1],
'Description': getdoc(self),
'Generable': self.is_generable()
}
)
# vim: set ts=4 sw=4 tw=0 et :
|
C
|
UTF-8
| 7,785 | 2.984375 | 3 |
[
"Apache-2.0"
] |
permissive
|
#include <string.h>
#include "cprini.h"
/*
*
***************************************************************************
*
* This is the end of the debugging code, and the beginning
* of the printing functions proper. The code below contains
* five user-callable functions: cprini, cprin, cprin2, cprinf,
* cprin_start_stop. Their functions are as follows.
*
* cprini - communicates to the function cprin8 (NOT a user-callable
* function) the names of the two files on which the output
* will be written. Please note that the name "stdout" is
* treated differently from all other names: specifying it
* will cause the output to be written on the standard output
* - screen, most probably.
* cprin - prints a real (of the type "float") array
* cprin2 - prints a double precision (of the type "double") array
* cprinf - prints an integer array
* cprina - prints a character array, string
* cprin_start_stop - starts and stops printing to either or both
* output files
*
***************************************************************************
*
*/
void cprin_init(char *str17, char *str27)
{
char *mes;
float *ap;
int *afp;
double *adp;
char *acp;
int n, m;
int itype;
int i1, i2;
//int *adp,*ap,itype,i1,i2,mes,afp,n,acp;
/* This function initializes which files to print to. */
/* To print to ONLY one file, set one of str17, str18 to " ". */
/* i.e., make the call cprini("stdout"," ") to print ONLY to */
/* the screen. Anything other than " ", such as " ", will cause */
/* a file to be created, in this case " ". */
itype=11;
cprin_master(mes, ap, afp, adp, acp, m, n, itype, str17, str27, i1, i2);
return;
}
void cprin_start_stop(int i1, int i2)
{
char *mes;
float *ap;
int *afp;
double *adp;
char *acp;
int n, m;
int itype;
char *str17,*str27;
// . . . stop/resume. i1 and i2 control printing to file
// str17 and str27, respectively. 0 means stop printing,
// and 1 means print.
itype=21;
cprin_master(mes,ap,afp,adp,acp,m,n,itype,str17,str27,i1,i2);
return;
}
void cprin_message(char *mes)
{
float *ap;
int *afp;
char *acp;
int itype;
char *str17, *str27;
int i1, i2;
double *adp;
int m, n;
itype = 99;
cprin_master(mes,ap,afp,adp,acp,m,n,itype,str17,str27,i1,i2);
return;
}
void cprin_skipline(int n)
{
float *ap;
int *afp;
char *acp;
int itype;
char *str17, *str27;
int i1, i2;
int status;
char *mes = NULL;
double *adp;
int m;
// printf("in cprin_skipline, n = %d\n", n);
//exit(status);
//int *ap,*afp,itype,str17,str27,i1,i2,acp;
/*
* Print double precision data
*/
itype = 77;
//printf("in cprin_skipline, itype = %d\n", itype);
cprin_master(mes,ap,afp,adp,acp,m,n,itype,str17,str27,i1,i2);
return;
}
void cprinz(char *mes, double _Complex *adp, int n)
{
float *ap;
int *afp;
char *acp;
int itype;
char *str17, *str27;
int i1, i2;
int status;
int n2, m;
//printf("n = %ld\n", n);
//exit(status);
//int *ap,*afp,itype,str17,str27,i1,i2,acp;
/*
* Print double precision data
*/
itype=7;
n2 = 2*n;
cprin_master(mes,ap,afp, (double *)adp,
acp,m,n2,itype,str17,str27,i1,i2);
return;
}
void cprinf(char *mes, int *afp, int n)
{
float *ap;
int itype, i1, i2, m;
double *adp;
char *acp, *str17, *str27;
//
// print integer data
//
itype = 2;
cprin_master(mes, ap, afp, adp, acp, m, n, itype, str17, str27, i1, i2);
return;
}
void cprind(char *mes, double *adp, int n) {
float *ap;
int itype, i1, i2, m, *afp;
char *acp, *str17, *str27;
//
// print double precision data
//
itype = 3;
cprin_master(mes, ap, afp, adp, acp, m, n, itype, str17, str27, i1, i2);
return;
}
void cprind_matrix(char *mes, double *adp, int m, int n)
{
float *ap;
int *afp;
char *acp;
int itype;
char *str17, *str27;
int i1, i2;
int status;
int n2;
//printf("n = %ld\n", n);
//exit(status);
//int *ap,*afp,itype,str17,str27,i1,i2,acp;
/*
* Print double precision data
*/
itype=33;
cprin_master(mes,ap,afp,adp,acp,m,n,itype,str17,str27,i1,i2);
return;
}
void cprin_master(char *mes, float *ap, int *afp, double *adp, char *acp, int m,
int n, int itype, char *str17, char *str27, int i1, int i2)
{
static int ifprint1,ifprint2,ifstr1,ifstr2;
static FILE *st1,*st2;
int iii;
// If this is the initialization call - open the
// files str17, str27 after checking if either is null, i.e. " "
//printf("in cprin_master, itype = %d\n", itype);
//return;
if(itype==11)
{
ifprint1=0;
ifprint2=0;
ifstr1=0;
ifstr2=0;
iii=strcmp(str17," ");
if(iii != 0) ifprint1=1;
if(iii != 0) ifstr1=1;
iii=strcmp(str27," ");
if(iii != 0) ifprint2=1;
if(iii != 0) ifstr2=1;
if(ifprint1 == 1)
{
iii=strcmp(str17,"stdout");
if(iii != 0) st1=fopen(str17,"w");
if(iii == 0) st1=stdout;
}
if(ifprint2 == 1) {
iii=strcmp(str27,"stdout");
if(iii != 0) st2=fopen(str27,"w");
if(iii == 0) st2=stdout;
}
return;
}
//
// If this is the "stop/resume" call - stop/resume printing
//
if(itype==21){
if(i1==0) ifprint1=0;
if((i1 != 0) && (ifstr1 != 0)) ifprint1=1;
if(i2==0) ifprint2=0;
if((i2 != 0) && (ifstr2 != 0)) ifprint2=1;
return;
}
//printf("ifprint1 = %d\n", ifprint1);
//printf("ifprint2 = %d\n", ifprint2);
if(ifprint1 !=0) cprin_all(mes,ap,afp,adp,acp,m,n,itype,st1);
if(ifprint2 !=0) cprin_all(mes,ap,afp,adp,acp,m,n,itype,st2);
return;
}
void cprin_all(char *mes, float *ap, int *afp, double *adp, char *acp,
int m, int n, int itype, FILE *str)
{
int i;
/*
* Process the message
*/
if(mes) fprintf(str,"%s\n",mes);
if (itype == 99) return;
// Process the double precision data to be printed
if(itype == 3) {
for(i=0; i<n; i=i+1) {
fprintf(str," %11.4le", adp[i]);
if(i%6==5 || i==n-1) fprintf(str,"\n");
}
return;
}
//
// print out the double precision matrix
//
if(itype ==33) {
int ijk = 0;
int j;
//printf("m = %d\n", m);
//printf("n = %d\n", n);
//return;
for(i=0; i<m; i=i+1) {
for (j=0; j<n; j++) {
fprintf(str," %11.4le", adp[ijk]);
ijk++;
}
fprintf(str,"\n");
}
return;
}
/*
* Process the complex double precision data to be printed
*/
if(itype ==7)
{
for(i=0; i<n; i=i+2)
{
fprintf(str," (%11.4le %+11.4le)", adp[i], adp[i+1]);
if(i%6==4 || i==n-2) fprintf(str,"\n");
}
return;
}
/*
* Process the integer data to be printed
*/
if(itype ==2)
{
for(i=0; i<n; i=i+1)
{
fprintf(str," %7d", afp[i]);
if(i%10==9 || i==n-1) fprintf(str,"\n");
}
return;
}
/*
* Process the single precision data to be printed
*/
if(itype ==1)
{
for(i=0; i<n; i=i+1)
{
fprintf(str," %11.4le", ap[i]);
if(i%6==5 || i==n-1) fprintf(str,"\n");
}
return;
}
/*
* Process the character data to be printed
*/
if(itype==4) {
for(i=0; i<n; i++) {
fprintf(str,"%c", acp[i]);
if(i%60==59 || i==n-1) fprintf(str,"\n");
}
return;
}
//
// insert a line skip
//
if(itype == 77) {
for (i=0; i<n; i++) {
fprintf(str,"\n");
}
}
return;
}
|
C#
|
UTF-8
| 1,484 | 3.046875 | 3 |
[] |
no_license
|
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using PizzaGuys.Models;
namespace PizzaGuys.Helper
{
public static class SessionHelper
{
public static void SetSession(this ISession session, string key, object o)
{
var str = JsonConvert.SerializeObject(o, Formatting.None,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
}
);
session.SetString(key, str);
}
public static T GetSession<T>(this ISession session, string key)
{
var value = session.GetString(key);
if (value != null)
{
return JsonConvert.DeserializeObject<T>(value);
}
return default(T);
}
public static Customer GetLoggedInUser(this ISession session)
{
return session.GetSession<Customer>("LoggedInUser");
}
public static Order GetOrder(this ISession session)
{
return session.GetSession<Order>("LoggedInOrder");
}
public static void SetLoggedInUser(this ISession session, Customer user)
{
session.SetSession("LoggedInUser", user);
}
public static void SetOrder(this ISession session, Order order)
{
session.SetSession("LoggedInOrder", order);
}
}
}
|
Java
|
UTF-8
| 659 | 2.4375 | 2 |
[] |
no_license
|
package com.controllerface.cmdr_j.classes.recipes;
import com.controllerface.cmdr_j.classes.data.ItemEffects;
import com.controllerface.cmdr_j.classes.data.CostData;
import com.controllerface.cmdr_j.enums.equipment.modules.stats.ItemGrade;
public abstract class AbstractTechnologyRecipe extends AbstractRecipe
{
public AbstractTechnologyRecipe(String name, ItemEffects effects, CostData ... cost)
{
super(name, ItemGrade.TechnologyBroker, effects, cost);
}
@Override
public String getShortLabel()
{
return getName();
}
@Override
public String getDisplayLabel()
{
return toString();
}
}
|
Java
|
UTF-8
| 34,113 | 1.828125 | 2 |
[] |
no_license
|
package eon.hg.fap.web.manage.action;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import eon.hg.fap.common.CommUtil;
import eon.hg.fap.common.util.metatype.Dto;
import eon.hg.fap.common.util.metatype.impl.HashDto;
import eon.hg.fap.core.body.ResultBody;
import eon.hg.fap.core.constant.AeonConstants;
import eon.hg.fap.core.domain.virtual.SysMap;
import eon.hg.fap.core.mv.JModelAndView;
import eon.hg.fap.core.query.QueryObject;
import eon.hg.fap.core.security.SecurityUserHolder;
import eon.hg.fap.core.tools.JsonHandler;
import eon.hg.fap.core.tools.WebHandler;
import eon.hg.fap.db.model.primary.*;
import eon.hg.fap.db.service.*;
import eon.hg.fap.security.annotation.SecurityMapping;
import eon.hg.fap.web.manage.op.UIManagerOP;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;
@Controller
@RequestMapping("/manage")
public class UIManageAction extends BizAction {
@Autowired
private ISysConfigService configService;
@Autowired
private IUserConfigService userConfigService;
@Autowired
private IUIManagerService uiManagerService;
@Autowired
private IUIConfService uiConfService;
@Autowired
private IElementService elementService;
@Autowired
private UIManagerOP uiManagerOP;
@Autowired
HttpSession httpSession;
@Autowired
IBaseUIService baseUIService;
@SecurityMapping(title = "界面视图管理",value = "ui:view")
@RequestMapping("/ui_manage.htm")
public ModelAndView ui_manage(HttpServletRequest request,
HttpServletResponse response) {
ModelAndView mv = new JModelAndView("fap/ui_manage.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 0, request, response);
return mv;
}
@SecurityMapping("ui:view")
@RequestMapping("/query_uimanager_view.htm")
public @ResponseBody String query_uimanager_view(Long ui_id) throws Exception {
UIManager uimanager = uiManagerService.getObjById(ui_id);
if (uimanager!=null)
uimanager.setUi_id(CommUtil.null2String(uimanager.getId()));
return JsonHandler.toExtJson(uimanager);
}
@SecurityMapping("ui:view")
@RequestMapping("/query_uimanager.htm")
public @ResponseBody String query_uimanager(Long ui_id) throws Exception {
UIManager uimanager = uiManagerService.getObjById(ui_id);
uiManagerService.removeLocal(new Object[]{"detail",httpSession.getId()});
uiManagerService.removeLocal(new Object[]{"confmain",httpSession.getId()});
uiManagerService.removeLocal(new Object[]{"confdetail",httpSession.getId()});
if (uimanager!=null)
uimanager.setUi_id(CommUtil.null2String(uimanager.getId()));
uiManagerService.getPoolCache(new Object[]{"detail", httpSession.getId(), Convert.toStr(ui_id)});
uiManagerService.getPoolCache(new Object[]{"confdetail", httpSession.getId(), Convert.toStr(ui_id)});
uiManagerService.getPoolCache(new Object[]{"confmain", httpSession.getId(), Convert.toStr(ui_id)});
return JsonHandler.toExtJson(uimanager);
}
@SecurityMapping("ui:view")
@RequestMapping("/ui_nullstore.htm")
public @ResponseBody String ui_nullstore(String ui_id) {
List lstView = new ArrayList();
Integer pageCount = Integer.valueOf(0);
String jsonString = JsonHandler.toPageJson(lstView, pageCount);
return jsonString;
}
@SecurityMapping("ui:view")
@RequestMapping("/ui_detail_tree.htm")
public @ResponseBody String ui_detail_tree(@RequestParam Map<String, Object> map, @RequestParam("node") String parent_id) {
Dto dto = new HashDto(map);
dto.put("parent_id", parent_id);
List list = uiManagerOP.getUIDetailTreeChildNodeList(dto,1,false);
return JsonHandler.toJson(list);
}
@SecurityMapping("ui:view")
@RequestMapping("/query_uiconfmain.htm")
public @ResponseBody String query_uiconfmain(String uiconf_id, String xtype) {
QueryObject qoconf = new QueryObject();
qoconf.addQuery("obj.uiconf_type","xtype",xtype,"=");
qoconf.setOrderBy("order_no");
List<UIConf> uiConfList= this.uiManagerService.findConf(qoconf);
QueryObject qoconfmain = new QueryObject();
qoconfmain.addQuery("obj.ui_main.id","uiconf_id",CommUtil.null2Long(uiconf_id),"=");
List<UIConfMain> uiconfmains = this.uiManagerService.findConfMain(qoconfmain);
for (UIConf dtoUiConf : uiConfList) {
dtoUiConf.setUiconf_value(null);
dtoUiConf.setIs_contain(0);
dtoUiConf.setEditmode("0");
for (UIConfMain uiconfmain : uiconfmains) {
if (StrUtil.equals(uiconfmain.getUiconf_field(), dtoUiConf.getUiconf_field())) {
dtoUiConf.setUiconf_value(uiconfmain.getUiconf_value());
dtoUiConf.setIs_contain(1);
break;
}
}
}
return JsonHandler.toPageJson(uiConfList);
}
@SecurityMapping("ui:view")
@RequestMapping("/query_uiconfdetail.htm")
public @ResponseBody String query_uiconfdetail(String uiconf_id, String xtype) {
QueryObject qoconf = new QueryObject();
qoconf.addQuery("obj.uiconf_type","xtype",xtype,"=");
qoconf.setOrderBy("order_no");
List<UIConf> uiConfList= this.uiManagerService.findConf(qoconf);
QueryObject qoconfdetail = new QueryObject();
qoconfdetail.addQuery("obj.ui_detail.id","uiconf_id",CommUtil.null2Long(uiconf_id),"=");
List<UIConfDetail> uiconfdetails = this.uiManagerService.findConfDetail(qoconfdetail);
for (UIConf dtoUiConf : uiConfList) {
dtoUiConf.setUiconf_value(null);
dtoUiConf.setIs_contain(0);
dtoUiConf.setEditmode("0");
for (UIConfDetail uiconfdetail : uiconfdetails) {
if (StrUtil.equals(uiconfdetail.getUiconf_field(), dtoUiConf.getUiconf_field())) {
dtoUiConf.setUiconf_value(uiconfdetail.getUiconf_value());
dtoUiConf.setIs_contain(1);
break;
}
}
}
return JsonHandler.toPageJson(uiConfList);
}
@RequestMapping("/append_uicolcache.htm")
public @ResponseBody Dto append_uicolcache(@RequestParam Map<String, Object> inDto) throws Exception {
inDto.remove("reqCode");
inDto.remove("loginuserid");
inDto.put("ui_detail_id", Convert.toStr(new Date().getTime()));
List<Map> dsDetail =uiManagerService.getPoolCache(new Object[]{"detail", httpSession.getId(), Convert.toStr(inDto.get("ui_id"))});
Dto outDto = new HashDto();
if (dsDetail!=null) {
inDto.put("hidden", 0);
inDto.put("field_index", dsDetail.size()+1);
inDto.put("detail_type", 0);
if (CommUtil.ContainsNode(dsDetail, (Map map) -> (map.get("field_name").equals(inDto.get("field_name"))))) {
outDto.put("msg", "新增字段已存在");
outDto.put("success", AeonConstants.FALSE);
} else {
dsDetail.add(inDto);
inDto.put("id", inDto.get("ui_detail_id"));
inDto.put("code", inDto.get("field_name"));
inDto.put("name", inDto.get("field_title"));
inDto.put("text", inDto.get("field_name")+" "+inDto.get("field_title"));
if ("hidden".equals(inDto.get("field_type"))) {
inDto.put("iconCls", "nodeNoIcon");
} else {
inDto.put("iconCls", "nodeYesIcon");
}
outDto.put("data", inDto);
outDto.put("msg", "字段新增成功");
outDto.put("success", AeonConstants.TRUE);
}
}
return outDto;
}
/**
* 界面视图删除缓存字段
* @param inDto
* @return
* @throws Exception
*/
@RequestMapping("/delete_uicolcache.htm")
public @ResponseBody Dto delete_uicolcache(@RequestParam Map<String, Object> inDto) throws Exception {
List<Map> dsDetail =uiManagerService.getPoolCache(new Object[]{"detail", httpSession.getId(), Convert.toStr(inDto.get("ui_id"))});
Dto outDto = new HashDto();
if (dsDetail!=null) {
for (Map dsMap : dsDetail) {
if (Convert.toStr(dsMap.get("ui_detail_id")).equals(Convert.toStr(inDto.get("ui_detail_id")))) {
dsDetail.remove(dsMap);
List<Map> dsUiConfDetail =uiManagerService.getPoolCache(new Object[]{"confdetail", httpSession.getId(), inDto.get("ui_detail_id")});
dsUiConfDetail.clear();
outDto.put("msg", "字段删除成功");
outDto.put("success", AeonConstants.TRUE);
return outDto;
}
}
outDto.put("msg", "指定字段不存在,删除失败");
outDto.put("success", AeonConstants.FALSE);
}
return outDto;
}
/**
* 界面视图主表缓存列
* @param uiconf_id
* @param xtype
* @return
* @throws Exception
*/
@RequestMapping("/cache_uiconfmain.htm")
public @ResponseBody String cache_uiconfmain(String uiconf_id, String xtype) throws Exception {
QueryObject qo = new QueryObject();
if (CommUtil.isNotEmpty(xtype)) {
qo.addQuery("obj.uiconf_type",
new SysMap("xtype", xtype), "=");
}
qo.setOrderBy("order_no");
List<UIConf> uiConfList = this.uiManagerService.findConf(qo);
List<Map> dsUiConfMain =uiManagerService.getPoolCache(new Object[]{"confmain", httpSession.getId(), uiconf_id});
//删除不存在的属性记录 add by cxj 2016.5.27
Iterator<Map> iter = dsUiConfMain.iterator();
while (iter.hasNext()) {
Map mapConfMain = iter.next();
boolean isfind=false;
for (UIConf uiConf : uiConfList) {
if (mapConfMain.get("uiconf_field").equals(uiConf.getUiconf_field())) {
isfind=true;
break;
}
}
if (!isfind) {
//dsUiConfMain.remove(mapConfMain);
iter.remove();
}
}
//end added
for (UIConf dtoUiConf : uiConfList) {
if (CommUtil.ContainsNode(dsUiConfMain, (Map map) -> {
boolean isexists = map.get("uiconf_field").equals(dtoUiConf.getUiconf_field());
if (isexists) {
dtoUiConf.setUiconf_value(Convert.toStr(map.get("uiconf_value")));
}
return isexists;
})) {
dtoUiConf.setIs_contain(1);
} else {
dtoUiConf.setIs_contain(0);
}
}
return JsonHandler.toPageJson(uiConfList);
}
/**
* 界面视图缓存列
* @param uiconf_id
* @param xtype
* @return
* @throws Exception
*/
@RequestMapping("/cache_uiconfdetail.htm")
public @ResponseBody String cache_uiconfdetail(String uiconf_id, String xtype) throws Exception {
QueryObject qo = new QueryObject();
if (CommUtil.isNotEmpty(xtype)) {
qo.addQuery("obj.uiconf_type",
new SysMap("xtype", xtype), "=");
}
qo.setOrderBy("order_no");
List<UIConf> uiConfList = this.uiManagerService.findConf(qo);
List<Map> dsUiConfDetail =uiManagerService.getPoolCache(new Object[]{"confdetail", httpSession.getId(), uiconf_id});
//删除不存在的属性记录 add by cxj 2016.5.27
Iterator<Map> iter = dsUiConfDetail.iterator();
while (iter.hasNext()) {
Map mapConfDetail = iter.next();
boolean isfind=false;
for (UIConf uiConf : uiConfList) {
if (mapConfDetail.get("uiconf_field").equals(uiConf.getUiconf_field())) {
isfind=true;
break;
}
}
if (!isfind) {
//dsUiConfDetail.remove(mapConfDetail);
iter.remove();
}
}
//end added
for (UIConf dtoUiConf : uiConfList) {
if (CommUtil.ContainsNode(dsUiConfDetail, (Map map) -> {
boolean isexists = map.get("uiconf_field").equals(dtoUiConf.getUiconf_field());
if (isexists) {
dtoUiConf.setUiconf_value(Convert.toStr(map.get("uiconf_value")));
}
return isexists;
})) {
dtoUiConf.setIs_contain(1);
} else {
dtoUiConf.setIs_contain(0);
}
}
return JsonHandler.toPageJson(uiConfList);
}
/**
* 界面视图调序缓存字段
* @param inDto
* @throws Exception
*/
@RequestMapping("/swap_uicolcache.htm")
public @ResponseBody void swap_uicolcache(@RequestParam Map<String, Object> inDto) throws Exception {
Dto swapDto = JsonHandler.parseDto((String)inDto.get("swap"));
List<Map> dsDetail =uiManagerService.getPoolCache(new Object[]{"detail", httpSession.getId(), Convert.toStr(inDto.get("ui_id"))});
if (dsDetail!=null) {
//顺序存在bug,将原有交换顺序号的代码换成更新为所有顺序号(同一父节点)重排 modify by cxj 2016.5.27
for (Map map:dsDetail) {
if (swapDto.containsKey(map.get("ui_detail_id"))) {
map.put("field_index",swapDto.get(map.get("ui_detail_id")));
}
}
}
}
/**
* 界面视图调级缓存字段
* @param inDto
* @throws Exception
*/
@RequestMapping("/grade_uicolcache.htm")
public @ResponseBody void grade_uicolcache(@RequestParam Map<String, Object> inDto) throws Exception {
Dto swapDto = JsonHandler.parseDto((String)inDto.get("swap"));
List<Map> dsDetail =uiManagerService.getPoolCache(new Object[]{"detail", httpSession.getId(), Convert.toStr(inDto.get("ui_id"))});
if (dsDetail!=null) {
//顺序存在bug,将原有交换顺序号的代码换成更新为所有顺序号(同一父节点)重排 modify by cxj 2016.5.27
for (Map map:dsDetail) {
if (swapDto.containsKey(map.get("ui_detail_id"))) {
map.put("parent_id",swapDto.get(map.get("ui_detail_id")));
}
}
}
}
/**
* 更新缓冲表,存入缓冲区
* @param inDto
* @throws Exception
*/
@RequestMapping("/update_uiconfandmain_cache.htm")
public @ResponseBody Dto update_uiconfandmain_cache(@RequestParam Map<String, Object> inDto, String dirtydata) throws Exception {
inDto.remove("dirtydata");
List<Map> dsConfMain =uiManagerService.getPoolCache(new Object[]{"confmain", httpSession.getId(), Convert.toStr(inDto.get("ui_id"))});
List list = JsonHandler.parseList(dirtydata);
for (int i=0; i<list.size(); i++) {
Dto dtoClientConfMain = (Dto) list.get(i);
if (!CommUtil.ContainsNode(dsConfMain, (Map map) -> {
boolean isexists = map.get("uiconf_field").equals(dtoClientConfMain.get("uiconf_field"));
if (isexists) {
if ("1".equals(dtoClientConfMain.getString("is_contain"))) {
map.put("uiconf_field", dtoClientConfMain.getString("uiconf_field"));
map.put("uiconf_title", dtoClientConfMain.getString("uiconf_title"));
map.put("uiconf_value", dtoClientConfMain.getString("uiconf_value"));
map.put("uiconf_datatype", dtoClientConfMain.getString("uiconf_datatype"));
} else {
dsConfMain.remove(map);
}
}
return isexists;
})) {
if ("1".equals(dtoClientConfMain.getString("is_contain"))) {
Map map = new HashMap();
map.put("uiconf_id", dtoClientConfMain.getString("ui_detail_id"));
map.put("uiconf_field", dtoClientConfMain.getString("uiconf_field"));
map.put("uiconf_title", dtoClientConfMain.getString("uiconf_title"));
map.put("uiconf_value", dtoClientConfMain.getString("uiconf_value"));
map.put("uiconf_datatype", dtoClientConfMain.getString("uiconf_datatype"));
dsConfMain.add(map);
}
}
}
return OkTipMsg("更新成功");
}
/**
* 更新缓冲表,存入缓冲区
* @param inDto
* @throws Exception
*/
@RequestMapping("/update_uiconfanddetail_cache.htm")
public @ResponseBody Dto update_uiconfanddetail_cache(@RequestParam Map<String, Object> inDto, String dirtydata) throws Exception {
inDto.remove("dirtydata");
List<Map> dsDetail =uiManagerService.getPoolCache(new Object[]{"detail", httpSession.getId(), Convert.toStr(inDto.get("ui_id"))});
Dto outDto = new HashDto();
if (dsDetail!=null) {
if (checkRepeatField(dsDetail,inDto)) {
if (CommUtil.ContainsNode(dsDetail, (Map map) -> {
boolean isexists = Convert.toStr(map.get("ui_detail_id")).equals(Convert.toStr(inDto.get("ui_detail_id")));
if (isexists) {
map.putAll(inDto);
}
return isexists;
})) {
List list = JsonHandler.parseList(dirtydata);
List<Map> dsUiConfDetail =uiManagerService.getPoolCache(new Object[]{"confdetail", httpSession.getId(), (String) inDto.get("ui_detail_id")});
for (int i=0; i<list.size(); i++) {
Dto dtoClientConfDetail = (Dto) list.get(i);
if (!CommUtil.ContainsNode(dsUiConfDetail, (Map map) -> {
boolean isexists = map.get("uiconf_field").equals(dtoClientConfDetail.get("uiconf_field"));
if (isexists) {
if ("1".equals(dtoClientConfDetail.getString("is_contain"))) {
map.put("uiconf_field", dtoClientConfDetail.getString("uiconf_field"));
map.put("uiconf_title", dtoClientConfDetail.getString("uiconf_title"));
map.put("uiconf_value", dtoClientConfDetail.getString("uiconf_value"));
map.put("uiconf_datatype", dtoClientConfDetail.getString("uiconf_datatype"));
} else {
dsUiConfDetail.remove(map);
}
}
return isexists;
})) {
if ("1".equals(dtoClientConfDetail.getString("is_contain"))) {
Map map = new HashMap();
map.put("uiconf_id", dtoClientConfDetail.getString("ui_detail_id"));
map.put("uiconf_field", dtoClientConfDetail.getString("uiconf_field"));
map.put("uiconf_title", dtoClientConfDetail.getString("uiconf_title"));
map.put("uiconf_value", dtoClientConfDetail.getString("uiconf_value"));
map.put("uiconf_datatype", dtoClientConfDetail.getString("uiconf_datatype"));
dsUiConfDetail.add(map);
}
}
}
if ("hidden".equals(inDto.get("field_type"))) {
inDto.put("iconCls", "nodeNoIcon");
} else {
boolean ishidden = CommUtil.ContainsNode(dsUiConfDetail, (Map map) -> {
if (map.get("uiconf_field").equals("hidden")) {
if ("true".equals(map.get("uiconf_value"))) {
return true;
}
}
return false;
});
if (ishidden) {
inDto.put("iconCls", "nodeNoIcon");
} else {
inDto.put("iconCls", "nodeYesIcon");
}
}
outDto.put("data", inDto);
outDto.put("msg", "字段更新成功");
outDto.put("success", AeonConstants.TRUE);
} else {
outDto.put("msg", "指定字段不存在,更新失败");
outDto.put("success", AeonConstants.FALSE);
}
} else {
outDto.put("msg", "字段编码不允许重复,请检查");
outDto.put("success", AeonConstants.FALSE);
}
}
return outDto;
}
private boolean checkRepeatField(List<Map> dsDetail,Map inDto) throws Exception {
for (Map map : dsDetail) {
if (!Convert.toStr(map.get("ui_detail_id")).equals(Convert.toStr(inDto.get("ui_detail_id")))
&& map.get("field_name").equals(inDto.get("field_name"))) {
return false;
}
}
return true;
}
@SecurityMapping(title = "界面视图新增",value = "ui:insert")
@RequestMapping("/insert_uiitem.htm")
public @ResponseBody Dto insert_uiitem(@RequestParam Map<String, Object> map) throws Exception {
UIManager uimanager = WebHandler.toPo(map,UIManager.class);
UIManager uiparent = uiManagerService.getObjByProperty(null, "ui_code", uimanager.getUi_code().substring(0,uimanager.getUi_code().length()-3));
uimanager.setParent_id(uiparent==null ? null : uiparent.getId());
uimanager.setAddTime(new Date());
uimanager.setRg_code(SecurityUserHolder.getRgCode());
Dto outDto = new HashDto();
List<Map> dsUiConfMain = uiManagerService.getPoolCache(new Object[]{"confmain", httpSession.getId(), uimanager.getUi_id()});
for (Map mapUiConfMain : dsUiConfMain) {
UIConfMain uiconfmain = new UIConfMain();
WebHandler.toPo(mapUiConfMain, uiconfmain);
uiconfmain.setId(null);
uimanager.getConfs().add(uiconfmain);
uiconfmain.setUi_main(uimanager);
}
Map<String,?> mapUiDetail = uiManagerService.getPool(new Object[]{"detail", httpSession.getId()});
for (Iterator<String> it = mapUiDetail.keySet().iterator(); it.hasNext();) {
String key = it.next();
List<Map> dsUiDetail = (List<Map>) mapUiDetail.get(key);
for (Map mapDs : dsUiDetail) {
UIDetail uidetail = new UIDetail();
WebHandler.toPo(mapDs, uidetail);
uidetail.setId(null);
uimanager.getDetails().add(uidetail);
uidetail.setUi(uimanager);
List<Map> dsUiConfDetail = uiManagerService.getPoolCache(new Object[]{"confdetail", httpSession.getId(), uidetail.getUi_detail_id()});
for (Map mapUiConfDetail : dsUiConfDetail) {
UIConfDetail uiconfdetail = new UIConfDetail();
WebHandler.toPo(mapUiConfDetail, uiconfdetail);
uiconfdetail.setId(null);
uidetail.getConfs().add(uiconfdetail);
uiconfdetail.setUi_detail(uidetail);
if ("hidden".equals(uiconfdetail.getUiconf_field()) && "true".equals(uiconfdetail.getUiconf_value())) {
uidetail.setHidden(Byte.valueOf("1"));
} else {
uidetail.setHidden(Byte.valueOf("0"));
}
}
}
}
uiManagerService.save(uimanager);
//新增的时候,处理上下级关系
boolean is_grade = false;
for (UIDetail uiDetail : uimanager.getDetails()) {
if (CommUtil.isNotEmpty(uiDetail.getParent_id())) {
for (UIDetail detailFind : uimanager.getDetails()) {
if (detailFind.getUi_detail_id().equals(Convert.toStr(uiDetail.getParent_id()))) {
uiDetail.setParent_id(detailFind.getId());
is_grade = true;
break;
}
}
}
}
if (is_grade)
uiManagerService.update(uimanager);
outDto.put("parent_id", uimanager.getParent_id());
outDto.put("msg", "界面视图新增成功");
outDto.put("success", AeonConstants.TRUE);
return outDto;
}
@SecurityMapping(title = "界面视图修改",value = "ui:update")
@RequestMapping("/update_uiitem.htm")
public @ResponseBody Dto update_uiitem(@RequestParam Map<String, Object> map,@RequestParam("ui_id") Long id) throws Exception {
UIManager uimanager = uiManagerService.getObjById(id);
WebHandler.toPo(map,uimanager);
UIManager uiparent = uiManagerService.getObjByProperty(null, "ui_code", uimanager.getUi_code().substring(0,uimanager.getUi_code().length()-3));
uimanager.setParent_id(uiparent==null ? null : uiparent.getId());
uimanager.setAddTime(new Date());
uimanager.setRg_code(SecurityUserHolder.getRgCode());
Dto outDto = new HashDto();
List<Map> dsUiConfMain = uiManagerService.getPoolCache(new Object[]{"confmain", httpSession.getId(), uimanager.getUi_id()});
for (UIConfMain uiConfMain : disposeRecordState(uimanager.getConfs(),dsUiConfMain,UIConfMain.class)) {
uiConfMain.setUi_main(uimanager);
}
List<Map> dsUiDetail = uiManagerService.getPoolCache(new Object[]{"detail", httpSession.getId(),Convert.toStr(id)});
for (UIDetail uidetail : disposeRecordState(uimanager.getDetails(),dsUiDetail,UIDetail.class)) {
uidetail.setUi(uimanager);
List<Map> dsUiConfDetail = uiManagerService.getPoolCache(new Object[]{"confdetail", httpSession.getId(), uidetail.getUi_detail_id()});
for (UIConfDetail uiconfdetail : disposeRecordState(uidetail.getConfs(),dsUiConfDetail,UIConfDetail.class)) {
uiconfdetail.setUi_detail(uidetail);
if ("hidden".equals(uiconfdetail.getUiconf_field()) && "true".equals(uiconfdetail.getUiconf_value())) {
uidetail.setHidden(Byte.valueOf("1"));
} else {
uidetail.setHidden(Byte.valueOf("0"));
}
}
}
uiManagerService.update(uimanager);
outDto.put("parent_id", uimanager.getParent_id());
outDto.put("msg", "界面视图修改成功");
outDto.put("success", AeonConstants.TRUE);
return outDto;
}
/**
* 处理明细列记录状态
* @param details
* @param maps
* @return
*/
private <T> List<T> disposeRecordState(List<T> details, List<Map> maps, Class<T> clazz) {
Iterator<T> iterator = details.iterator();
while (iterator.hasNext()) {
T detail = iterator.next();
BeanWrapper wrapper = new BeanWrapperImpl(detail);
if (!CommUtil.ContainsNode(maps,(Map map) -> {
if (map.get("id")!=null) {
if (Convert.toStr(map.get("id")).equals(Convert.toStr(wrapper.getPropertyValue("id")))) {
//修改状态
WebHandler.toPo(map, detail);
return true;
}
}
return false;
})) {
//wrapper.setPropertyValue("is_deleted",1);
iterator.remove();
}
}
for (Map map : maps) {
boolean isexists =false;
if (map.get("id")!=null) {
for (T detail : details) {
BeanWrapper wrapper = new BeanWrapperImpl(detail);
if (Convert.toStr(map.get("id")).equals(Convert.toStr(wrapper.getPropertyValue("id")))) {
isexists = true;
}
}
}
if (!isexists) {
map.remove("id");
T obj = WebHandler.toPo(map, clazz);
details.add(obj);
}
}
return details;
}
@SecurityMapping(title = "界面视图删除",value = "ui:delete")
@RequestMapping("/delete_uiitem.htm")
public @ResponseBody Dto delete_uiitem(@RequestParam("ui_id") Long id) throws Exception {
this.uiManagerService.delete(id);
return OkTipMsg("界面视图删除成功");
}
@RequestMapping("/ui_designer.htm")
public @ResponseBody String ui_designer(@RequestParam Map<String, Object> map) throws Exception{
return baseUIService.getCache(new Object[]{map});
}
@RequestMapping("/uimain_designer.htm")
public @ResponseBody String uimain_designer(String comp_id, String servletpath, Long ui_id) throws Exception{
QueryObject qo = new QueryObject();
if (CommUtil.isNotEmpty(comp_id)) {
qo.addQuery("obj.ui_main.comp_id", new SysMap("comp_id", comp_id), "=");
}
if (CommUtil.isNotEmpty(servletpath)) {
qo.addQuery("obj.ui_main.servletpath", new SysMap("servletpath", servletpath), "=");
}
if (CommUtil.isNotEmpty(ui_id)) {
qo.addQuery("obj.ui_main.id", new SysMap("ui_id", ui_id), "=");
}
List<UIConfMain> elements = this.uiManagerService.findConfMain(qo);
if (elements!=null && elements.size()>0) {
return JsonHandler.toJson(elements.get(0));
} else {
return "[]";
}
}
@RequestMapping("/ui_designer1.htm")
public @ResponseBody String ui_designer1(String comp_id, String servletpath, Long ui_id) {
QueryObject qo = new QueryObject("ui_code","asc");
//qo.setFetchs(" join fetch obj.details as det join fetch det.confs");
if (CommUtil.isNotEmpty(comp_id)) {
qo.addQuery("obj.comp_id", new SysMap("comp_id", comp_id), "=");
}
if (CommUtil.isNotEmpty(servletpath)) {
qo.addQuery("obj.servletpath", new SysMap("servletpath", servletpath), "=");
}
if (CommUtil.isNotEmpty(ui_id)) {
qo.addQuery("obj.id", new SysMap("ui_id", ui_id), "=");
}
List<UIManager> elements = this.uiManagerService.find(qo);
if (elements!=null && elements.size()>0) {
// Map<String,String> mapInclude = new HashMap<>();
// mapInclude.put(UIManager.class.getName(),"id,ui_code,ui_name,details");
// mapInclude.put(UIDetail.class.getName(),"id,field_name,field_index,confs");
// mapInclude.put(UIConfDetail.class.getName(),"id,uiconf_field,uiconf_value");
return JsonHandler.toJson(elements.get(0).getDetails());
} else {
return "[]";
}
}
@RequestMapping("/ui_ele_designer.htm")
public @ResponseBody String ui_ele_designer(String source) throws Exception {
if (CommUtil.isNotEmpty(source)) {
Element ele = elementService.getObjByProperty(null, "ele_code", source);
if (ele!=null && CommUtil.isNotEmpty(ele.getUi_id())) {
Map map = new HashMap();
map.put("ui_id",ele.getUi_id());
return baseUIService.getCache(new Object[]{map});
}
}
return "[]";
}
@RequestMapping("/ui_sync_memory.htm")
public @ResponseBody void ui_sync_memory() {
this.baseUIService.reset();
}
@SecurityMapping(title = "界面视图新增",value = "ui:insert")
@RequestMapping("/insert_uiconf.htm")
public @ResponseBody ResultBody insert_uiconf(@RequestParam Map<String,Object> mapPara,
@RequestParam("uiconf_type") String uiconf_type,
@RequestParam("uiconf_field") String uiconf_field) {
UIConf vf = this.uiConfService.getObjByProperty("uiconf_type", uiconf_type,"uiconf_field",uiconf_field);
if (vf == null) {
UIConf uiConf = WebHandler.toPo(mapPara, UIConf.class);
this.uiConfService.save(uiConf);
return ResultBody.success();
} else {
return ResultBody.failed();
}
}
@SecurityMapping(title = "界面视图新增",value = "ui:insert")
@RequestMapping("/delete_uiconf.htm")
public @ResponseBody ResultBody delete_uiconf(@RequestParam("uiconf_type") String uiconf_type,
@RequestParam("uiconf_field") String uiconf_field) {
UIConf vf = this.uiConfService.getObjByProperty("uiconf_type", uiconf_type,"uiconf_field",uiconf_field);
if (vf != null) {
this.uiConfService.delete(vf.getId());
}
return ResultBody.success();
}
}
|
C++
|
UTF-8
| 1,262 | 3.5625 | 4 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
class MinStack{
public:
stack<int> StackValue;
stack<int> StackMin;
MinStack(){
}
void push(int n ){
StackValue.push(n);
if( StackMin.empty() || StackMin.top() >= n ){
StackMin.push(n);
}
}
void pop(){
if( StackMin.top() == StackValue.top() ){
StackMin.pop();
}
StackValue.pop();
}
int top(){
return StackValue.top();
}
int getMin(){
return StackMin.top();
}
};
int main(int argc, char* argv[] ){
int n ;
cin >> n ;
MinStack mystack = new MinStack();
while( n--){
cout << mystack.top() <<endl;
cout << mystack.getMin() << endl;
}
return 0 ;
}
int main(int argc, char* argv[] ){
int n ;
cin >> n ;
MinStack mystack = new MinStack();
while( n--){
string temp ;
cin >> temp;
if( temp == "top"){
cout << mystack.top() <<endl;
}else if( temp == "getMin"){
cout << mystack.getMin() << endl;
}
}
return 0 ;
}
|
Python
|
UTF-8
| 1,586 | 2.5625 | 3 |
[] |
no_license
|
from sklearn.model_selection import StratifiedKFold
from sklearn import preprocessing
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
import numpy as np
import semi_chi
def getACC(X, y, selected_num,classifier = 'Gauss',k = 10):
skf = StratifiedKFold(n_splits=k)
if classifier == 'Gauss':
clf = GaussianNB()
elif classifier == 'KNN':
clf = KNeighborsClassifier()
elif classifier == 'SVM':
clf = SVC()
acc = 0.0
X = preprocessing.minmax_scale(X, feature_range=(0, 1), axis=0)
for train_index,test_index in skf.split(X,y):
X_train,X_test = X[train_index],X[test_index]
y_train,y_test = y[train_index],y[test_index]
n_row_train,n_col_train = X_train.shape
n_row_test,n_col_test = X_test.shape
feature_train = np.zeros((n_row_train,n_col_train))
feature_test = np.zeros((n_row_test,n_col_test))
sort_score = semi_chi.SEMICHI(X_train,y_train)
sort_index = semi_chi.feature_ranking(sort_score)
for col in range(selected_num):
for row in range(n_row_train):
feature_train[row, col] = X_train[row, sort_index[col]]
for col in range(selected_num):
for row in range(n_row_test):
feature_test[row, col] = X_test[row, sort_index[col]]
clf.fit(feature_train, y_train)
score = clf.score(feature_test,y_test) * 100
acc += score
acc = acc / k
print(selected_num,'\t', fs_type, '\t', acc)
return acc
|
Java
|
UTF-8
| 599 | 2.203125 | 2 |
[] |
no_license
|
package com.plantix.data.database;
import androidx.room.Database;
import androidx.room.RoomDatabase;
import androidx.room.TypeConverters;
import com.plantix.data.database.converters.DateTypeConverter;
import com.plantix.data.database.daos.DatumTableDao;
import com.plantix.data.database.dbpojo.Datum;
//Here initialise daos with respective tables
@Database(entities = {Datum.class}, version = RoomDB.DATABASE_VERSION, exportSchema = false)
@TypeConverters(DateTypeConverter.class)
public abstract class AppDatabase extends RoomDatabase {
public abstract DatumTableDao datumTableDao();
}
|
Shell
|
UTF-8
| 8,667 | 3.03125 | 3 |
[] |
no_license
|
#!/bin/bash
help_info ()
{
echo "****************************************************************************"
echo "*"
echo "* MODULE: Linux Script - facenet"
echo "*"
echo "* COMPONENT: This script used to run facenet python process"
echo "*"
echo "* REVISION: $Revision: 1.0 $"
echo "*"
echo "* DATED: $Date: 2018-04-09 15:16:28 +0000 () $"
echo "*"
echo "* AUTHOR: PCT"
echo "*"
echo "***************************************************************************"
echo ""
echo "* Copyright yanhong.jia@kuang-chi.com. 2020. All rights reserved"
echo "*"
echo "***************************************************************************"
}
usage()
{
echo "##################Usage################## "
echo "You provided $# parameters,but 3 are required. \
th first parameter is run cmd,\
the second parameter is datasets path,\
the third parameter is project path"
#echo " facenet pretrain use: ./facenet.sh pretrain "
#echo "facenet train on own images: ./facenet.sh train "
echo "examples are as follows:"
echo "./assoc.sh represent data_dir "
echo "./assoc.sh eval test_dir "
echo "./assoc.sh train train_dir_ID train_dir_camera valid_dir"
}
case $1 in
represent)
export PYTHONPATH=$(pwd)/src
export CUDA_VISABLE_DEVICES=0
python util/batch_represent_double.py \
--data_dir /home/asus/fengchen/facenet/data/pairwise/validate \
--output_dir /home/asus/fengchen/facenet/emb/pairwise/validate \
--trained_model_dir $(pwd)/models/20180904-172233/
;;
eval)
export PYTHONPATH=$(pwd)/src
export CUDA_VISABLE_DEVICES=2
echo "my_validate_on_lfw ....."
python evaluation/my_validate_on_lfw.py \
--lfw_dir $2 \
--model $(pwd)/models/double_input/20180814-164925 \
--lfw_pairs $2/pairs.txt \
;;
train)
export PYTHONPATH=$(pwd)/src
python src/main_tripletloss.py \
--logs_base_dir ./logs \
--models_base_dir ./models/ \
--data_source SINGLE \
--data_dir /data/liukang/face_data/80w_camera/80w_split_70_10/70w_all \
--model_def models.inception_resnet_v1 \
--optimizer ADAM \
--learning_rate 0.5 \
--learning_rate_decay_epochs 10 \
--learning_rate_decay_factor 0.8 \
--unsupervised NONE \
--lfw_dir /data/nfs/asus/yanhong.jia/datasets/face_recognition/datasets_for_train/valid_35 \
--lfw_pairs /data/nfs/asus/yanhong.jia/datasets/face_recognition/datasets_for_train/valid_35/pairs.txt \
--val_dir /data/liukang/face_data/valid_150 \
--val_pairs /data/liukang/face_data/valid_150/pairs.txt \
--max_nrof_epochs 5000 \
--epoch_size 1000 \
--people_per_batch 45 \
--images_per_person 10 \
--max_triplet_per_select 1500 \
--random_flip False \
--gpu_memory_fraction 1.0 \
--gpu 0
;;
train_shallow)
export PYTHONPATH=$(pwd)/src
python src/main_tripletloss.py \
--logs_base_dir ./logs \
--models_base_dir ./models/ \
--data_source SINGLE \
--data_dir /data/liukang/face_data/80w_camera/80w_split_70_10/70w_all \
--model_def models.inception_resnet_v1 \
--optimizer ADAM \
--learning_rate 0.5 \
--learning_rate_decay_epochs 10 \
--learning_rate_decay_factor 0.8 \
--unsupervised NONE \
--lfw_dir /data/nfs/asus/yanhong.jia/datasets/face_recognition/datasets_for_train/valid_35 \
--lfw_pairs /data/nfs/asus/yanhong.jia/datasets/face_recognition/datasets_for_train/valid_35/pairs.txt \
--val_dir /data/liukang/face_data/valid_150 \
--val_pairs /data/liukang/face_data/valid_150/pairs.txt \
--max_nrof_epochs 5000 \
--epoch_size 1000 \
--people_per_batch 1800 \
--images_per_person 2 \
--max_triplet_per_select 1500 \
--random_flip False \
--gpu_memory_fraction 1.0 \
--gpu 1
;;
train_hvd)
export PYTHONPATH=$(pwd)/src
HOROVOD_TIMELINE=./logs/timeline.json \
mpirun -np 4 \
-H localhost:4 \
-bind-to none -map-by slot \
-x NCCL_DEBUG=INFO -x LD_LIBRARY_PATH -x PATH \
-mca pml ob1 -x HOROVOD_MPI_THREADS_DISABLE=1 \
python src/main_tripletloss.py \
--logs_base_dir ./logs \
--models_base_dir ./models/ \
--data_source SINGLE \
--data_dir /data/datasets/face_camera_80w/80w_split_70_10/70w_all \
--model_def models.inception_resnet_v1 \
--optimizer ADAM \
--learning_rate 0.4 \
--learning_rate_decay_epochs 10 \
--learning_rate_decay_factor 0.8 \
--unsupervised NONE \
--lfw_dir /data/yanhong.jia/datasets/face_recognition/datasets_for_train/valid_35 \
--lfw_pairs /data/yanhong.jia/datasets/face_recognition/datasets_for_train/valid_35/pairs.txt \
--val_dir /data/nfs/kc/liukang/face_data/valid_150 \
--val_pairs /data/nfs/kc/liukang/face_data/valid_150/pairs.txt \
--max_nrof_epochs 5000 \
--epoch_size 1000 \
--people_per_batch 30 \
--images_per_person 10 \
--max_triplet_per_select 600 \
--random_flip False \
--gpu_memory_fraction 1.0 \
--gpu 0,1,2,3 \
--cluster True \
--nrof_warmup_epochs 0
;;
train_shallow_hvd)
export PYTHONPATH=$(pwd)/src
HOROVOD_TIMELINE=./logs/timeline.json \
mpirun -np 4 \
-H localhost:4 \
-bind-to none -map-by slot \
-x NCCL_DEBUG=INFO -x LD_LIBRARY_PATH -x PATH \
-mca pml ob1 -x HOROVOD_MPI_THREADS_DISABLE=1 \
python src/main_tripletloss.py \
--logs_base_dir ./logs \
--models_base_dir ./models/ \
--data_source SINGLE \
--data_dir /data/nfs/kc/liukang/face_data/80w_camera/80w_split_70_10/70w_all \
--model_def models.inception_resnet_v1 \
--optimizer ADAM \
--learning_rate 0.4 \
--learning_rate_decay_epochs 10 \
--learning_rate_decay_factor 0.8 \
--unsupervised NONE \
--lfw_dir /data/yanhong.jia/datasets/face_recognition/datasets_for_train/valid_35 \
--lfw_pairs /data/yanhong.jia/datasets/face_recognition/datasets_for_train/valid_35/pairs.txt \
--val_dir /data/nfs/kc/liukang/face_data/valid_150 \
--val_pairs /data/nfs/kc/liukang/face_data/valid_150/pairs.txt \
--max_nrof_epochs 5000 \
--epoch_size 1000 \
--people_per_batch 900 \
--images_per_person 2 \
--max_triplet_per_select 600 \
--random_flip False \
--gpu_memory_fraction 1.0 \
--gpu 0,1,2,3 \
--cluster True \
--nrof_warmup_epochs 0
;;
train_inc)
export PYTHONPATH=$(pwd)/src
python src/main_tripletloss.py \
--logs_base_dir ./logs \
--models_base_dir ./models/ \
--data_dir /data/nfs/kc/liukang/face_data/80w_camera/80w_all \
--model_def models.inception_resnet_v1 \
--pretrained_model ../../../models/facenet/20170512-110547/model-20170512-110547.ckpt-250000 \
--optimizer ADAM \
--learning_rate 0.01 \
--learning_rate_decay_epochs 10 \
--learning_rate_decay_factor 0.8 \
--weight_decay 1e-4 \
--lfw_dir /data/yanhong.jia/datasets/face_recognition/datasets_for_train/valid_35 \
--lfw_pairs /data/yanhong.jia/datasets/face_recognition/datasets_for_train/valid_35/pairs.txt \
--val_dir /data/yanhong.jia/datasets/face_recognition/datasets_for_train/valid_24peo_3D+camera \
--val_pairs /data/yanhong.jia/datasets/face_recognition/datasets_for_train/valid_24peo_3D+camera/pairs.txt \
--max_nrof_epochs 5000 \
--people_per_batch 45 \
--images_per_person 10 \
--gpu_memory_fraction 1.0 \
--gpu 1
;;
clear)
find . -name "*.pyc" -type f -print -exec rm -rf {} \;
;;
*)
help_info
usage
exit 1
;;
esac
exit 0
|
C++
|
UTF-8
| 3,250 | 3.203125 | 3 |
[] |
no_license
|
/**
* @file arena.cc
*
* @copyright 2017 3081 Staff, All rights reserved.
*/
/*******************************************************************************
* Includes
******************************************************************************/
#include <algorithm>
#include <iostream>
#include "arena.h"
#include "robot.h"
#include "robot_virtual.h"
/*******************************************************************************
* Constructors/Destructor
******************************************************************************/
Arena::Arena() :
n_robots_virtual_(0), n_robots_(0) {
}
Arena::~Arena(void) {
for (int i=0;i<n_robots_;i++) {
delete robots_[i];
} /* for(ent..) */
}
/*******************************************************************************
* Member Functions
******************************************************************************/
void Arena::AddRobotVirtual(const Position& pos, const int rad) {
robots_virtual_[n_robots_virtual_] = new RobotVirtual( pos, rad);
n_robots_virtual_++;
}
void Arena::AddRobot(const Position& pos, const int rad) {
robots_[n_robots_] = new Robot( pos, rad );
n_robots_++;
}
void Arena::AdvanceTime() {
UpdateEntities();
}
void Arena::UpdateEntities(void) {
// Update the position of all entities.
for (int i=0; i<n_robots_; i++) {
robots_[i]->TimestepUpdate();
}
// Some pairs of entities may now be close enough to be colliding
for (int i=0; i<n_robots_; i++) {
for (int j=i+1; j<n_robots_; j++) {
if (CheckForCollision(robots_[i],robots_[j])) {
std::cout << "Robot "<< i << " colliding with robot " << j << "\n";
}
}
}
// Same thing, except for robots with virtual setters/getters
for (int i=0; i<n_robots_virtual_; i++) {
robots_virtual_[i]->TimestepUpdate();
}
// Some pairs of entities may now be close enough to be colliding
for (int i=0; i<n_robots_virtual_; i++) {
for (int j=i+1; j<n_robots_virtual_; j++) {
if (CheckForCollisionVirtual(robots_virtual_[i],robots_virtual_[j])) {
std::cout << "Virtual robot "<< i << " colliding with robot " << j << "\n";
}
}
}
}
bool Arena::CheckForCollision(Entity* ent1, Entity* ent2 ) {
/* Note: this assumes circular entities */
double ent1_x = ent1->get_position().x;
double ent1_y = ent1->get_position().y;
double ent2_x = ent2->get_position().x;
double ent2_y = ent2->get_position().y;
double dist = std::sqrt(std::pow(ent2_x - ent1_x, 2) +
std::pow(ent2_y - ent1_y, 2));
if (dist > (ent1->get_radius() + ent2->get_radius())) {
return false;
} else {
return true;
}
} /* CheckForCollision() */
bool Arena::CheckForCollisionVirtual(EntityVirtual* ent1,
EntityVirtual* ent2 ) {
/* Note: this assumes circular entities */
double ent1_x = ent1->get_position().x;
double ent1_y = ent1->get_position().y;
double ent2_x = ent2->get_position().x;
double ent2_y = ent2->get_position().y;
double dist = std::sqrt(std::pow(ent2_x - ent1_x, 2) +
std::pow(ent2_y - ent1_y, 2));
if (dist > (ent1->get_radius() + ent2->get_radius())) {
return false;
} else {
return true;
}
} /* CheckForCollisionVirtual() */
|
Markdown
|
UTF-8
| 625 | 2.59375 | 3 |
[] |
no_license
|
## 1819-csse1
___
## Hektor Misplon
## NMD-2
### _16/12/18_
___
# Deel 1: Dataformaten
## 1. Wat is een Dataformaat?
Een dataformaat is een formaat die het mogelijk maakt om data uit te wisselen tussen verschillende bestanden of databasestructuren.
Gegevens kunnen dus omgezet worden naar een bepaald dataformaat door een programma. Zo wordt het mogelijk om dit dataformaat dan weer om te zetten door een ander programma naar het gewenste formaat.
## 2. Welke dataformaten zijn er?
* JSON (JavaScript Object Notation)
* XML
* CSV
* RDF
* Spreadsheets
* Text Documenten
* Plain Text (.txt)
* HTML
## 3. Wat zijn de verschillen?
|
C#
|
UTF-8
| 3,180 | 2.828125 | 3 |
[] |
no_license
|
namespace Dtx.IO
{
/// <summary>
/// Version: 1.0.1
/// Update Date: 1392/05/16
///
/// </summary>
public static class File
{
public static string Read(string pathName)
{
if (pathName == null)
{
return (string.Empty);
}
pathName = pathName.Trim();
if (pathName == string.Empty)
{
return (string.Empty);
}
if (System.IO.File.Exists(pathName) == false)
{
return (string.Empty);
}
string strResult = string.Empty;
System.IO.StreamReader oStream = null;
try
{
oStream =
new System.IO.StreamReader
(pathName, System.Text.Encoding.UTF8);
strResult = oStream.ReadToEnd();
}
catch
{
}
finally
{
if (oStream != null)
{
//oStream.Close();
oStream.Dispose();
oStream = null;
}
}
return (strResult);
}
public static bool Write(string pathName, string text, bool append)
{
if (pathName == null)
{
return (false);
}
pathName = pathName.Trim();
if (pathName == string.Empty)
{
return (false);
}
if (text == null)
{
text = string.Empty;
}
System.IO.StreamWriter oStream = null;
try
{
oStream =
new System.IO.StreamWriter
(pathName, append, System.Text.Encoding.UTF8);
oStream.Write(text);
return (true);
}
catch
{
return (false);
}
finally
{
if (oStream != null)
{
//oStream.Close();
oStream.Dispose();
oStream = null;
}
}
}
public static bool Append(string pathName, string text)
{
return (Write(pathName, text, true));
}
public static bool Overwrite(string pathName, string text)
{
return (Write(pathName, text, false));
}
private static string GetCurrentCultureName()
{
return (System.Threading.Thread.CurrentThread.CurrentCulture.Name);
}
public static string GetFileNameByCulture
(string name, string cultureName, string extension)
{
string strFileName = name;
//if (string.Compare(cultureName, "en-US", ignoreCase: true) != 0)
//{
// strFileName =
// string.Format("{0}.{1}", strFileName, cultureName);
//}
//strFileName =
// string.Format("{0}.{1}", strFileName, extension);
strFileName =
string.Format("{0}.{1}.{2}",
strFileName, cultureName, extension);
return (strFileName);
}
public static string GetFileNameByCurrentCulture
(string fileName, string extension)
{
return (GetFileNameByCulture(fileName, GetCurrentCultureName(), extension));
}
public static string GetPathNameByCulture
(string rootRelativePath, string name, string cultureName, string extension)
{
string strFileName =
GetFileNameByCulture(name, cultureName, extension);
string strRootRelativePathName =
string.Format("{0}/{1}", rootRelativePath, strFileName);
string strPathName =
System.Web.HttpContext.Current.Server.MapPath(strRootRelativePathName);
return (strPathName);
}
public static string GetPathNameByCurrentCulture
(string rootRelativePath, string name, string extension)
{
return (GetPathNameByCulture
(rootRelativePath, name, GetCurrentCultureName(), extension));
}
}
}
|
Java
|
UTF-8
| 372 | 1.90625 | 2 |
[] |
no_license
|
package be.tomvertommen.drinksMachine.communication;
/**
* The names of all possible requests.
* @author Tom Vertommen
*
*/
public enum RequestName {
SET_MODE,
GET_DRINK,
ADD_INGREDIENT,
REMOVE_INGREDIENT,
ADD_MAX_QTY,
REMOVE_MAX_QTY,
ADD_ALARM_QTY,
REMOVE_ALARM_QTY,
GET_STOCK_QTYS,
GET_STATUS,
SET_POWER,
SET_PLUGGED_IN,
SET_WATER,
SET_CARD,
PREPARE;
}
|
C++
|
UTF-8
| 631 | 3.140625 | 3 |
[] |
no_license
|
#ifndef BITSTOSHIFT_H
#define BITSTOSHIFT_H
class BitsToShift {
public:
BitsToShift() {
bits = 0;
}
void setBit(uint8_t reg_bit, bool set) {
if (set)
bits = bits | reg_bit;
else
bits = bits & ~reg_bit;
setRegister();
}
bool getBit(uint8_t reg_bit) {
return (bits & reg_bit) > 0;
}
private:
uint8_t bits;
void setRegister() {
digitalWrite(LATCH_PIN, LOW); // начинаем передачу данных
shiftOut(DATA_PIN, CLOCK_PIN, LSBFIRST, bits ^ 0b11111111);
digitalWrite(LATCH_PIN, HIGH); // прекращаем передачу данных
}
};
#endif
|
JavaScript
|
UTF-8
| 6,848 | 2.515625 | 3 |
[] |
no_license
|
'use strict';
import React, { Component } from 'react';
import {
View,
StyleSheet,
Text,
StatusBar,
TextInput,
Image,
Dimensions,
TouchableOpacity,
Alert,
AppRegistry,
} from 'react-native';
import { FlatList } from 'react-native-gesture-handler';
import * as firebase from 'firebase';
const { width, height } = Dimensions.get('window');
import QRCode from 'react-native-qrcode-generator';
export default class Wallet extends Component {
constructor(props) {
super(props);
this.state = {
query: null,
loading: true,
data: [],
qrSize: 100
};
this.dataBackup = [];
}
handledeleteItembyId(id) {
firebase.firestore()
.collection("users")
.doc(firebase.auth().currentUser.uid)
.collection('wallet')
.doc(id)
.delete().then(function () {
console.log("Document successfully deleted!");
}).catch(function (error) {
console.error("Error removing document: ", error);
});
}
//Alert to confirm add item to wallet
addItemWalletById(id) {
Alert.alert(
'Deseja excuir o cupom?',
'Esta ação não pode ser desfeita!',
[
{ text: 'Cancelar', style: 'cancel' },
{ text: 'Confirmar', onPress: () => this.handledeleteItembyId(id) },
],
{ cancelable: false }
)
}
getFirebaseData() {
firebase.firestore()
.collection('users')
.doc(firebase.auth().currentUser.uid)
.collection('wallet')
.onSnapshot(querySnapshot => {
const list = [];
querySnapshot.forEach(doc => {
const { descricao, img, produto, valor } = doc.data();
list.push({
id: doc.id,
descricao,
img,
produto,
valor
});
});
this.dataBackup = list;
this.setState({
data: list,
})
if (this.loading) {
this.setState({
loading: false
})
}
});
}
componentDidMount() {
this.getFirebaseData();
}
//SearchBar working
filterItem = event => {
//Armazena texto do input search
var text = event.nativeEvent.text;
this.setState({
query: text,
});
const newData = this.dataBackup.filter(item => {
const itemData = `${item.produto.toUpperCase()} ${item.descricao.toUpperCase()} ${item.valor.toUpperCase()}`;
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
this.setState({
data: newData,
});
};
separator = () => {
return (
<View style={{ height: 5, width: '100%', backgroundColor: '#e5e5e5' }} />
);
};
render() {
const { navigation } = this.props;
console.disableYellowBox = true;
return (
<View style={styles.container}>
<StatusBar barStyle="light-content" backgroundColor="#ff5b77" />
<View style={styles.header}>
<Text style={styles.headerTitle}>Desconto Fácil App</Text>
</View>
<View style={styles.header}>
<View style={styles.SectionStyle}>
<Image
//We are showing the Image from online
source={{ uri: 'https://img.icons8.com/ios/100/000000/search--v1.png', }}
//Image Style
style={styles.ImageStyle}
/>
<TextInput
underlineColorAndroid="transparent"
placeholder="O que procura..."
placeholderTextColor="gray"
value={this.state.query}
onChange={this.filterItem.bind(this)}
style={styles.input}
/>
</View>
</View>
<FlatList
data={this.state.data}
ItemSeparatorComponent={() => this.separator()}
keyExtractor={(item) => item.id}
renderItem={({ item }) => {
return (
<TouchableOpacity
onLongPress={() => this.addItemWalletById(item.id)}
>
<View style={styles.productContainer}>
<Image
resizeMode="contain"
style={styles.image}
source={{ uri: item.img }}
/>
<View style={styles.dataContainer}>
<Text numberOfLines={1} style={styles.title}>
{item.produto}
</Text>
<Text numberOfLines={8} style={styles.description}>
{item.descricao}
</Text>
<Text style={styles.price}>{item.valor}</Text>
</View>
<View style={styles.qrView}>
<QRCode
value={item.id}
size={this.state.qrSize}
bgColor='black'
fgColor='white' />
</View>
</View>
</TouchableOpacity>
);
}}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
},
header: {
height: 60,
width: '100%',
backgroundColor: '#ff5b77',
justifyContent: 'center',
alignContent: 'center',
alignItems: 'center',
},
headerTitle: {
fontSize: 20,
fontWeight: "500",
color: "#fff",
fontWeight: "bold",
},
input: {
height: 40,
width: '90%',
backgroundColor: '#fff',
borderRadius: 20,
padding: 5,
paddingLeft: 10,
},
SectionStyle: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
height: 40,
borderRadius: 20,
margin: 10,
},
ImageStyle: {
padding: 10,
margin: 5,
height: 25,
width: 25,
resizeMode: 'stretch',
alignItems: 'center',
},
productContainer: {
flexDirection: 'column',
padding: 2,
padding: 8,
},
image: {
height: 150,
width: 100,
alignSelf: "center"
},
dataContainer: {
padding: 5,
paddingTop: 5,
marginRight: 5,
resizeMode: 'stretch',
alignContent:'center',
alignItems:'center'
},
qrView:{
alignSelf:'center',
},
title: {
fontSize: 16,
fontWeight: "bold",
color: "#000"
},
description: {
fontSize: 14,
flexDirection: 'row',
color: 'gray',
textAlign: 'justify',
},
price: {
fontSize: 18,
fontWeight: "bold",
color: "#000"
},
addButton: {
position: 'absolute',
backgroundColor: '#ff5b77',
elevation: 4,
borderRadius: 100,
height: 57,
width: 58,
right: 15,
bottom: 30,
alignItems: 'center',
justifyContent: 'center'
},
});
|
C++
|
UTF-8
| 2,303 | 4.03125 | 4 |
[] |
no_license
|
// Ivan Stus cssc1719
// CS320Lab3 - point.cpp (Class)
#include <cmath>
#include <iostream>
using namespace std;
class Point {
private: //Initialize inputted point as private
float x1;
float y1;
public: //(0,0) is a public point
float x2;
float y2;
//Constructor
Point(float x, float y) {
x1 = x;
y1 = y;
}
//Calculate distance between point and origin, return distance
float distance() {
x2 = 0;
y2 = 0;
float x = x1 - x2;
float y = y1 - y2;
float dist;
dist = pow(x, 2) + pow(y, 2);
dist = sqrt(dist);
return dist;
}
//Less than
friend bool operator < (Point& lhs, Point& rhs) {
if (lhs.distance() < rhs.distance()) {
return true;
}
else {
return false;
}
}
//Greater than
friend bool operator > (Point& lhs, Point& rhs) {
if (lhs.distance() > rhs.distance()) {
return true;
}
else {
return false;
}
}
//Greater than or equal to
friend bool operator >= (Point& lhs, Point& rhs) {
if ((lhs > rhs == true) || (lhs.distance() == rhs.distance())) {
return true;
}
else {
return false;
}
}
//Less than or equal to
friend bool operator <= (Point& lhs, Point& rhs) {
if ((lhs < rhs == true) || (lhs.distance() == rhs.distance())) {
return true;
}
else {
return false;
}
}
//Equal
friend bool operator == (Point& lhs, Point& rhs) {
if (lhs.distance() == rhs.distance()) {
return true;
}
else {
return false;
}
}
//Not equal
friend bool operator != (Point& lhs, Point& rhs) {
if (lhs.distance() != rhs.distance()) {
return true;
}
else {
return false;
}
}
//Override << operator for proper printing to output stream
friend ostream& operator << (ostream& os, const Point& obj) {
return os << "X:" << obj.x1 << " Y:" << obj.y1;
}
};
|
Shell
|
UTF-8
| 614 | 3.125 | 3 |
[
"Apache-2.0",
"MIT",
"EPL-1.0"
] |
permissive
|
#!/bin/sh
# exit when any command fails
set -e
echo "Building and testing artifacts, and creating pom files"
./gradlew -s --scan build publishToMavenLocal codeCoverageReport
echo "Testing Bintray publication by uploading in dry run mode"
./gradlew -s -i --scan bintrayUploadAll -Pbintray.dryRun
echo "Pull request: [$TRAVIS_PULL_REQUEST], Travis branch: [$TRAVIS_BRANCH]"
# release only from master when no pull request build
if [ "$TRAVIS_BRANCH" = "master" ] && [ "$TRAVIS_PULL_REQUEST" = "false" ]
then
echo "Releasing (tagging, uploading to Bintray)"
./gradlew -s -i --scan ciPerformRelease
fi
|
C++
|
UTF-8
| 274 | 2.71875 | 3 |
[] |
no_license
|
#pragma once
template<typename T>
class Singleton
{
public:
static T* GetInstance()
{
// static T instance_;
return instance_;
}
private:
Singleton(){};
static T* instance_;
};
template <typename T>
T* Singleton<T>::instance_ = new T;
|
Python
|
UTF-8
| 456 | 3.03125 | 3 |
[] |
no_license
|
import requests
from requests import status_codes
#Melakukan input data yang akan dimasukkan pada json
load_data = {"title":"recommendation", "body":"motorcycle", "userId":12}
#Melakukan POST data yang ingin diinput pada link json
r = requests.post("https://jsonplaceholder.typicode.com/posts", json = load_data)
#Mencetak hasil data (response) yang telah diinput
print(r.text)
print("\n")
#Mencetak status request
print("Status:")
print(r.status_code)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.