hexsha
stringlengths 40
40
| size
int64 5
1.05M
| ext
stringclasses 98
values | lang
stringclasses 21
values | max_stars_repo_path
stringlengths 3
945
| max_stars_repo_name
stringlengths 4
118
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
int64 1
368k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
945
| max_issues_repo_name
stringlengths 4
118
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
134k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
945
| max_forks_repo_name
stringlengths 4
135
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 5
1.05M
| avg_line_length
float64 1
1.03M
| max_line_length
int64 2
1.03M
| alphanum_fraction
float64 0
1
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
96db4c6a644b950acb4f417a0e3e894acd0a6975
| 729
|
cshtml
|
C#
|
src/Spark/Views/Maintenance/RebuildIndex.cshtml
|
rootstrap/spark
|
fa03c3ecd7e9ecb36d2c8208741465b2ed6784ea
|
[
"BSD-3-Clause"
] | null | null | null |
src/Spark/Views/Maintenance/RebuildIndex.cshtml
|
rootstrap/spark
|
fa03c3ecd7e9ecb36d2c8208741465b2ed6784ea
|
[
"BSD-3-Clause"
] | null | null | null |
src/Spark/Views/Maintenance/RebuildIndex.cshtml
|
rootstrap/spark
|
fa03c3ecd7e9ecb36d2c8208741465b2ed6784ea
|
[
"BSD-3-Clause"
] | 1
|
2021-04-27T02:54:51.000Z
|
2021-04-27T02:54:51.000Z
|
@{
ViewBag.Title = "Rebuilding Index";
}
<h2>Rebuilding Index</h2>
<div class="progress">
<div class="progress-bar progress-bar-striped active" id="pbar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
<span class="sr-only" id="percentage">0%</span>
</div>
</div>
<span id="resultmessage">Initializing..</span>
@section scripts {
<script src="~/Scripts/jquery.signalR-2.4.1.min.js"></script>
<!-- autogenerated signalr hub script -->
<script src="~/signalr/hubs"></script>
<script src="~/Scripts/pbarupdate.js"></script>
<script>
InitProgress(function (server) {
server.rebuildIndex();
});
</script>
}
| 25.137931
| 162
| 0.621399
|
0de6f6a6e49ad2ccd85ae712a7b080bdf7300863
| 206
|
cshtml
|
C#
|
CouStem/CouStem/Views/Shared/_RegisterPartial.cshtml
|
morarj/net-coustem
|
38827205123632ccacfaa63a14b8854fa04c546e
|
[
"MIT"
] | null | null | null |
CouStem/CouStem/Views/Shared/_RegisterPartial.cshtml
|
morarj/net-coustem
|
38827205123632ccacfaa63a14b8854fa04c546e
|
[
"MIT"
] | null | null | null |
CouStem/CouStem/Views/Shared/_RegisterPartial.cshtml
|
morarj/net-coustem
|
38827205123632ccacfaa63a14b8854fa04c546e
|
[
"MIT"
] | null | null | null |
@using Microsoft.AspNet.Identity
@if (Request.IsAuthenticated)
{
<li>@Html.ActionLink("Registrar Usuario", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
}
| 34.333333
| 137
| 0.713592
|
2922a50fb68ad7d3b99f817221952d54faddd5c3
| 1,686
|
rs
|
Rust
|
examples/roulette.rs
|
sirhcel/stm32f3-discovery
|
e2b18a5cc19aa86be39f615a4b649f7dc1cee4eb
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
examples/roulette.rs
|
sirhcel/stm32f3-discovery
|
e2b18a5cc19aa86be39f615a4b649f7dc1cee4eb
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
examples/roulette.rs
|
sirhcel/stm32f3-discovery
|
e2b18a5cc19aa86be39f615a4b649f7dc1cee4eb
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
#![no_std]
#![no_main]
extern crate panic_itm;
use cortex_m_rt::entry;
use stm32f3_discovery::stm32f3xx_hal::delay::Delay;
use stm32f3_discovery::stm32f3xx_hal::prelude::*;
use stm32f3_discovery::stm32f3xx_hal::stm32;
use stm32f3_discovery::leds::Leds;
use stm32f3_discovery::switch_hal::OutputSwitch;
#[entry]
fn main() -> ! {
let device_periphs = stm32::Peripherals::take().unwrap();
let mut reset_and_clock_control = device_periphs.RCC.constrain();
let core_periphs = cortex_m::Peripherals::take().unwrap();
let mut flash = device_periphs.FLASH.constrain();
let clocks = reset_and_clock_control.cfgr.freeze(&mut flash.acr);
let mut delay = Delay::new(core_periphs.SYST, clocks);
// initialize user leds
let mut gpioe = device_periphs.GPIOE.split(&mut reset_and_clock_control.ahb);
let leds = Leds::new(
gpioe.pe8,
gpioe.pe9,
gpioe.pe10,
gpioe.pe11,
gpioe.pe12,
gpioe.pe13,
gpioe.pe14,
gpioe.pe15,
&mut gpioe.moder,
&mut gpioe.otyper,
);
let mut compass = leds.into_array();
loop {
let ms_delay = 50u16;
let ubound = compass.len();
for curr in 0..ubound {
let next = (curr + 1) % ubound;
compass[next].on().ok();
delay.delay_ms(ms_delay);
compass[curr].off().ok();
delay.delay_ms(ms_delay);
}
// Alternative way to iterate through lights
// for led in compass.iter_mut() {
// led.on().ok();
// delay.delay_ms(ms_delay);
// led.off().ok();
// delay.delay_ms(ms_delay);
// }
}
}
| 26.761905
| 81
| 0.599644
|
a3a8e6b94059b6141679b73d84103b602b7bfbf0
| 43,719
|
java
|
Java
|
drools-compiler/src/test/java/org/drools/integrationtests/QueryTest.java
|
rsynek/drools
|
56260b46d607754a527abe9e265548eb4789b1c9
|
[
"Apache-2.0"
] | null | null | null |
drools-compiler/src/test/java/org/drools/integrationtests/QueryTest.java
|
rsynek/drools
|
56260b46d607754a527abe9e265548eb4789b1c9
|
[
"Apache-2.0"
] | null | null | null |
drools-compiler/src/test/java/org/drools/integrationtests/QueryTest.java
|
rsynek/drools
|
56260b46d607754a527abe9e265548eb4789b1c9
|
[
"Apache-2.0"
] | null | null | null |
package org.drools.integrationtests;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.drools.Address;
import org.drools.Cheese;
import org.drools.CommonTestMethodBase;
import org.drools.DomainObject;
import org.drools.FactHandle;
import org.drools.InsertedObject;
import org.drools.Interval;
import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.Person;
import org.drools.QueryResult;
import org.drools.QueryResults;
import org.drools.RuleBase;
import org.drools.StatefulSession;
import org.drools.Worker;
import org.drools.WorkingMemory;
import org.drools.base.ClassObjectType;
import org.drools.base.DroolsQuery;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderError;
import org.drools.builder.KnowledgeBuilderErrors;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.common.AbstractWorkingMemory;
import org.drools.common.DefaultFactHandle;
import org.drools.common.InternalRuleBase;
import org.drools.compiler.PackageBuilder;
import org.drools.core.util.Entry;
import org.drools.core.util.ObjectHashMap.ObjectEntry;
import org.drools.core.util.ObjectHashSet;
import org.drools.impl.StatefulKnowledgeSessionImpl;
import org.drools.io.ResourceFactory;
import org.drools.reteoo.EntryPointNode;
import org.drools.reteoo.ObjectTypeNode;
import org.drools.reteoo.ReteooWorkingMemoryInterface;
import org.drools.rule.Package;
import org.drools.runtime.KnowledgeSessionConfiguration;
import org.drools.runtime.StatefulKnowledgeSession;
import org.drools.runtime.conf.QueryListenerOption;
import org.drools.runtime.rule.LiveQuery;
import org.drools.runtime.rule.QueryResultsRow;
import org.drools.runtime.rule.Row;
import org.drools.runtime.rule.Variable;
import org.drools.runtime.rule.ViewChangedEventListener;
import org.drools.runtime.rule.impl.FlatQueryResults;
import org.drools.spi.ObjectType;
import org.junit.Test;
public class QueryTest extends CommonTestMethodBase {
@Test
public void testQuery() throws Exception {
final PackageBuilder builder = new PackageBuilder();
builder.addPackageFromDrl( new InputStreamReader( getClass().getResourceAsStream( "simple_query_test.drl" ) ) );
final Package pkg = builder.getPackage();
RuleBase ruleBase = getSinglethreadRuleBase();
ruleBase.addPackage( pkg );
ruleBase = SerializationHelper.serializeObject( ruleBase );
StatefulSession session = ruleBase.newStatefulSession();
final Cheese stilton = new Cheese( "stinky",
5 );
session.insert( stilton );
session = SerializationHelper.getSerialisedStatefulSession( session,
ruleBase );
final QueryResults results = session.getQueryResults( "simple query" );
assertEquals( 1,
results.size() );
}
@Test
public void testQueryRemoval() throws Exception {
final PackageBuilder builder = new PackageBuilder();
builder.addPackageFromDrl( new InputStreamReader( getClass().getResourceAsStream( "simple_query_test.drl" ) ) );
final Package pkg = builder.getPackage();
RuleBase ruleBase = getSinglethreadRuleBase();
ruleBase.addPackage( pkg );
ruleBase = SerializationHelper.serializeObject( ruleBase );
StatefulSession session = ruleBase.newStatefulSession();
final Cheese stilton = new Cheese( "stinky",
5 );
session.insert( stilton );
session = SerializationHelper.getSerialisedStatefulSession( session,
ruleBase );
QueryResults results = session.getQueryResults( "simple query" );
assertEquals( 1,
results.size() );
assertNotNull( ruleBase.getPackage( "org.drools.test" ).getRule( "simple query" ) );
ruleBase.removeQuery( "org.drools.test",
"simple query" );
assertNull( ruleBase.getPackage( "org.drools.test" ).getRule( "simple query" ) );
results = session.getQueryResults( "simple query" );
assertEquals( 0,
results.size() );
}
@Test
public void testQuery2() throws Exception {
final PackageBuilder builder = new PackageBuilder();
builder.addPackageFromDrl( new InputStreamReader( getClass().getResourceAsStream( "test_Query.drl" ) ) );
if ( builder.hasErrors() ) {
fail( builder.getErrors().toString() );
}
RuleBase ruleBase = getSinglethreadRuleBase();
ruleBase.addPackage( builder.getPackage() );
ruleBase = SerializationHelper.serializeObject( ruleBase );
final WorkingMemory workingMemory = ruleBase.newStatefulSession();
workingMemory.fireAllRules();
final QueryResults results = workingMemory.getQueryResults( "assertedobjquery" );
assertEquals( 1,
results.size() );
assertEquals( new InsertedObject( "value1" ),
results.get( 0 ).get( 0 ) );
}
@Test
public void testQuery2KnowledgeBuilder() throws Exception {
final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add( ResourceFactory.newClassPathResource( "test_Query.drl",
getClass() ),
ResourceType.DRL );
KnowledgeBase kbase = kbuilder.newKnowledgeBase();
kbase.addKnowledgePackages( kbase.getKnowledgePackages() );
if ( kbuilder.hasErrors() ) {
fail( kbuilder.getErrors().toString() );
}
kbase = SerializationHelper.serializeObject( kbase );
final StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
ksession.fireAllRules();
final org.drools.runtime.rule.QueryResults results = ksession.getQueryResults( "assertedobjquery" );
assertEquals( 1,
results.size() );
assertEquals( new InsertedObject( "value1" ),
results.iterator().next().get( "assertedobj" ) );
}
@Test
public void testQueryWithParams() throws Exception {
final PackageBuilder builder = new PackageBuilder();
builder.addPackageFromDrl( new InputStreamReader( getClass().getResourceAsStream( "test_QueryWithParams.drl" ) ) );
if ( builder.hasErrors() ) {
fail( builder.getErrors().toString() );
}
RuleBase ruleBase = getSinglethreadRuleBase();
ruleBase.addPackage( builder.getPackage() );
ruleBase = SerializationHelper.serializeObject( ruleBase );
final WorkingMemory workingMemory = ruleBase.newStatefulSession();
workingMemory.fireAllRules();
QueryResults results = workingMemory.getQueryResults( "assertedobjquery",
new String[]{"value1"} );
assertEquals( 1,
results.size() );
assertEquals( new InsertedObject( "value1" ),
results.get( 0 ).get( 0 ) );
results = workingMemory.getQueryResults( "assertedobjquery",
new String[]{"value3"} );
assertEquals( 0,
results.size() );
results = workingMemory.getQueryResults( "assertedobjquery2",
new String[]{null, "value2"} );
assertEquals( 1,
results.size() );
assertEquals( new InsertedObject( "value2" ),
results.get( 0 ).get( 0 ) );
results = workingMemory.getQueryResults( "assertedobjquery2",
new String[]{"value3", "value2"} );
assertEquals( 1,
results.size() );
assertEquals( new InsertedObject( "value2" ),
results.get( 0 ).get( 0 ) );
}
@Test
public void testQueryWithParamsOnKnowledgeApi() throws Exception {
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add( ResourceFactory.newClassPathResource( "test_QueryWithParams.drl",
getClass() ),
ResourceType.DRL );
if ( kbuilder.hasErrors() ) {
fail( kbuilder.getErrors().toString() );
}
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
kbase = SerializationHelper.serializeObject( kbase );
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
ksession.fireAllRules();
org.drools.runtime.rule.QueryResults results = ksession.getQueryResults( "assertedobjquery",
new String[]{"value1"} );
assertEquals( 1,
results.size() );
// assertEquals( new InsertedObject( "value1" ),
// results.get( 0 ).get( 0 ) );
results = ksession.getQueryResults( "assertedobjquery",
new String[]{"value3"} );
assertEquals( 0,
results.size() );
results = ksession.getQueryResults( "assertedobjquery2",
new String[]{null, "value2"} );
assertEquals( 1,
results.size() );
assertEquals( new InsertedObject( "value2" ),
((org.drools.runtime.rule.QueryResultsRow) results.iterator().next()).get( "assertedobj" ) );
results = ksession.getQueryResults( "assertedobjquery2",
new String[]{"value3", "value2"} );
assertEquals( 1,
results.size() );
assertEquals( new InsertedObject( "value2" ),
((org.drools.runtime.rule.QueryResultsRow) results.iterator().next()).get( "assertedobj" ) );
}
@Test
public void testQueryWithMultipleResultsOnKnowledgeApi() throws Exception {
String str = "";
str += "package org.drools.test \n";
str += "import org.drools.Cheese \n";
str += "query cheeses \n";
str += " stilton : Cheese(type == 'stilton') \n";
str += " cheddar : Cheese(type == 'cheddar', price == stilton.price) \n";
str += "end\n";
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add( ResourceFactory.newByteArrayResource( str.getBytes() ),
ResourceType.DRL );
if ( kbuilder.hasErrors() ) {
fail( kbuilder.getErrors().toString() );
}
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
kbase = SerializationHelper.serializeObject( kbase );
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
Cheese stilton1 = new Cheese( "stilton",
1 );
Cheese cheddar1 = new Cheese( "cheddar",
1 );
Cheese stilton2 = new Cheese( "stilton",
2 );
Cheese cheddar2 = new Cheese( "cheddar",
2 );
Cheese stilton3 = new Cheese( "stilton",
3 );
Cheese cheddar3 = new Cheese( "cheddar",
3 );
Set set = new HashSet();
List list = new ArrayList();
list.add( stilton1 );
list.add( cheddar1 );
set.add( list );
list = new ArrayList();
list.add( stilton2 );
list.add( cheddar2 );
set.add( list );
list = new ArrayList();
list.add( stilton3 );
list.add( cheddar3 );
set.add( list );
ksession.insert( stilton1 );
ksession.insert( stilton2 );
ksession.insert( stilton3 );
ksession.insert( cheddar1 );
ksession.insert( cheddar2 );
ksession.insert( cheddar3 );
org.drools.runtime.rule.QueryResults results = ksession.getQueryResults( "cheeses" );
assertEquals( 3,
results.size() );
assertEquals( 2,
results.getIdentifiers().length );
Set newSet = new HashSet();
for ( org.drools.runtime.rule.QueryResultsRow result : results ) {
list = new ArrayList();
list.add( result.get( "stilton" ) );
list.add( result.get( "cheddar" ) );
newSet.add( list );
}
assertEquals( set,
newSet );
FlatQueryResults flatResults = new FlatQueryResults( ((StatefulKnowledgeSessionImpl) ksession).session.getQueryResults( "cheeses" ) );
assertEquals( 3,
flatResults.size() );
assertEquals( 2,
flatResults.getIdentifiers().length );
newSet = new HashSet();
for ( org.drools.runtime.rule.QueryResultsRow result : flatResults ) {
list = new ArrayList();
list.add( result.get( "stilton" ) );
list.add( result.get( "cheddar" ) );
newSet.add( list );
}
assertEquals( set,
newSet );
}
@Test
public void testTwoQuerries() throws Exception {
// @see JBRULES-410 More than one Query definition causes an incorrect
// Rete network to be built.
final PackageBuilder builder = new PackageBuilder();
builder.addPackageFromDrl( new InputStreamReader( getClass().getResourceAsStream( "test_TwoQuerries.drl" ) ) );
final Package pkg = builder.getPackage();
RuleBase ruleBase = getSinglethreadRuleBase();
ruleBase.addPackage( pkg );
ruleBase = SerializationHelper.serializeObject( ruleBase );
final WorkingMemory workingMemory = ruleBase.newStatefulSession();
final Cheese stilton = new Cheese( "stinky",
5 );
workingMemory.insert( stilton );
final Person per1 = new Person( "stinker",
"smelly feet",
70 );
final Person per2 = new Person( "skunky",
"smelly armpits",
40 );
workingMemory.insert( per1 );
workingMemory.insert( per2 );
QueryResults results = workingMemory.getQueryResults( "find stinky cheeses" );
assertEquals( 1,
results.size() );
results = workingMemory.getQueryResults( "find pensioners" );
assertEquals( 1,
results.size() );
}
@Test
public void testDoubleQueryWithExists() throws Exception {
final PackageBuilder builder = new PackageBuilder();
builder.addPackageFromDrl( new InputStreamReader( getClass().getResourceAsStream( "test_DoubleQueryWithExists.drl" ) ) );
final Package pkg = builder.getPackage();
RuleBase ruleBase = getSinglethreadRuleBase();
ruleBase.addPackage( pkg );
ruleBase = SerializationHelper.serializeObject( ruleBase );
final WorkingMemory workingMemory = ruleBase.newStatefulSession();
final Person p1 = new Person( "p1",
"stilton",
20 );
p1.setStatus( "europe" );
final FactHandle c1FactHandle = workingMemory.insert( p1 );
final Person p2 = new Person( "p2",
"stilton",
30 );
p2.setStatus( "europe" );
final FactHandle c2FactHandle = workingMemory.insert( p2 );
final Person p3 = new Person( "p3",
"stilton",
40 );
p3.setStatus( "europe" );
final FactHandle c3FactHandle = workingMemory.insert( p3 );
workingMemory.fireAllRules();
QueryResults queryResults = workingMemory.getQueryResults( "2 persons with the same status" );
assertEquals( 2,
queryResults.size() );
// europe=[ 1, 2 ], america=[ 3 ]
p3.setStatus( "america" );
workingMemory.update( c3FactHandle,
p3 );
workingMemory.fireAllRules();
queryResults = workingMemory.getQueryResults( "2 persons with the same status" );
assertEquals( 1,
queryResults.size() );
// europe=[ 1 ], america=[ 2, 3 ]
p2.setStatus( "america" );
workingMemory.update( c2FactHandle,
p2 );
workingMemory.fireAllRules();
queryResults = workingMemory.getQueryResults( "2 persons with the same status" );
assertEquals( 1,
queryResults.size() );
// europe=[ ], america=[ 1, 2, 3 ]
p1.setStatus( "america" );
workingMemory.update( c1FactHandle,
p1 );
workingMemory.fireAllRules();
queryResults = workingMemory.getQueryResults( "2 persons with the same status" );
assertEquals( 2,
queryResults.size() );
// europe=[ 2 ], america=[ 1, 3 ]
p2.setStatus( "europe" );
workingMemory.update( c2FactHandle,
p2 );
workingMemory.fireAllRules();
queryResults = workingMemory.getQueryResults( "2 persons with the same status" );
assertEquals( 1,
queryResults.size() );
// europe=[ 1, 2 ], america=[ 3 ]
p1.setStatus( "europe" );
workingMemory.update( c1FactHandle,
p1 );
workingMemory.fireAllRules();
queryResults = workingMemory.getQueryResults( "2 persons with the same status" );
assertEquals( 1,
queryResults.size() );
// europe=[ 1, 2, 3 ], america=[ ]
p3.setStatus( "europe" );
workingMemory.update( c3FactHandle,
p3 );
workingMemory.fireAllRules();
queryResults = workingMemory.getQueryResults( "2 persons with the same status" );
assertEquals( 2,
queryResults.size() );
}
@Test
public void testQueryWithCollect() throws Exception {
final PackageBuilder builder = new PackageBuilder();
builder.addPackageFromDrl( new InputStreamReader( getClass().getResourceAsStream( "test_Query.drl" ) ) );
RuleBase ruleBase = getSinglethreadRuleBase();
ruleBase.addPackage( builder.getPackage() );
ruleBase = SerializationHelper.serializeObject( ruleBase );
final WorkingMemory workingMemory = ruleBase.newStatefulSession();
workingMemory.fireAllRules();
final QueryResults results = workingMemory.getQueryResults( "collect objects" );
assertEquals( 1,
results.size() );
final QueryResult result = results.get( 0 );
final List list = (List) result.get( "$list" );
assertEquals( 2,
list.size() );
}
@Test
public void testDroolsQueryCleanup() {
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add( ResourceFactory.newClassPathResource( "test_QueryMemoryLeak.drl",
getClass() ),
ResourceType.DRL );
KnowledgeBuilderErrors errors = kbuilder.getErrors();
if ( errors.size() > 0 ) {
for ( KnowledgeBuilderError error : errors ) {
System.err.println( error );
}
throw new IllegalArgumentException( "Could not parse knowledge." );
}
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
String workerId = "B1234";
Worker worker = new Worker();
worker.setId( workerId );
org.drools.runtime.rule.FactHandle handle = ksession.insert( worker );
ksession.fireAllRules();
assertNotNull( handle );
Object retractedWorker = null;
for ( int i = 0; i < 100; i++ ) {
retractedWorker = (Object) ksession.getQueryResults( "getWorker",
new Object[]{workerId} );
}
assertNotNull( retractedWorker );
StatefulKnowledgeSessionImpl sessionImpl = (StatefulKnowledgeSessionImpl) ksession;
ReteooWorkingMemoryInterface reteWorkingMemory = sessionImpl.session;
AbstractWorkingMemory abstractWorkingMemory = (AbstractWorkingMemory) reteWorkingMemory;
InternalRuleBase ruleBase = (InternalRuleBase) abstractWorkingMemory.getRuleBase();
Collection<EntryPointNode> entryPointNodes = ruleBase.getRete().getEntryPointNodes().values();
EntryPointNode defaultEntryPointNode = null;
for ( EntryPointNode epNode : entryPointNodes ) {
if ( epNode.getEntryPoint().getEntryPointId() == "DEFAULT" ) {
defaultEntryPointNode = epNode;
break;
}
}
assertNotNull( defaultEntryPointNode );
Map<ObjectType, ObjectTypeNode> obnodes = defaultEntryPointNode.getObjectTypeNodes();
ObjectType key = new ClassObjectType( DroolsQuery.class );
ObjectTypeNode droolsQueryNode = obnodes.get( key );
ObjectHashSet droolsQueryMemory = (ObjectHashSet) abstractWorkingMemory.getNodeMemory( droolsQueryNode );
assertEquals( 0,
droolsQueryMemory.size() );
Entry[] entries = droolsQueryMemory.getTable();
int entryCounter = 0;
for ( Entry entry : entries ) {
if ( entry != null ) {
entryCounter++;
ObjectEntry oEntry = (ObjectEntry) entry;
DefaultFactHandle factHandle = (DefaultFactHandle) oEntry.getValue();
assertNull( factHandle.getObject() );
}
}
}
@Test
public void testQueriesWithVariableUnification() throws Exception {
String str = "";
str += "package org.drools.test \n";
str += "import org.drools.Person \n";
str += "query peeps( String $name, String $likes, int $age ) \n";
str += " $p : Person( $name := name, $likes := likes, $age := age ) \n";
str += "end\n";
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add( ResourceFactory.newByteArrayResource( str.getBytes() ),
ResourceType.DRL );
if ( kbuilder.hasErrors() ) {
fail( kbuilder.getErrors().toString() );
}
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
kbase = SerializationHelper.serializeObject( kbase );
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
Person p1 = new Person( "darth",
"stilton",
100 );
Person p2 = new Person( "yoda",
"stilton",
300 );
Person p3 = new Person( "luke",
"brie",
300 );
Person p4 = new Person( "bobba",
"cheddar",
300 );
ksession.insert( p1 );
ksession.insert( p2 );
ksession.insert( p3 );
ksession.insert( p4 );
org.drools.runtime.rule.QueryResults results = ksession.getQueryResults( "peeps",
new Object[]{Variable.v, Variable.v, Variable.v} );
assertEquals( 4,
results.size() );
List names = new ArrayList();
for ( org.drools.runtime.rule.QueryResultsRow row : results ) {
names.add( ((Person) row.get( "$p" )).getName() );
}
assertEquals( 4,
names.size() );
assertTrue( names.contains( "luke" ) );
assertTrue( names.contains( "yoda" ) );
assertTrue( names.contains( "bobba" ) );
assertTrue( names.contains( "darth" ) );
results = ksession.getQueryResults( "peeps",
new Object[]{Variable.v, Variable.v, 300} );
assertEquals( 3,
results.size() );
names = new ArrayList();
for ( org.drools.runtime.rule.QueryResultsRow row : results ) {
names.add( ((Person) row.get( "$p" )).getName() );
}
assertEquals( 3,
names.size() );
assertTrue( names.contains( "luke" ) );
assertTrue( names.contains( "yoda" ) );
assertTrue( names.contains( "bobba" ) );
results = ksession.getQueryResults( "peeps",
new Object[]{Variable.v, "stilton", 300} );
assertEquals( 1,
results.size() );
names = new ArrayList();
for ( org.drools.runtime.rule.QueryResultsRow row : results ) {
names.add( ((Person) row.get( "$p" )).getName() );
}
assertEquals( 1,
names.size() );
assertTrue( names.contains( "yoda" ) );
results = ksession.getQueryResults( "peeps",
new Object[]{Variable.v, "stilton", Variable.v} );
assertEquals( 2,
results.size() );
names = new ArrayList();
for ( org.drools.runtime.rule.QueryResultsRow row : results ) {
names.add( ((Person) row.get( "$p" )).getName() );
}
assertEquals( 2,
names.size() );
assertTrue( names.contains( "yoda" ) );
assertTrue( names.contains( "darth" ) );
results = ksession.getQueryResults( "peeps",
new Object[]{"darth", Variable.v, Variable.v} );
assertEquals( 1,
results.size() );
names = new ArrayList();
for ( org.drools.runtime.rule.QueryResultsRow row : results ) {
names.add( ((Person) row.get( "$p" )).getName() );
}
assertEquals( 1,
names.size() );
assertTrue( names.contains( "darth" ) );
}
@Test
public void testQueriesWithVariableUnificationOnPatterns() throws Exception {
String str = "";
str += "package org.drools.test \n";
str += "import org.drools.Person \n";
str += "query peeps( Person $p, String $name, String $likes, int $age ) \n";
str += " $p := Person( $name := name, $likes := likes, $age := age ) \n";
str += "end\n";
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add( ResourceFactory.newByteArrayResource( str.getBytes() ),
ResourceType.DRL );
if ( kbuilder.hasErrors() ) {
fail( kbuilder.getErrors().toString() );
}
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
kbase = SerializationHelper.serializeObject( kbase );
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
Person p1 = new Person( "darth",
"stilton",
100 );
Person p2 = new Person( "yoda",
"stilton",
300 );
Person p3 = new Person( "luke",
"brie",
300 );
Person p4 = new Person( "bobba",
"cheddar",
300 );
ksession.insert( p1 );
ksession.insert( p2 );
ksession.insert( p3 );
ksession.insert( p4 );
org.drools.runtime.rule.QueryResults results = ksession.getQueryResults( "peeps",
new Object[]{Variable.v, Variable.v, Variable.v, Variable.v} );
assertEquals( 4,
results.size() );
List names = new ArrayList();
for ( org.drools.runtime.rule.QueryResultsRow row : results ) {
names.add( ((Person) row.get( "$p" )).getName() );
}
assertEquals( 4,
names.size() );
assertTrue( names.contains( "luke" ) );
assertTrue( names.contains( "yoda" ) );
assertTrue( names.contains( "bobba" ) );
assertTrue( names.contains( "darth" ) );
results = ksession.getQueryResults( "peeps",
new Object[]{p1, Variable.v, Variable.v, Variable.v} );
assertEquals( 1,
results.size() );
names = new ArrayList();
for ( org.drools.runtime.rule.QueryResultsRow row : results ) {
names.add( ((Person) row.get( "$p" )).getName() );
}
assertEquals( 1,
names.size() );
assertTrue( names.contains( "darth" ) );
}
@Test
public void testQueriesWithVariableUnificationOnNestedFields() throws Exception {
String str = "";
str += "package org.drools.test \n";
str += "import org.drools.Person \n";
str += "query peeps( String $name, String $likes, String $street) \n";
str += " $p : Person( $name := name, $likes := likes, $street := address.street ) \n";
str += "end\n";
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add( ResourceFactory.newByteArrayResource( str.getBytes() ),
ResourceType.DRL );
if ( kbuilder.hasErrors() ) {
fail( kbuilder.getErrors().toString() );
}
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
kbase = SerializationHelper.serializeObject( kbase );
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
Person p1 = new Person( "darth",
"stilton",
100 );
p1.setAddress( new Address( "s1" ) );
Person p2 = new Person( "yoda",
"stilton",
300 );
p2.setAddress( new Address( "s2" ) );
ksession.insert( p1 );
ksession.insert( p2 );
org.drools.runtime.rule.QueryResults results = ksession.getQueryResults( "peeps",
new Object[]{Variable.v, Variable.v, Variable.v} );
assertEquals( 2,
results.size() );
List names = new ArrayList();
for ( org.drools.runtime.rule.QueryResultsRow row : results ) {
names.add( ((Person) row.get( "$p" )).getName() );
}
assertTrue( names.contains( "yoda" ) );
assertTrue( names.contains( "darth" ) );
results = ksession.getQueryResults( "peeps",
new Object[]{Variable.v, Variable.v, "s1"} );
assertEquals( 1,
results.size() );
names = new ArrayList();
for ( org.drools.runtime.rule.QueryResultsRow row : results ) {
names.add( ((Person) row.get( "$p" )).getName() );
}
assertTrue( names.contains( "darth" ) );
}
@Test
public void testOpenQuery() throws Exception {
String str = "";
str += "package org.drools.test \n";
str += "import org.drools.Cheese \n";
str += "query cheeses(String $type1, String $type2) \n";
str += " stilton : Cheese(type == $type1, $sprice : price) \n";
str += " cheddar : Cheese(type == $type2, $cprice : price == stilton.price) \n";
str += "end\n";
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add( ResourceFactory.newByteArrayResource( str.getBytes() ),
ResourceType.DRL );
if ( kbuilder.hasErrors() ) {
fail( kbuilder.getErrors().toString() );
}
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
kbase = SerializationHelper.serializeObject( kbase );
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
Cheese stilton1 = new Cheese( "stilton",
1 );
Cheese cheddar1 = new Cheese( "cheddar",
1 );
Cheese stilton2 = new Cheese( "stilton",
2 );
Cheese cheddar2 = new Cheese( "cheddar",
2 );
Cheese stilton3 = new Cheese( "stilton",
3 );
Cheese cheddar3 = new Cheese( "cheddar",
3 );
org.drools.runtime.rule.FactHandle s1Fh = ksession.insert( stilton1 );
ksession.insert( stilton2 );
ksession.insert( stilton3 );
ksession.insert( cheddar1 );
ksession.insert( cheddar2 );
org.drools.runtime.rule.FactHandle c3Fh = ksession.insert( cheddar3 );
final List<Object[]> updated = new ArrayList<Object[]>();
final List<Object[]> removed = new ArrayList<Object[]>();
final List<Object[]> added = new ArrayList<Object[]>();
ViewChangedEventListener listener = new ViewChangedEventListener() {
public void rowUpdated( Row row ) {
Object[] array = new Object[6];
array[0] = row.get( "stilton" );
array[1] = row.get( "cheddar" );
array[2] = row.get( "$sprice" );
array[3] = row.get( "$cprice" );
array[4] = row.get( "$type1" );
array[5] = row.get( "$type2" );
updated.add( array );
}
public void rowRemoved( Row row ) {
Object[] array = new Object[6];
array[0] = row.get( "stilton" );
array[1] = row.get( "cheddar" );
array[2] = row.get( "$sprice" );
array[3] = row.get( "$cprice" );
array[4] = row.get( "$type1" );
array[5] = row.get( "$type2" );
removed.add( array );
}
public void rowAdded( Row row ) {
Object[] array = new Object[6];
array[0] = row.get( "stilton" );
array[1] = row.get( "cheddar" );
array[2] = row.get( "$sprice" );
array[3] = row.get( "$cprice" );
array[4] = row.get( "$type1" );
array[5] = row.get( "$type2" );
added.add( array );
}
};
// Open the LiveQuery
LiveQuery query = ksession.openLiveQuery( "cheeses",
new Object[]{"stilton", "cheddar"},
listener );
// Assert that on opening we have three rows added
assertEquals( 3,
added.size() );
assertEquals( 0,
removed.size() );
assertEquals( 0,
updated.size() );
// Assert that the identifiers where retrievable
assertSame( stilton1,
added.get( 0 )[0] );
assertSame( cheddar1,
added.get( 0 )[1] );
assertEquals( 1,
added.get( 0 )[2] );
assertEquals( 1,
added.get( 0 )[3] );
assertEquals( "stilton",
added.get( 0 )[4] );
assertEquals( "cheddar",
added.get( 0 )[5] );
// And that we have correct values from those rows
assertEquals( 1,
added.get( 0 )[3] );
assertEquals( 2,
added.get( 1 )[3] );
assertEquals( 3,
added.get( 2 )[3] );
// Do an update that causes a match to become untrue, thus triggering a removed
cheddar3.setPrice( 4 );
ksession.update( c3Fh,
cheddar3 );
assertEquals( 3,
added.size() );
assertEquals( 1,
removed.size() );
assertEquals( 0,
updated.size() );
assertEquals( 4,
removed.get( 0 )[3] );
// Now make that partial true again, and thus another added
cheddar3.setPrice( 3 );
ksession.update( c3Fh,
cheddar3 );
assertEquals( 4,
added.size() );
assertEquals( 1,
removed.size() );
assertEquals( 0,
updated.size() );
assertEquals( 3,
added.get( 3 )[3] );
// check a standard update
cheddar3.setOldPrice( 0 );
ksession.update( c3Fh,
cheddar3 );
assertEquals( 4,
added.size() );
assertEquals( 1,
removed.size() );
assertEquals( 1,
updated.size() );
assertEquals( 3,
updated.get( 0 )[3] );
// Check a standard retract
ksession.retract( s1Fh );
assertEquals( 4,
added.size() );
assertEquals( 2,
removed.size() );
assertEquals( 1,
updated.size() );
assertEquals( 1,
removed.get( 1 )[3] );
// Close the query, we should get removed events for each row
query.close();
assertEquals( 4,
added.size() );
assertEquals( 4,
removed.size() );
assertEquals( 1,
updated.size() );
assertEquals( 2,
removed.get( 2 )[3] );
assertEquals( 3,
removed.get( 3 )[3] );
// Check that updates no longer have any impact.
ksession.update( c3Fh,
cheddar3 );
assertEquals( 4,
added.size() );
assertEquals( 4,
removed.size() );
assertEquals( 1,
updated.size() );
}
@Test
public void testStandardQueryListener() {
runQueryListenerTest( QueryListenerOption.STANDARD );
}
@Test
public void testNonCloningQueryListener() {
runQueryListenerTest( QueryListenerOption.LIGHTWEIGHT );
}
public void runQueryListenerTest( QueryListenerOption option ) {
String str = "";
str += "package org.drools\n";
str += "query cheeses(String $type) \n";
str += " $cheese : Cheese(type == $type) \n";
str += "end\n";
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add( ResourceFactory.newByteArrayResource( str.getBytes() ),
ResourceType.DRL );
if ( kbuilder.hasErrors() ) {
fail( kbuilder.getErrors().toString() );
}
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
KnowledgeSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
conf.setOption( option );
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession( conf,
null );
// insert some data into the session
for ( int i = 0; i < 10000; i++ ) {
ksession.insert( new Cheese( i % 2 == 0 ? "stilton" : "brie" ) );
}
// query the session
List<Cheese> cheeses;
for ( int i = 0; i < 100; i++ ) {
org.drools.runtime.rule.QueryResults queryResults = ksession.getQueryResults( "cheeses",
new Object[]{"stilton"} );
cheeses = new ArrayList<Cheese>();
for ( QueryResultsRow row : queryResults ) {
cheeses.add( (Cheese) row.get( "$cheese" ) );
}
assertEquals( 5000,
cheeses.size() );
}
}
@Test
public void testQueryWithEval() {
// [Regression in 5.2.0.M2]: NPE during rule evaluation on MVELPredicateExpression.evaluate(MVELPredicateExpression.java:82)
String str = "package org.drools\n" +
"query queryWithEval \n" +
" $do: DomainObject()\n" +
" not DomainObject( id == $do.id, eval(interval.isAfter($do.getInterval())))\n" +
"end";
KnowledgeBase kbase = loadKnowledgeBaseFromString( str );
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
DomainObject do1 = new DomainObject();
do1.setId( 1 );
do1.setInterval( new Interval( 10,
5 ) );
DomainObject do2 = new DomainObject();
do2.setId( 1 );
do2.setInterval( new Interval( 20,
5 ) );
ksession.insert( do1 );
ksession.insert( do2 );
org.drools.runtime.rule.QueryResults results = ksession.getQueryResults( "queryWithEval" );
assertEquals( 1,
results.size() );
assertEquals( do2,
results.iterator().next().get( "$do" ) );
ksession.dispose();
}
private KnowledgeBase loadKnowledgeBaseFromString( String str ) {
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add( ResourceFactory.newByteArrayResource( str.getBytes() ),
ResourceType.DRL );
if ( kbuilder.hasErrors() ) {
fail( kbuilder.getErrors().toString() );
}
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
return kbase;
}
}
| 39.672414
| 144
| 0.541549
|
6a9ef87ef047cec2ea98e21afd77a0509fad3b12
| 2,479
|
lua
|
Lua
|
Libs/tdGUI/Widget/AutoHideController.lua
|
shines77/tdPack2_classic
|
4deb49cfd467961dc085d332a1cab38a8b20e946
|
[
"MIT"
] | null | null | null |
Libs/tdGUI/Widget/AutoHideController.lua
|
shines77/tdPack2_classic
|
4deb49cfd467961dc085d332a1cab38a8b20e946
|
[
"MIT"
] | null | null | null |
Libs/tdGUI/Widget/AutoHideController.lua
|
shines77/tdPack2_classic
|
4deb49cfd467961dc085d332a1cab38a8b20e946
|
[
"MIT"
] | null | null | null |
--[[
AutoHideController.lua
@Author : DengSir (tdaddon@163.com)
@Link : https://dengsir.github.io
]]
local MAJOR, MINOR = 'AutoHideController', 2
local GUI = LibStub('tdGUI-1.0')
local AutoHideController, oldminor, ns = GUI:NewClass(MAJOR, MINOR, 'Frame')
if not AutoHideController then return end
LibStub('AceTimer-3.0'):Embed(AutoHideController)
ns._Objects = ns._Objects or {}
ns.ESCHandler = ns.ESCHandler or CreateFrame('Frame', nil, UIParent)
ns.ESCHandler:Hide()
ns.ESCHandler:SetScript('OnKeyDown', function(self, key)
local found = false
if key == GetBindingKey('TOGGLEGAMEMENU') then
for object in pairs(ns._Objects) do
if object:IsVisible() then
object:OnTimer()
found = true
end
end
self:Hide()
end
self:SetPropagateKeyboardInput(not found)
end)
function AutoHideController:Constructor()
self:SetScript('OnUpdate', self.OnUpdate)
self:SetScript('OnHide', self.OnTimer)
self:SetScript('OnShow', self.OnShow)
ns._Objects[self] = true
end
function AutoHideController:GetOwner()
return self:GetParent():GetOwner()
end
function AutoHideController:IsOwnerVisible()
return self:GetOwner() and self:GetOwner():IsVisible()
end
function AutoHideController:IsOwnerOver()
return self:GetOwner() and self:GetOwner():IsMouseOver()
end
function AutoHideController:IsMenuOver()
return self:GetParent():IsMouseOver()
end
function AutoHideController:OnUpdate(elapsed)
if self:Fire('OnUpdateCheck') then
return self:OnTimer()
end
self.updater = (self.updater or 0) - elapsed
if self.updater > 0 then
return
end
self.updater = 0.5
if self:IsOwnerOver() or self:IsMenuOver() then
self:CancelTimer()
else
self:StartTimer()
end
end
function AutoHideController:OnTimer()
self:GetParent():Hide()
self:CancelTimer()
end
function AutoHideController:CancelTimer()
if self.timer then
self.timer:Cancel()
self.timer = nil
end
end
function AutoHideController:StartTimer()
if not self.timer then
self.timer = C_Timer.NewTimer(self:GetAutoHideDelay(), function() self:OnTimer() end)
end
end
function AutoHideController:OnShow()
ns.ESCHandler:Show()
end
function AutoHideController:SetAutoHideDelay(delay)
self.autoHideDelay = delay
end
function AutoHideController:GetAutoHideDelay()
return self.autoHideDelay or 1.5
end
| 24.303922
| 93
| 0.701493
|
15d9d0a1ab7191b4cc59ff8644730b674c50b671
| 953
|
rb
|
Ruby
|
spec/features/sessions/exceptions_spec.rb
|
saasbook/planning-poker
|
636d3ae60bb2c64a2f272738868cd02c4df9c086
|
[
"MIT"
] | null | null | null |
spec/features/sessions/exceptions_spec.rb
|
saasbook/planning-poker
|
636d3ae60bb2c64a2f272738868cd02c4df9c086
|
[
"MIT"
] | null | null | null |
spec/features/sessions/exceptions_spec.rb
|
saasbook/planning-poker
|
636d3ae60bb2c64a2f272738868cd02c4df9c086
|
[
"MIT"
] | null | null | null |
require 'spec_helper'
describe 'Sessions::Exceptions', type: :feature do
let(:user) { FactoryBot.create(:user) }
context 'unauthenticated' do
before { visit root_path }
specify { expect(current_path).to eq login_path }
specify { expect(page).to have_content t('flashes.sessions.expired') }
end
# context 'no token' do
# before do
# RestClient::Request.stubs(:execute).raises(
# RestClient::Unauthorized
# )
#
# login
# end
#
# specify { page.should have_content t('flashes.sessions.token') }
# end
context 'rest client unauthorized' do
before do
skip_auth_feature(DashboardController)
@client.stubs(:projects).raises(
TrackerApi::Errors::ClientError.new(OpenStruct.new)
)
visit root_path
end
specify { expect(current_path).to eq login_path }
specify { expect(page).to have_content t('flashes.sessions.unauthorized') }
end
end
| 23.243902
| 79
| 0.66107
|
fab1f48aaa10a09f0a0767f7ceacb3dbfd4c9793
| 910
|
kt
|
Kotlin
|
app/src/main/java/dev/eyosiyas/smsblocker/repository/BlacklistRepository.kt
|
devEyosiyas/CodeNightSMSBlocker
|
9304a95ef688c6bc3d7bc5cc598b52e285903d1d
|
[
"MIT"
] | 14
|
2020-09-14T00:56:44.000Z
|
2022-03-21T20:32:54.000Z
|
app/src/main/java/dev/eyosiyas/smsblocker/repository/BlacklistRepository.kt
|
devEyosiyas/CodeNightSMSBlocker
|
9304a95ef688c6bc3d7bc5cc598b52e285903d1d
|
[
"MIT"
] | 1
|
2020-09-10T16:43:08.000Z
|
2020-09-10T16:58:04.000Z
|
app/src/main/java/dev/eyosiyas/smsblocker/repository/BlacklistRepository.kt
|
devEyosiyas/CodeNightSMSBlocker
|
9304a95ef688c6bc3d7bc5cc598b52e285903d1d
|
[
"MIT"
] | 6
|
2020-09-13T13:31:06.000Z
|
2022-01-03T18:50:47.000Z
|
package dev.eyosiyas.smsblocker.repository
import androidx.lifecycle.LiveData
import dev.eyosiyas.smsblocker.dao.BlacklistDao
import dev.eyosiyas.smsblocker.model.Blacklist
class BlacklistRepository(private val blacklistDao: BlacklistDao) {
val blacklists: LiveData<List<Blacklist>> = blacklistDao.blacklists()
suspend fun addBlacklist(blacklist: Blacklist) {
blacklistDao.addBlacklist(blacklist)
}
suspend fun updateBlacklist(blacklist: Blacklist) {
blacklistDao.updateBlacklist(blacklist)
}
suspend fun deleteBlacklist(blacklist: Blacklist) {
blacklistDao.deleteBlacklist(blacklist)
}
suspend fun deleteBlacklists() {
blacklistDao.deleteBlacklists()
}
fun exists(input: String): Boolean {
return blacklistDao.exists(input)
}
suspend fun blacklistCount(): Int {
return blacklistDao.blacklistCount()
}
}
| 28.4375
| 73
| 0.731868
|
f4de036f58fe73c72269e50cc44613b8b4b91c99
| 992
|
lua
|
Lua
|
spirograph-samples/demo.lua
|
LuaDist/zerobraneedupack
|
68920d78dc9a10f3b16b16bd19697857def58931
|
[
"MIT"
] | 55
|
2015-02-15T11:24:59.000Z
|
2021-12-05T07:33:34.000Z
|
spirograph-samples/demo.lua
|
dvdvideo1234/ZeroBraneEduPack
|
9f3764ee34ae31a2a4a8a2ce79250172c57f0bb1
|
[
"MIT"
] | 20
|
2015-04-03T04:23:55.000Z
|
2022-01-19T13:38:13.000Z
|
spirograph-samples/demo.lua
|
dvdvideo1234/ZeroBraneEduPack
|
9f3764ee34ae31a2a4a8a2ce79250172c57f0bb1
|
[
"MIT"
] | 16
|
2015-04-03T00:35:39.000Z
|
2022-01-17T10:41:31.000Z
|
--[[ This program runs scripts that demonstrate what you can do with spirograph graphics. To execute this program [click here](macro:run), press `F6` on the keyboard, or click on `Project | Run` menu at the top of this window. After you explore the demos you can open each of the files to study and tweak them. ]]
require "spirograph"
local demos = [[
astroid.lua
bud.lua
cardioid.lua
circles.lua
donut.lua
double.lua
earth.lua
galaxy.lua
flower.lua
pearls.lua
resolution.lua
rose.lua
spiral.lua
square.lua
star.lua
sunflower.lua
]]
local x,y = size()
local waitorg = wait
wait(1)
for file in demos:gmatch("([%w%p]+)") do
wait = function(seconds)
if seconds then return waitorg(seconds) end
local x, y = size()
posn(-x/2+10, -y/2+10)
hide() -- hide the turtles (if any are shown)
text("Done with '"..file.."'; pause for 2s...")
updt() -- refresh the screen
waitorg(2)
end
dofile('spirograph-samples/'..file)
size(x,y)
end
| 25.435897
| 313
| 0.673387
|
3867da7e1f4a2a5f7057152aeee4098f80f13680
| 13,719
|
php
|
PHP
|
config/common_sliders.php
|
martinvelezf/lab_innovaccion
|
511b7a99c1f90026fe284f3a9f7248bc16397a6b
|
[
"MIT"
] | 1
|
2020-11-26T20:05:49.000Z
|
2020-11-26T20:05:49.000Z
|
config/common_sliders.php
|
martinvelezf/lab_innovaccion
|
511b7a99c1f90026fe284f3a9f7248bc16397a6b
|
[
"MIT"
] | null | null | null |
config/common_sliders.php
|
martinvelezf/lab_innovaccion
|
511b7a99c1f90026fe284f3a9f7248bc16397a6b
|
[
"MIT"
] | null | null | null |
<?php
return [
/*
|--------------------------------------------------------------------------
| Slider list
| Example How to use: @include('slider_support', [ 'sliderID' => 'slider_name', 'slides' => 'slides_group' ])
|--------------------------------------------------------------------------
| Slide configuration list
| title = string
| content = string
| show_button = boolean
| button_title = string
| button_url = string = URL, anchor
| open_new_tab = boolean
| content_classes = string = Bootstrap 4 classes or custom class
| text_color = string = white, black, orange, blue, yellow, red, aqua (see CSS file)
| background_color = string = white, black, orange, blue, yellow, red, aqua (see CSS file)
| background_image_url = string = URL
| background_blend_mode = string = normal(default), use CSS regular values
| background_position = string = Use CSS regular values
*/
'home_slides' => [
// [
// 'title' => '',
// 'content' => '',
// 'show_button' => false,
// 'button_title' => 'BOTON EJEMPLO',
// 'button_background' => 'yellow',
// 'button_text_color' => 'white',
// 'button_url' => '#',
// 'open_new_tab' => false,
// 'content_classes' => 'd-flex flex-column justify-content-center align-items-center text-center',
// 'text_color' => 'white',
// 'background_color' => 'black',
// 'background_image_url' => 'img/home-hero-banner.jpg',
// 'background_blend_mode' => '',
// 'background_position' => 'center',
// 'background_size' => 'cover'
// ],
// [
// 'title' => '',
// 'content' => '',
// 'show_button' => false,
// 'button_title' => 'BOTON EJEMPLO',
// 'button_background' => 'yellow',
// 'button_text_color' => 'white',
// 'button_url' => '#',
// 'open_new_tab' => false,
// 'content_classes' => 'd-flex flex-column justify-content-center align-items-center text-center',
// 'text_color' => 'white',
// 'background_color' => 'black',
// 'background_image_url' => 'img/pexels-pixabay-416405.jpg',
// 'background_blend_mode' => '',
// 'background_position' => 'center',
// 'background_size' => 'cover'
// ],
[
'title' => '',
'content' => '',
'show_button' => false,
'button_title' => 'BOTON EJEMPLO',
'button_background' => 'yellow',
'button_text_color' => 'white',
'button_url' => '#',
'open_new_tab' => false,
'content_classes' => 'd-flex flex-column justify-content-center align-items-center text-center',
'text_color' => 'white',
'background_color' => 'black',
'background_image_url' => 'img/pexels-pixabay-373543.jpg',
'background_blend_mode' => '',
'background_position' => 'center',
'background_size' => 'cover'
],
],
'example_slider' => [
[
'title' => 'PASO 1',
'content' => 'Contenido para el paso 1',
'show_button' => false,
'button_title' => 'Ver más',
'button_url' => '',
'open_new_tab' => false,
'content_classes' => 'd-flex flex-column justify-content-center align-items-center text-center',
'text_color' => '',
'background_color' => '',
'background_image_url' => '',
'background_blend_mode' => '',
'background_position' => '',
'background_size' => ''
],
[
'title' => 'PASO 2',
'content' => 'Contenido para el paso 2',
'show_button' => false,
'button_title' => 'Ver más',
'button_url' => '',
'open_new_tab' => false,
'content_classes' => 'd-flex flex-column justify-content-center align-items-center text-center',
'text_color' => '',
'background_color' => '',
'background_image_url' => '',
'background_blend_mode' => '',
'background_position' => '',
'background_size' => ''
],
[
'title' => 'PASO 3',
'content' => 'Contenido para el paso 3',
'show_button' => false,
'button_title' => 'Ver más',
'button_url' => '',
'open_new_tab' => false,
'content_classes' => 'd-flex flex-column justify-content-center align-items-center text-center',
'text_color' => '',
'background_color' => '',
'background_image_url' => '',
'background_blend_mode' => '',
'background_position' => '',
'background_size' => ''
],
],
'reporta_slides' => [
[
'title' => 'PASO 1',
'content' => 'Registra tu necesidad aquí. Recuerda incluir tu información de contacto.',
'show_button' => false,
'button_title' => 'Ver más',
'button_url' => '',
'open_new_tab' => false,
'content_classes' => 'd-flex flex-column justify-content-center align-items-center text-center',
'text_color' => '',
'background_color' => 'red',
'background_image_url' => '',
'background_blend_mode' => '',
'background_position' => '',
'background_size' => ''
],
[
'title' => 'PASO 2',
'content' => 'Recibirás un correo de confirmación de tu registro',
'show_button' => false,
'button_title' => 'Ver más',
'button_url' => '',
'open_new_tab' => false,
'content_classes' => 'd-flex flex-column justify-content-center align-items-center text-center',
'text_color' => '',
'background_color' => 'red',
'background_image_url' => '',
'background_blend_mode' => '',
'background_position' => '',
'background_size' => ''
],
[
'title' => 'PASO 3',
'content' => 'Comparte tu necesidad en redes para mayor difusión',
'show_button' => false,
'button_title' => 'Ver más',
'button_url' => '',
'open_new_tab' => false,
'content_classes' => 'd-flex flex-column justify-content-center align-items-center text-center',
'text_color' => '',
'background_color' => 'red',
'background_image_url' => '',
'background_blend_mode' => '',
'background_position' => '',
'background_size' => ''
],
[
'title' => 'PASO 4',
'content' => 'Cuando un/a ciudadano/a contribuya a tu necesidad, se pondrá en contacto contigo para coordinar la entrega de la colaboración. NOTA: Recuerda seguir nuestras guías de seguridad COVID-19 para receptar una colaboración en persona. ¡Gracias por formar parte de nuestra comunidad!
',
'show_button' => false,
'button_title' => 'Ver más',
'button_url' => '',
'open_new_tab' => false,
'content_classes' => 'd-flex flex-column justify-content-center align-items-center text-center',
'text_color' => '',
'background_color' => 'red',
'background_image_url' => '',
'background_blend_mode' => '',
'background_position' => '',
'background_size' => ''
],
],
'colabora_slides' => [
[
'title' => 'PASO 1',
'content' => 'Explora las necesidades publicadas cerca de ti',
'show_button' => false,
'button_title' => 'Ver más',
'button_url' => '',
'open_new_tab' => false,
'content_classes' => 'd-flex flex-column justify-content-center align-items-center text-center',
'text_color' => 'white',
'background_color' => 'aqua',
'background_image_url' => '',
'background_blend_mode' => '',
'background_position' => '',
'background_size' => ''
],
[
'title' => 'PASO 2',
'content' => 'Selecciona la necesidad en la que deseas colaborar y lee los detalles',
'show_button' => false,
'button_title' => 'Ver más',
'button_url' => '',
'open_new_tab' => false,
'content_classes' => 'd-flex flex-column justify-content-center align-items-center text-center',
'text_color' => 'white',
'background_color' => 'aqua',
'background_image_url' => '',
'background_blend_mode' => '',
'background_position' => '',
'background_size' => ''
],
[
'title' => 'PASO 3',
'content' => 'Haz click en "Colabora ahora" e ingresa el detalle de tu colaboración',
'show_button' => false,
'button_title' => 'Ver más',
'button_url' => '',
'open_new_tab' => false,
'content_classes' => 'd-flex flex-column justify-content-center align-items-center text-center',
'text_color' => 'white',
'background_color' => 'aqua',
'background_image_url' => '',
'background_blend_mode' => '',
'background_position' => '',
'background_size' => ''
],
[
'title' => 'PASO 4',
'content' => 'Toma nota de la ubicación de entrega y el número de contacto. Comunícate con la persona beneficiaria para coordinar la entrega de tu colaboración. NOTA: Recuerda seguir nuestras guías de seguridad COVID-19.',
'show_button' => false,
'button_title' => 'Ver más',
'button_url' => '',
'open_new_tab' => false,
'content_classes' => 'd-flex flex-column justify-content-center align-items-center text-center',
'text_color' => 'white',
'background_color' => 'aqua',
'background_image_url' => '',
'background_blend_mode' => '',
'background_position' => '',
'background_size' => ''
],
[
'title' => 'PASO 5',
'content' => 'Comparte tu colaboración en redes para motivar a más amigos y familiares a contribuir. ¡Gracias por colaborar!',
'show_button' => false,
'button_title' => 'Ver más',
'button_url' => '',
'open_new_tab' => false,
'content_classes' => 'd-flex flex-column justify-content-center align-items-center text-center',
'text_color' => 'white',
'background_color' => 'aqua',
'background_image_url' => '',
'background_blend_mode' => '',
'background_position' => '',
'background_size' => ''
]
]
];
| 51.575188
| 320
| 0.406881
|
442d3a64baf645e86d88223fdea6691517abbbdd
| 706
|
py
|
Python
|
python/03_tipos_de_dados/tipos.py
|
ac-gomes/python-iniciante
|
002fc91facb5d89c23540d8b05073e8a3c8a4c59
|
[
"MIT"
] | null | null | null |
python/03_tipos_de_dados/tipos.py
|
ac-gomes/python-iniciante
|
002fc91facb5d89c23540d8b05073e8a3c8a4c59
|
[
"MIT"
] | null | null | null |
python/03_tipos_de_dados/tipos.py
|
ac-gomes/python-iniciante
|
002fc91facb5d89c23540d8b05073e8a3c8a4c59
|
[
"MIT"
] | null | null | null |
# função usada abaixo 'print()' é usada para exibir ou imprimir mensagens no console.
# Iteiros | Int
print(10)
# Será exibido no console o numero 10
# Ponto Flutuante | Float
print(9.5)
# Cadeia de caracteres | Strings
cadeia_de_caracter = "Olá Mundo!"
print(cadeia_de_caracter)
# Boleano | Boolean
valor_verdadeiro = True
valor_falso = False
print("valor_verdadeiro: ", valor_verdadeiro)
print("valor_falso: ", valor_falso)
# Tipo de dado None, em Python não existe tipo de dados Null.
valor_none = None
print(valor_none)
# Para verificar o tipo de dado armazenado em uma varivel usar a função type
print("\n")
print(type(valor_none))
print(type(valor_verdadeiro))
print(type(cadeia_de_caracter))
| 23.533333
| 85
| 0.763456
|
aa2f13a83bef3d19d67f8a9836fa782a16697b63
| 1,587
|
swift
|
Swift
|
Groupir/Models/Album.swift
|
dvkch/Groupir
|
007003d0ae080e6cc76b7ad1b34efcc7cc70991a
|
[
"MIT"
] | null | null | null |
Groupir/Models/Album.swift
|
dvkch/Groupir
|
007003d0ae080e6cc76b7ad1b34efcc7cc70991a
|
[
"MIT"
] | null | null | null |
Groupir/Models/Album.swift
|
dvkch/Groupir
|
007003d0ae080e6cc76b7ad1b34efcc7cc70991a
|
[
"MIT"
] | null | null | null |
//
// Album.swift
// Groupir
//
// Created by Stanislas Chevallier on 24/10/2021.
//
import Foundation
import Photos
struct Album: Codable {
// MARK: Init
init(title: String, medias: [Media] = []) {
uniqueID = UUID().uuidString
self.title = title
mediaIDs = medias.sorted().map(\.asset.localIdentifier)
}
init(from decoder: Decoder) throws {
// we need a custom intializer because in older version `uniqueID` didn't exist, and we dont want to loose those groups!
let container = try decoder.container(keyedBy: CodingKeys.self)
uniqueID = try container.decodeIfPresent(String.self, forKey: .uniqueID) ?? UUID().uuidString
title = try container.decode(String.self, forKey: .title)
mediaIDs = try container.decode([String].self, forKey: .mediaIDs)
}
// MARK: Properties
let uniqueID: String
var title: String = "Group"
private(set) var mediaIDs: [String]
var medias: [Media] {
return MediasManager.shared.medias(in: self)
}
enum CodingKeys: String, CodingKey {
case uniqueID = "unique_id"
case title = "title"
case mediaIDs = "media_ids"
}
mutating func add(medias: [Media]) {
let allMedias = self.medias + medias
mediaIDs = allMedias.sorted().map(\.asset.localIdentifier)
}
}
extension Album: Group {
mutating func remove(medias: [Media]) {
let mediaIDsToRemove = Set(medias.map(\.asset.localIdentifier))
mediaIDs.removeAll(where: { mediaIDsToRemove.contains($0) })
}
}
| 29.388889
| 128
| 0.638311
|
ef7fc4f771a4fc36f65584942cd620f6c3a21ebb
| 38,577
|
h
|
C
|
include/pbbam/DataSetTypes.h
|
bio-nim/pbbam
|
d3bf59e90865ef3b39bf50f19fd846db42bb0fe1
|
[
"BSD-3-Clause-Clear"
] | 21
|
2016-04-26T20:46:41.000Z
|
2022-03-01T01:55:55.000Z
|
include/pbbam/DataSetTypes.h
|
bio-nim/pbbam
|
d3bf59e90865ef3b39bf50f19fd846db42bb0fe1
|
[
"BSD-3-Clause-Clear"
] | 25
|
2015-09-03T22:18:01.000Z
|
2019-08-27T14:47:39.000Z
|
include/pbbam/DataSetTypes.h
|
bio-nim/pbbam
|
d3bf59e90865ef3b39bf50f19fd846db42bb0fe1
|
[
"BSD-3-Clause-Clear"
] | 20
|
2015-11-24T15:54:26.000Z
|
2022-03-14T03:49:18.000Z
|
#ifndef PBBAM_DATASETTYPES_H
#define PBBAM_DATASETTYPES_H
#include <pbbam/Config.h>
#include <iosfwd>
#include <string>
#include <pbbam/BamFile.h>
#include <pbbam/CollectionMetadata.h>
#include <pbbam/DataSetXsd.h>
#include <pbbam/internal/DataSetBaseTypes.h>
namespace PacBio {
namespace BAM {
///
/// Set filepath resolving mode for XML output. Default is to always 'absolutize'
/// paths. Selecting 'ALLOW_RELATIVE' leaves file names verbatim.
///
enum class DataSetPathMode
{
ABSOLUTE,
ALLOW_RELATIVE
};
///
/// \brief The DNABarcode class represents a %DNABarcode element in
/// DataSetXML, consisting of a Name and optional UniqueId.
///
class PBBAM_EXPORT DNABarcode : public internal::DataSetElement
{
public:
DNABarcode(const std::string& name);
DNABarcode(const std::string& name, const std::string& uuid);
DNABarcode(const std::string& name, const internal::FromInputXml& fromInputXml);
DNABarcode(const std::string& name, const std::string& uuid,
const internal::FromInputXml& fromInputXml);
const std::string& Name() const;
std::string& Name();
DNABarcode& Name(const std::string& name);
const std::string& UniqueId() const;
std::string& UniqueId();
DNABarcode& UniqueId(const std::string& name);
};
/// \brief The DNABarcodes class represents an %DNABarcodes element in DataSetXML.
///
/// The DNABarcodes element is essentially just a list of DNABarcode
/// objects.
///
class PBBAM_EXPORT DNABarcodes : public internal::DataSetElement
{
public:
DNABarcodes();
DNABarcodes(const internal::FromInputXml& fromInputXml);
public:
void Add(const DNABarcode& barcode);
void Remove(const DNABarcode& barcode);
public:
using value_type = DNABarcode;
using iterator_type = internal::DataSetElementIterator<value_type>;
using const_iterator_type = internal::DataSetElementConstIterator<value_type>;
const value_type& operator[](size_t index) const;
value_type& operator[](size_t index);
iterator_type begin();
const_iterator_type begin() const;
const_iterator_type cbegin() const;
iterator_type end();
const_iterator_type end() const;
const_iterator_type cend() const;
};
class PBBAM_EXPORT BioSample : public internal::DataSetElement
{
public:
BioSample(const std::string& name);
BioSample(const std::string& name, const internal::FromInputXml& fromInputXml);
const BAM::DNABarcodes& DNABarcodes() const;
BAM::DNABarcodes& DNABarcodes();
BioSample& DNABarcodes(const BAM::DNABarcodes& barcodes);
const std::string& Name() const;
std::string& Name();
BioSample& Name(const std::string& name);
};
/// \brief The DNABarcodes class represents an %DNABarcodes element in DataSetXML.
///
/// The DNABarcodes element is essentially just a list of DNABarcode
/// objects.
///
class PBBAM_EXPORT BioSamples : public internal::DataSetElement
{
public:
BioSamples();
BioSamples(const internal::FromInputXml& fromInputXml);
public:
void Add(const BioSample& sample);
void Remove(const BioSample& sample);
public:
using value_type = BioSample;
using iterator_type = internal::DataSetElementIterator<value_type>;
using const_iterator_type = internal::DataSetElementConstIterator<value_type>;
const value_type& operator[](size_t index) const;
value_type& operator[](size_t index);
iterator_type begin();
const_iterator_type begin() const;
const_iterator_type cbegin() const;
iterator_type end();
const_iterator_type end() const;
const_iterator_type cend() const;
};
/// \brief The ExtensionElement class represents an %ExtensionElement element in
/// DataSetXML.
///
class PBBAM_EXPORT ExtensionElement : public internal::DataSetElement
{
public:
ExtensionElement();
ExtensionElement(const internal::FromInputXml& fromInputXml);
};
/// \brief The Extensions class represents an %Extensions element in DataSetXML.
///
/// The Extensions element is essentially just a list of ExtensionElement
/// objects.
///
class PBBAM_EXPORT Extensions : public internal::DataSetElement
{
public:
/// \brief Creates an empty extensions list.
Extensions();
Extensions(const internal::FromInputXml& fromInputXml);
public:
using value_type = ExtensionElement;
using iterator_type = internal::DataSetElementIterator<value_type>;
using const_iterator_type = internal::DataSetElementConstIterator<value_type>;
const value_type& operator[](size_t index) const;
value_type& operator[](size_t index);
iterator_type begin();
const_iterator_type begin() const;
const_iterator_type cbegin() const;
iterator_type end();
const_iterator_type end() const;
const_iterator_type cend() const;
};
class ExternalResources;
/// \brief The ExternalResource class represents an %ExternalResource element in
/// DataSetXML.
///
/// An ExternalResource can itself have a child element, ExternalResources, that
/// lists related files (e.g. index files).
///
class PBBAM_EXPORT ExternalResource : public internal::IndexedDataType
{
public:
/// \brief Creates an ExternalResource from a BamFile object.
///
/// The metatype & resourceId are automatically set.
///
ExternalResource(const BamFile& bamFile);
/// \brief Creates an ExternalResource with provided \p metatype and
/// \p filename as resource ID.
///
ExternalResource(const std::string& metatype, const std::string& filename);
ExternalResource(const std::string& metatype, const std::string& filename,
const internal::FromInputXml& fromInputXml);
public:
/// \brief Fetches the resource's ExternalResources child element.
///
/// \returns const reference to child element
/// \throws std::runtime_error if element does not exist
///
const BAM::ExternalResources& ExternalResources() const;
public:
/// \brief Fetches the resource's ExternalResources child element.
///
/// This element will be created if it does not yet exist.
///
/// \returns non-const reference to child element
///
BAM::ExternalResources& ExternalResources();
/// \brief Sets this resource's ExternalResources child element.
///
/// This element will be created if it does not yet exist.
///
/// \param[in] resources new value for the element
/// \returns reference to this resource object
///
ExternalResource& ExternalResources(const BAM::ExternalResources& resources);
public:
/// \brief Converts an ExternalResource to a BamFile object
///
/// \returns corresponding BamFile object for this ExternalResource
/// \throws std::runtime_error if fails to open %BAM file (e.g. does not
/// exist, not a %BAM file, etc.)
///
/// \deprecated Use the results from DataSet::BamFiles instead. This method
/// cannot resolve relative filepaths and will be removed in the
/// near future.
///
BamFile ToBamFile() const;
};
/// \brief The ExternalResources class represents an %ExternalResources element
/// in DataSetXML.
///
/// The ExternalResources element is essentially just a list of ExternalResource
/// elements.
///
class PBBAM_EXPORT ExternalResources : public internal::DataSetElement
{
public:
/// \brief Creates an empty resource list.
ExternalResources();
ExternalResources(const internal::FromInputXml& fromInputXml);
/// \brief Merges \p other resource list with this one.
ExternalResources& operator+=(const ExternalResources& other);
public:
/// \brief Adds an ExternalResource to this list.
void Add(const ExternalResource& ext);
/// \brief Removes an ExternalResource from this list.
void Remove(const ExternalResource& ext);
public:
/// \brief Converts resource list to BamFile objects.
///
/// \deprecated Use DataSet::BamFiles instead. This method cannot resolve
/// relative filepaths and will be removed in the near future.
///
std::vector<BamFile> BamFiles() const;
public:
using value_type = ExternalResource;
using iterator_type = internal::DataSetElementIterator<value_type>;
using const_iterator_type = internal::DataSetElementConstIterator<value_type>;
const value_type& operator[](size_t index) const;
value_type& operator[](size_t index);
iterator_type begin();
const_iterator_type begin() const;
const_iterator_type cbegin() const;
iterator_type end();
const_iterator_type end() const;
const_iterator_type cend() const;
};
/// \brief The FileIndex class represents a %FileIndex element in DataSetXML.
///
/// A FileIndex is used as an auxiliary to an ExternalResource, providing
/// information about a data file's index file (e.g. for %BAM files, *.bai or
/// *.pbi).
///
class PBBAM_EXPORT FileIndex : public internal::InputOutputDataType
{
public:
/// \brief Creates a FileIndex with provided \p metatype and \p filename as
/// resource ID.
///
FileIndex(const std::string& metatype, const std::string& filename);
FileIndex(const std::string& metatype, const std::string& filename,
const internal::FromInputXml& fromInputXml);
};
/// \brief The FileIndices class represents a %FileIndices element in DataSetXML.
///
/// The FileIndices element is essentially just a list of FileIndex elements,
/// providing information about a data file's index files (e.g. for %BAM files
/// this will usually be *.bai and/or *.pbi).
///
class PBBAM_EXPORT FileIndices : public internal::DataSetElement
{
public:
/// \brief Creates an empty index list.
FileIndices();
FileIndices(const internal::FromInputXml& fromInputXml);
public:
/// \brief Adds a FileIndex to this list.
void Add(const FileIndex& index);
/// \brief Removes a FileIndex from this list.
void Remove(const FileIndex& index);
public:
using value_type = FileIndex;
using iterator_type = internal::DataSetElementIterator<value_type>;
using const_iterator_type = internal::DataSetElementConstIterator<value_type>;
const value_type& operator[](size_t index) const;
value_type& operator[](size_t index);
iterator_type begin();
const_iterator_type begin() const;
const_iterator_type cbegin() const;
iterator_type end();
const_iterator_type end() const;
const_iterator_type cend() const;
};
/// \brief The Filter class represents a %Filter element in DataSetXML.
///
/// The Filter element allows analysis pipelines to describe filters on data
/// that should be respected downstream, without needing to create filtered
/// intermediate files.
///
/// A filter consists of a list of Property elements, each of which must be
/// passed (logical AND) to pass the filter, e.g. property1 && property2 &&
/// property3.
///
class PBBAM_EXPORT Filter : public internal::DataSetElement
{
public:
/// \brief Creates an empty filter.
Filter();
Filter(const internal::FromInputXml& fromInputXml);
public:
/// \brief Fetches the filter's property list element.
///
/// \returns const reference to child element
/// \throws std::runtime_error if element does not exist
///
const BAM::Properties& Properties() const;
public:
/// \brief Fetches the filter's property list child element.
///
/// This element will be created if it does not yet exist.
///
/// \returns non-const reference to child element
///
BAM::Properties& Properties();
/// \brief Sets this filter's Properties child element.
///
/// This element will be created if it does not yet exist.
///
/// \param[in] properties new value for the element
/// \returns reference to this filter object
///
Filter& Properties(const BAM::Properties& properties);
};
/// \brief The Filters class represents a %Filters list element in DataSetXML.
///
/// The Filters element is essentially a list of Filter elements. For analysis
/// purpose, each filter is considered separately (logical OR) to consider which
/// data passes, e.g. filter1 || filter2 || filter3.
///
class PBBAM_EXPORT Filters : public internal::DataSetElement
{
public:
/// \brief Creates an empty filter list.
Filters();
Filters(const internal::FromInputXml& fromInputXml);
/// \brief Merges \p other filter list with this one.
Filters& operator+=(const Filters& other);
public:
/// \brief Adds a filter to this list.
void Add(const Filter& filter);
/// \brief Removes a filter from this list.
void Remove(const Filter& filter);
public:
using value_type = Filter;
using iterator_type = internal::DataSetElementIterator<value_type>;
using const_iterator_type = internal::DataSetElementConstIterator<value_type>;
const value_type& operator[](size_t index) const;
value_type& operator[](size_t index);
iterator_type begin();
const_iterator_type begin() const;
const_iterator_type cbegin() const;
iterator_type end();
const_iterator_type end() const;
const_iterator_type cend() const;
};
/// \brief The ParentTool class represents a %ParentTool element in DataSetXML.
///
class PBBAM_EXPORT ParentTool : public internal::BaseEntityType
{
public:
/// \brief Creates an empty %ParentTool element.
ParentTool();
ParentTool(const internal::FromInputXml& fromInputXml);
};
/// \brief The Property class represents a %Property element in DataSetXML.
///
/// A Property is the primary building block of %DataSetXML filtering. The
/// %Property element describes a data record's property (or field), some value,
/// and a comparison operator.
///
/// For example, one could filter all %BAM records with a read accuracy at or
/// above 0.9. In C++ this could be constructed like:
/// \code{.cpp}
/// Property p("accuracy", "0.9", ">=");
/// \endcode
///
class PBBAM_EXPORT Property : public internal::DataSetElement
{
public:
/// \brief Constructs a filter property.
Property(const std::string& name, const std::string& value, const std::string& op);
Property(const std::string& name, const std::string& value, const std::string& op,
const internal::FromInputXml& fromInputXml);
public:
/// \brief Fetches the value of property's Name attribute.
///
/// \returns const reference to attribute value
///
const std::string& Name() const;
/// \brief Fetches the value of property's Operator attribute.
///
/// \returns const reference to attribute value
///
const std::string& Operator() const;
/// \brief Fetches the value of property's Value attribute.
///
/// \returns const reference to attribute value
///
const std::string& Value() const;
public:
/// \brief Fetches the value of property's Name attribute.
///
/// \returns non-const reference to attribute value
///
std::string& Name();
/// \brief Fetches the value of property's Operator attribute.
///
/// \returns non-const reference to attribute value
///
std::string& Operator();
/// \brief Fetches the value of property's Value attribute.
///
/// \returns nonconst reference to attribute value
///
std::string& Value();
public:
/// \brief Sets this property's Name attribute.
///
/// \param[in] name new value for the attribute
/// \returns reference to this property object
///
Property& Name(const std::string& name);
/// \brief Sets this property's Operator attribute.
///
/// \param[in] op new value for the attribute
/// \returns reference to this property object
///
Property& Operator(const std::string& op);
/// \brief Sets this property's Value attribute.
///
/// \param[in] value new value for the attribute
/// \returns reference to this property object
///
Property& Value(const std::string& value);
};
/// \brief The Properties class represents a %Properties list element in
/// DataSetXML.
///
/// The Properties element is essentially a list of Property elements.
///
class PBBAM_EXPORT Properties : public internal::DataSetElement
{
public:
/// \brief Creates an empty property list.
Properties();
Properties(const internal::FromInputXml& fromInputXml);
public:
/// \brief Adds a property to this list.
void Add(const Property& property);
/// \brief Removes a property from this list.
void Remove(const Property& property);
public:
using value_type = Property;
using iterator_type = internal::DataSetElementIterator<value_type>;
using const_iterator_type = internal::DataSetElementConstIterator<value_type>;
const value_type& operator[](size_t index) const;
value_type& operator[](size_t index);
iterator_type begin();
const_iterator_type begin() const;
const_iterator_type cbegin() const;
iterator_type end();
const_iterator_type end() const;
const_iterator_type cend() const;
};
/// \brief The Provenance class represents a %Provenance element in DataSetXML.
///
class PBBAM_EXPORT Provenance : public internal::DataSetElement
{
public:
/// \brief Creates a empty provenance element.
Provenance();
Provenance(const internal::FromInputXml& fromInputXml);
public:
/// \brief Fetches the value of CreatedBy attribute.
///
/// \returns const reference to attribute value (empty string if not
/// present)
///
const std::string& CreatedBy() const;
/// \brief Fetches the value of CommonServicesInstanceId attribute.
///
/// \returns const reference to attribute value (empty string if not
/// present)
///
const std::string& CommonServicesInstanceId() const;
/// \brief Fetches the value of CreatorUserId attribute.
///
/// \returns const reference to attribute value (empty string if not
/// present)
///
const std::string& CreatorUserId() const;
/// \brief Fetches the value of ParentJobId attribute.
///
/// \returns const reference to attribute value (empty string if not
/// present)
///
const std::string& ParentJobId() const;
/// \brief Fetches the ParentTool child element.
///
/// \returns const reference to child element
/// \throws std::runtime_error if element does not exist
///
const BAM::ParentTool& ParentTool() const;
public:
/// \brief Fetches the value of CreatedBy attribute.
///
/// This attribute will be created if it does not yet exist.
///
/// \returns non-const reference to attribute value (empty string if this is
/// a new attribute)
///
std::string& CreatedBy();
/// \brief Fetches the value of CommonServicesInstanceId attribute.
///
/// This attribute will be created if it does not yet exist.
///
/// \returns non-const reference to attribute value (empty string if this is
/// a new attribute)
///
std::string& CommonServicesInstanceId();
/// \brief Fetches the value of CreatorUserId attribute.
///
/// This attribute will be created if it does not yet exist.
///
/// \returns non-const reference to attribute value (empty string if this is
/// a new attribute)
///
std::string& CreatorUserId();
/// \brief Fetches the value of ParentJobId attribute.
///
/// This attribute will be created if it does not yet exist.
///
/// \returns non-const reference to attribute value (empty string if this is
/// a new attribute)
///
std::string& ParentJobId();
/// \brief Fetches the ParentTool element element.
///
/// This element will be created if it does not yet exist.
///
/// \returns non-const reference to child element
///
BAM::ParentTool& ParentTool();
public:
/// \brief Sets the CreatedBy attribute.
///
/// This attribute will be created if it does not yet exist.
///
/// \param[in] createdBy new value for the attribute
/// \returns reference to this object
///
Provenance& CreatedBy(const std::string& createdBy);
/// \brief Sets the CommonServicesInstanceId attribute.
///
/// This attribute will be created if it does not yet exist.
///
/// \param[in] id new value for the attribute
/// \returns reference to this object
///
Provenance& CommonServicesInstanceId(const std::string& id);
/// \brief Sets the CreatorUserId attribute.
///
/// This attribute will be created if it does not yet exist.
///
/// \param[in] id new value for the attribute
/// \returns reference to this object
///
Provenance& CreatorUserId(const std::string& id);
/// \brief Sets the ParentJobId attribute.
///
/// This attribute will be created if it does not yet exist.
///
/// \param[in] id new value for the attribute
/// \returns reference to this object
///
Provenance& ParentJobId(const std::string& id);
/// \brief Sets the ParentTool child element.
///
/// This element will be created if it does not yet exist.
///
/// \param[in] tool new value for the element
/// \returns reference to this dataset object
///
Provenance& ParentTool(const BAM::ParentTool& tool);
};
/// \brief The DataSetMetadata class represents the %DataSetMetadata child
/// element in DataSetXML.
///
/// A few top-level elements are built-in, but as pbbam is not primarily a
/// DataSetXML API, most of the metadata hierarchy needs to be manually managed.
///
class PBBAM_EXPORT DataSetMetadata : public internal::DataSetElement
{
public:
/// \name Constructors & Related Methods
/// \{
DataSetMetadata();
DataSetMetadata(const internal::FromInputXml& fromInputXml);
/// \brief Constructs a DataSetMetadata with required fields.
DataSetMetadata(const std::string& numRecords, const std::string& totalLength);
DataSetMetadata(const std::string& numRecords, const std::string& totalLength,
const internal::FromInputXml& fromInputXml);
/// \}
public:
/// \name Operators
/// \{
/// \brief Merges DataSetMetadata contents.
///
/// Adds contents of \p other to this metadata object
///
/// \param[in] other some other metadata to add to this one
/// \returns reference to this object
///
DataSetMetadata& operator+=(const DataSetMetadata& other);
/// \}
public:
/// \name Child Elements
/// \{
/// \brief Fetches the text of the NumRecords element.
///
/// \returns const reference to element text (empty string if not present)
///
const std::string& NumRecords() const;
/// \brief Fetches the text of the TotalLength element.
///
/// \returns const reference to element text (empty string if not present)
///
const std::string& TotalLength() const;
/// \brief Fetches the Provenance element.
///
/// \returns const reference to child element
/// \throws std::runtime_error if element does not exist
///
const BAM::Provenance& Provenance() const;
/// \brief Fetches the BioSamples element.
///
/// \returns const reference to child element
/// \throws std::runtime_error if element does not exist
///
const BAM::BioSamples& BioSamples() const;
///
/// \brief Fetches the CollectionMetadata.
///
/// \note Assumes 1 CollectionMetadata child for a given DataSetMetadata instance.
///
/// \returns const reference to child element
/// \throw std::runtime_error if element does not exist
///
const BAM::CollectionMetadata& CollectionMetadata() const;
/// \}
public:
/// \name Child Elements
/// \{
/// \brief Fetches the text of the NumRecords element.
///
/// This element will be created if it does not yet exist.
///
/// \returns non-const reference to element text
///
std::string& NumRecords();
/// \brief Fetches the text of the TotalLength element.
///
/// This element will be created if it does not yet exist.
///
/// \returns non-const reference to element text
///
std::string& TotalLength();
/// \brief Fetches Provenance element.
///
/// This element will be created if it does not yet exist.
///
/// \returns non-const reference to child element
///
BAM::Provenance& Provenance();
/// \brief Fetches BioSamples element.
///
/// This element will be created if it does not yet exist.
///
/// \returns non-const reference to child element
///
BAM::BioSamples& BioSamples();
///
/// \brief Fetches the CollectionMetadata element.
///
/// This element will be created if it does not yet exist.
///
/// \note Assumes 1 CollectionMetadata child for a given DataSetMetadata instance.
///
/// \return const CollectionMetadata&
///
BAM::CollectionMetadata& CollectionMetadata();
/// \}
public:
/// \name Child Elements
/// \{
/// \brief Sets the text of the NumRecords element.
///
/// This element will be created if it does not yet exist.
///
/// \returns reference to this metadata object
///
DataSetMetadata& NumRecords(const std::string& numRecords);
/// \brief Sets the text of the TotalLength element.
///
/// This element will be created if it does not yet exist.
///
/// \returns reference to this metadata object
///
DataSetMetadata& TotalLength(const std::string& totalLength);
/// \brief Sets the Provenance child element.
///
/// This element will be created if it does not yet exist.
///
/// \returns reference to this metadata object
///
DataSetMetadata& Provenance(const BAM::Provenance& provenance);
/// \brief Sets the BioSamples child element.
///
/// This element will be created if it does not yet exist.
///
/// \returns reference to this metadata object
///
DataSetMetadata& BioSamples(const BAM::BioSamples& samples);
/// \brief Sets the CollectionMetadata child element.
///
/// This element will be created if it does not yet exist.
///
/// \returns reference to this metadata object
///
DataSetMetadata& CollectionMetadata(const BAM::CollectionMetadata& metadata);
/// \}
};
class SubDataSets;
/// \brief The DataSetBase class provides the attributes & child elements shared
/// by all dataset types.
///
/// Client code should not need to use this class directly. It should be
/// considered as more of an implementation detail and may in fact be removed
/// from public API in the future. The top-level DataSet is the recommended
/// entry point.
///
class PBBAM_EXPORT DataSetBase : public internal::StrictEntityType
{
public:
/// \brief Creates a DataSetBase object, or one of its subclasses, from an
/// XML element name (e.g. SubreadSet)
///
static std::shared_ptr<DataSetBase> Create(const std::string& typeName);
static std::shared_ptr<DataSetBase> Create(const std::string& typeName,
const internal::FromInputXml& fromInputXml);
public:
/// \brief Creates an empty, generic DataSetBase.
DataSetBase();
DataSetBase(const internal::FromInputXml& fromInputXml);
protected:
/// \brief Creates a DataSetBase with key values initialized.
DataSetBase(const std::string& metatype, const std::string& label, const XsdType& xsd);
DataSetBase(const std::string& metatype, const std::string& label,
const internal::FromInputXml& fromInputXml, const XsdType& xsd);
/// \brief Returns a new DataSetBase containing a deep copy of contents
DataSetBase* DeepCopy() const;
public:
/// \brief Merges dataset contents.
///
/// Adds contents of \p other to this dataset object
///
/// \param[in] other some other dataset to add to this one
/// \returns reference to this dataset object
///
DataSetBase& operator+=(const DataSetBase& other);
public:
/// \brief Fetches the dataset's ExternalResources element.
///
/// \returns const reference to child element
/// \throws std::runtime_error if element does not exist
///
const BAM::ExternalResources& ExternalResources() const;
/// \brief Fetches the dataset's Filters element.
///
/// \returns const reference to child element
///
const BAM::Filters& Filters() const;
/// \brief Fetches the dataset's DataSetMetadata element.
///
/// \returns const reference to child element
///
const BAM::DataSetMetadata& Metadata() const;
/// \brief Fetches the dataset's DataSets element.
///
/// \returns const reference to child element
///
const BAM::SubDataSets& SubDataSets() const;
public:
/// \brief Access this dataset's namespace info.
///
/// \returns const reference to dataset's NamespaceRegistry
///
const NamespaceRegistry& Namespaces() const;
public:
/// \brief Fetches the dataset's ExternalResources element.
///
/// This element will be created if it does not yet exist.
///
/// \returns non-const reference to child element
///
BAM::ExternalResources& ExternalResources();
/// \brief Fetches the dataset's Filters element.
///
/// This element will be created if it does not yet exist.
///
/// \returns non-const reference to child element
///
BAM::Filters& Filters();
/// \brief Fetches the dataset's DataSetMetadata element.
///
/// This element will be created if it does not yet exist.
///
/// \returns non-const reference to child element
///
BAM::DataSetMetadata& Metadata();
/// \brief Fetches the dataset's DataSets element.
///
/// This element will be created if it does not yet exist.
///
/// \returns non-const reference to child element
///
BAM::SubDataSets& SubDataSets();
public:
/// \brief Sets this dataset's ExternalResources element.
///
/// This element will be created if it does not yet exist.
///
/// \param[in] resources new value for the element
/// \returns reference to this dataset object
///
DataSetBase& ExternalResources(const BAM::ExternalResources& resources);
/// \brief Sets this dataset's Filters element.
///
/// This element will be created if it does not yet exist.
///
/// \param[in] filters new value for the element
/// \returns reference to this dataset object
///
DataSetBase& Filters(const BAM::Filters& filters);
/// \brief Sets this dataset's DataSetMetadata element.
///
/// This element will be created if it does not yet exist.
///
/// \param[in] metadata new value for the element
/// \returns reference to this dataset object
///
DataSetBase& Metadata(const BAM::DataSetMetadata& metadata);
/// \brief Sets this dataset's DataSets element.
///
/// This element will be created if it does not yet exist.
///
/// \param[in] subdatasets new value for the element
/// \returns reference to this dataset object
///
DataSetBase& SubDataSets(const BAM::SubDataSets& subdatasets);
public:
/// \brief Access this dataset's namespace info.
///
/// \returns non-const reference to dataset's NamespaceRegistry
///
NamespaceRegistry& Namespaces();
public:
/// \brief Saves dataset XML to file.
///
/// \param[in] outputFilename destination for XML contents
/// \param[in] pathMode print absolute paths or allow relative
///
/// \throws std::runtime_error if file could be opened or if DataSet
/// elements could not be converted to XML
///
void Save(const std::string& outputFilename,
DataSetPathMode pathMode = DataSetPathMode::ABSOLUTE);
/// \brief Saves dataset XML to output stream, e.g. std::cout,
/// std::ostringstream.
///
/// \param[out] out destination for XML contents
/// \param[in] pathMode print absolute paths or allow relative
///
/// \throws std::runtime_error if DataSet elements could not be converted to
/// XML
///
void SaveToStream(std::ostream& out, DataSetPathMode pathMode = DataSetPathMode::ABSOLUTE);
public:
///
/// \returns true if dataset was read from XML input
///
bool FromInputXml() const;
///
/// \brief Indicate that dataset was read from XML input
///
void FromInputXml(bool ok);
///
/// \returns (absolute) path for dataset
///
const std::string& Path() const;
///
/// \brief Set dataset path
///
void Path(const std::string& path);
private:
NamespaceRegistry registry_;
std::string path_;
bool fromInputXml_ = false;
};
/// \brief The AlignmentSet class represents an %AlignmentSet root element in
/// DataSetXML.
///
class PBBAM_EXPORT AlignmentSet : public DataSetBase
{
public:
/// \brief Creates an empty AlignmentSet dataset.
AlignmentSet();
AlignmentSet(const internal::FromInputXml& fromInputXml);
};
/// \brief The BarcodeSet class represents a %BarcodeSet root element in
/// DataSetXML.
///
class PBBAM_EXPORT BarcodeSet : public DataSetBase
{
public:
/// \brief Creates an empty BarcodeSet dataset.
BarcodeSet();
BarcodeSet(const internal::FromInputXml& fromInputXml);
};
/// \brief The ConsensusAlignmentSet class represents a %ConsensusAlignmentSet
/// root element in DataSetXML.
///
class PBBAM_EXPORT ConsensusAlignmentSet : public DataSetBase
{
public:
/// \brief Creates an empty ConsensusAlignmentSet dataset.
ConsensusAlignmentSet();
ConsensusAlignmentSet(const internal::FromInputXml& fromInputXml);
};
/// \brief The ConsensusReadSet class represents a %ConsensusReadSet root
/// element in DataSetXML.
///
class PBBAM_EXPORT ConsensusReadSet : public DataSetBase
{
public:
/// \brief Creates an empty ConsensusReadSet dataset.
ConsensusReadSet();
ConsensusReadSet(const internal::FromInputXml& fromInputXml);
};
/// \brief The ContigSet class represents a %ContigSet root element in
/// DataSetXML.
///
class PBBAM_EXPORT ContigSet : public DataSetBase
{
public:
/// \brief Creates an empty ContigSet dataset.
ContigSet();
ContigSet(const internal::FromInputXml& fromInputXml);
};
/// \brief The HdfSubreadSet class represents a %HdfSubreadSet root element in
/// DataSetXML.
///
class PBBAM_EXPORT HdfSubreadSet : public DataSetBase
{
public:
/// \brief Creates an empty HdfSubreadSet dataset.
HdfSubreadSet();
HdfSubreadSet(const internal::FromInputXml& fromInputXml);
};
/// \brief The ReferenceSet class represents a %ReferenceSet root element in
/// DataSetXML.
///
class PBBAM_EXPORT ReferenceSet : public DataSetBase
{
public:
/// \brief Creates an empty ReferenceSet dataset.
ReferenceSet();
ReferenceSet(const internal::FromInputXml& fromInputXml);
};
/// \brief The SubDataSets class represents a %DataSets list element in
/// DataSetXML.
///
/// The SubDataSets element is essentially a list of DataSets.
///
class PBBAM_EXPORT SubDataSets : public internal::DataSetElement
{
public:
/// \brief Creates an empty list of sub-datasets.
SubDataSets();
SubDataSets(const internal::FromInputXml& fromInputXml);
public:
/// \brief Adds \p other sub-dataset to this list.
SubDataSets& operator+=(const DataSetBase& other); // single
/// \brief Adds \p other sub-dataset list to this list.
SubDataSets& operator+=(const SubDataSets& other); // list
public:
/// \brief Adds a sub-dataset to this list.
void Add(const DataSetBase& subdataset);
/// \brief Removes a sub-dataset from this list.
void Remove(const DataSetBase& subdataset);
public:
using value_type = DataSetBase;
using iterator_type = internal::DataSetElementIterator<value_type>;
using const_iterator_type = internal::DataSetElementConstIterator<value_type>;
const value_type& operator[](size_t index) const;
value_type& operator[](size_t index);
iterator_type begin();
const_iterator_type begin() const;
const_iterator_type cbegin() const;
iterator_type end();
const_iterator_type end() const;
const_iterator_type cend() const;
};
/// \brief The SubreadSet class represents a %SubreadSet root element in
/// DataSetXML.
///
class PBBAM_EXPORT SubreadSet : public DataSetBase
{
public:
/// \brief Creates an empty SubreadSet dataset.
SubreadSet();
SubreadSet(const internal::FromInputXml& fromInputXml);
};
/// \brief The TranscriptSet class represents a %TranscriptSet root element in
/// DataSetXML.
///
class PBBAM_EXPORT TranscriptSet : public DataSetBase
{
public:
/// \brief Creates an empty TranscriptSet dataset.
TranscriptSet();
TranscriptSet(const internal::FromInputXml& fromInputXml);
};
/// \brief The TranscriptAlignmentSet class represents a %TranscriptAlignmentSet
/// root element in DataSetXML.
///
class PBBAM_EXPORT TranscriptAlignmentSet : public DataSetBase
{
public:
/// \brief Creates an empty TranscriptAlignmentSet dataset.
TranscriptAlignmentSet();
TranscriptAlignmentSet(const internal::FromInputXml& fromInputXml);
};
enum class XmlElementType
{
GENERIC_ELEMENT,
DATASET_METADATA,
AUTOMATION,
AUTOMATION_PARAMETER,
AUTOMATION_PARAMETERS,
BINDING_KIT,
BIOSAMPLE,
BIOSAMPLES,
DNA_BARCODE,
DNA_BARCODES,
COLLECTIONS,
COLLECTION_METADATA,
CONTROL_KIT,
EXTENSION,
EXTENSIONS,
EXTERNAL_RESOURCE,
EXTERNAL_RESOURCES,
FILE_INDEX,
FILE_INDICES,
FILTER,
FILTERS,
PARENT_TOOL,
PPACONFIG,
PROPERTY,
PROPERTIES,
PROVENANCE,
SEQUENCING_KIT_PLATE,
TEMPLATE_PREP_KIT,
GENERIC_DATASET,
ALIGNMENT_SET,
BARCODE_SET,
CONSENSUS_ALIGNMENT_SET,
CONSENSUS_READ_SET,
CONTIG_SET,
HDF_SUBREAD_SET,
REFERENCE_SET,
SUBREAD_SET,
TRANSCRIPT_SET,
TRANSCRIPT_ALIGNMENT_SET,
SUBDATASETS
};
/// \returns the enum value for the requested XML element
/// (generic if not a built-in element type)
XmlElementType ElementTypeFromName(const std::string& name);
} // namespace BAM
} // namespace PacBio
#endif // PBBAM_DATASETTYPES_H
| 30.616667
| 95
| 0.678435
|
5b3ed5f94253c1ed2f86c307b583f7008077ccc9
| 3,208
|
dart
|
Dart
|
lib/src/chat/chat_admin_screen_contents.dart
|
dvx-ventures/dvx_flutter_firebase
|
d42d4e06588d4f2ef639114166c9e240db217fe3
|
[
"MIT"
] | null | null | null |
lib/src/chat/chat_admin_screen_contents.dart
|
dvx-ventures/dvx_flutter_firebase
|
d42d4e06588d4f2ef639114166c9e240db217fe3
|
[
"MIT"
] | null | null | null |
lib/src/chat/chat_admin_screen_contents.dart
|
dvx-ventures/dvx_flutter_firebase
|
d42d4e06588d4f2ef639114166c9e240db217fe3
|
[
"MIT"
] | null | null | null |
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:dvx_flutter/dvx_flutter_web.dart';
import 'package:dvx_flutter_firebase/src/chat/chat_models.dart';
import 'package:dvx_flutter_firebase/src/chat/chat_screen_contents.dart';
import 'package:dvx_flutter_firebase/src/firebase/firestore.dart';
class ChatAdminScreenContents extends StatefulWidget {
const ChatAdminScreenContents({
required this.title,
required this.name,
});
final String title;
final String name;
@override
_ChatAdminScreenContentsState createState() =>
_ChatAdminScreenContentsState();
}
class _ChatAdminScreenContentsState extends State<ChatAdminScreenContents> {
final Stream<List<ChatMessage>> stream = ChatMessageUtils.stream(
where: [WhereQuery('', 'admin')],
);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Chat Admin')),
body: StreamBuilder<List<ChatMessage>>(
stream: stream,
builder: (context, snap) {
bool hasData = false;
if (snap.hasError) {
print('snap.hasError');
print(snap);
}
if (snap.hasData && !snap.hasError) {
hasData = true;
}
if (hasData) {
final List<ChatMessage> resources = snap.data ?? [];
return ListView.builder(
itemCount: resources.length,
itemBuilder: (context, index) {
final ChatMessage chat = resources[index];
final String title =
'From: ${chat.user.uid} message: ${chat.text!.substring(0, math.min(10, chat.text!.length))}';
return ListTile(
title: Text(title),
onTap: () {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (context) => ChatScreenContents(
toUid: chat.user.uid,
stream: ChatMessageUtils.stream(
where: [
WhereQuery(chat.user.uid, 'admin'),
WhereQuery('admin', chat.user.uid),
],
),
isAdmin: true,
title: widget.title,
name: widget.name,
),
),
);
},
trailing: IconButton(
icon: const Icon(Icons.remove_circle, color: Colors.red),
onPressed: () {
final deleteStream = ChatMessageUtils.stream(
where: [
WhereQuery(chat.user.uid, 'admin'),
WhereQuery('admin', chat.user.uid),
],
);
ChatMessageUtils.deleteMessagesFromStream(deleteStream);
},
),
);
},
);
}
return LoadingWidget();
},
),
);
}
}
| 32.40404
| 114
| 0.495324
|
e498066ebe221a16fa2e6159268decec4b26eeff
| 2,505
|
h
|
C
|
src/baseapp/modelData.h
|
ZimmerA/HairGroomer
|
8c3579473f9170adff106fdb2079f3e180f3cd38
|
[
"FSFAP"
] | null | null | null |
src/baseapp/modelData.h
|
ZimmerA/HairGroomer
|
8c3579473f9170adff106fdb2079f3e180f3cd38
|
[
"FSFAP"
] | null | null | null |
src/baseapp/modelData.h
|
ZimmerA/HairGroomer
|
8c3579473f9170adff106fdb2079f3e180f3cd38
|
[
"FSFAP"
] | null | null | null |
#ifndef MODEL_H
#define MODEL_H
#include "meshData.h"
#include <vector>
#include <map>
#include <memory>
#include <QOpenGLShaderProgram>
#include <fbxsdk.h>
/**
* \brief Holds the info of a bone
*/
struct Bone
{
glm::mat4 m_global_bindpose{1};
std::string m_name;
int m_parent = -1;
};
/**
* \brief Helper struct used when loading meshes
*/
struct ControlPointInfo
{
glm::vec3 m_position{};
std::vector<VertexBoneInfo> m_bone_info;
};
/**
* \brief Loads and stores all the data of a model, contains a list of MeshData objects that make up the model
*/
class ModelData
{
private:
static glm::vec3 read_normal(FbxMesh* mesh, int control_point_index, int vertex_counter);
static glm::vec2 read_uv(FbxMesh* mesh, int control_point_index, int vertex_counter);
static glm::vec3 read_binormal(FbxMesh* mesh, int control_point_index, int vertex_counter);
static glm::vec3 read_tangent(FbxMesh* mesh, int control_point_index, int vertex_counter);
public:
std::vector<MeshData> m_meshes;
std::vector<std::string> m_name_list;
std::vector<Bone> m_bone_list;
QString m_path;
explicit ModelData(const QString& path);
// Getters/Setters
size_t get_num_bones() const noexcept { return m_bone_map_.size(); }
private:
void load_model(const QString& path);
void process_skeleton_hierachy(FbxNode* node, int parent_index);
void process_mesh_nodes(FbxNode* node, FbxManager* manager);
MeshData process_mesh(FbxMesh* mesh, FbxManager* manager, std::string mesh_name);
// Maps bone names to the index in the bone_list
std::map<std::string, uint> m_bone_map_;
};
/**
* \brief std::unique_ptr wrapper for Fbx pointers to wrap the Create/Destroy mechanism of the fbx sdk
* \tparam T The pointer type
*/
template<typename T>
class FbxPointer : public std::unique_ptr<T, void(*)(T*)>
{
public:
explicit FbxPointer(T *ptr = nullptr);
FbxPointer(FbxPointer &&other) noexcept;
FbxPointer& operator=(FbxPointer &&other) noexcept;
private:
static void destroy(T *ptr);
};
template<typename T>
FbxPointer<T>::FbxPointer(T *ptr) : std::unique_ptr<T, void(*)(T*)>(ptr, &FbxPointer::destroy)
{
}
template<typename T>
FbxPointer<T>::FbxPointer(FbxPointer &&other) noexcept : std::unique_ptr(std::move(other))
{
}
template<typename T>
FbxPointer<T>& FbxPointer<T>::operator=(FbxPointer &&other) noexcept
{
std::unique_ptr<T>::operator=(std::move(other));
return *this;
}
template<typename T>
void FbxPointer<T>::destroy(T *ptr)
{
if (ptr)
ptr->Destroy();
}
#endif // MODEL_H
| 22.168142
| 110
| 0.732934
|
d4f431d85f142a84497fc70f65e35a76051aadaa
| 1,497
|
ts
|
TypeScript
|
src/app/modules/assessments/components/assessment-question-results/assessment-question-results.component.ts
|
danielsprohar/Quizzer
|
be3b5dacce7bf6865bc8c30b8de4f249a80db06e
|
[
"MIT"
] | null | null | null |
src/app/modules/assessments/components/assessment-question-results/assessment-question-results.component.ts
|
danielsprohar/Quizzer
|
be3b5dacce7bf6865bc8c30b8de4f249a80db06e
|
[
"MIT"
] | null | null | null |
src/app/modules/assessments/components/assessment-question-results/assessment-question-results.component.ts
|
danielsprohar/Quizzer
|
be3b5dacce7bf6865bc8c30b8de4f249a80db06e
|
[
"MIT"
] | null | null | null |
import { Component, Input, OnInit } from '@angular/core'
import { Question } from 'src/app/models/question'
import { AssessmentQuestion } from '../../models/assessment-question'
@Component({
selector: 'app-assessment-question-results',
templateUrl: './assessment-question-results.component.html',
styleUrls: ['./assessment-question-results.component.scss'],
})
export class AssessmentQuestionResultsComponent implements OnInit {
@Input() question: Question
@Input() assessmentQuestion: AssessmentQuestion
isMultipleChoice = true
constructor() {}
ngOnInit(): void {
this.isMultipleChoice =
this.question.type === 'multiple choice' ||
this.question.type === 'dropdown'
}
isOptionCorrect(index: number): boolean {
if (!Array.isArray(this.question.options)) {
throw new Error('Question options are not defined')
}
return this.question.options[index].isAnswer
}
isUserSelectedOption(index: number): boolean {
const assessmentOptions = this.assessmentQuestion.options
const options = this.question.options
if (!Array.isArray(assessmentOptions)) {
throw new Error('Assessment options are not defined')
}
if (!Array.isArray(options)) {
throw new Error('Question options are not defined')
}
const expectedOptionText = options[index].text.toUpperCase()
const i = assessmentOptions.findIndex(
(ao) => ao.isSelected && ao.text.toUpperCase() === expectedOptionText
)
return i !== -1
}
}
| 32.543478
| 75
| 0.702739
|
c3bf654ee14d2d296a6a3d332d429c1ac9f68c11
| 1,204
|
cs
|
C#
|
ParseTheArgs.Demo/LongestWordCommand.cs
|
rent-a-developer/ParseTheArgs
|
f95198b51f46a847ec31494b0e49710beb37929a
|
[
"MIT"
] | null | null | null |
ParseTheArgs.Demo/LongestWordCommand.cs
|
rent-a-developer/ParseTheArgs
|
f95198b51f46a847ec31494b0e49710beb37929a
|
[
"MIT"
] | 3
|
2020-09-24T13:07:40.000Z
|
2021-12-07T18:44:17.000Z
|
ParseTheArgs.Demo/LongestWordCommand.cs
|
rent-a-developer/ParseTheArgs
|
f95198b51f46a847ec31494b0e49710beb37929a
|
[
"MIT"
] | null | null | null |
using System;
using System.Linq;
using ParseTheArgs.Setup;
namespace ParseTheArgs.Demo
{
public static class LongestWordCommand
{
public static Int32 LongestWord(LongestWordCommandOptions options)
{
try
{
var longestWord = options.Words.OrderBy(a => a.Length).Last();
Console.WriteLine($"The longest word is: {longestWord}");
return 0;
}
catch (Exception ex)
{
Console.Error.WriteLine("Unhandled exception:");
Console.Error.WriteLine(ex.ToString());
return 1;
}
}
public static void SetupCommand(ParserSetup parserSetup)
{
var command = parserSetup
.Command<LongestWordCommandOptions>()
.Name("longestWord")
.Help("Gets the longest word of a list of words.")
.ExampleUsage("Tool longestWord --words cat dog fish crocodile");
command
.Option(a => a.Words)
.Name("words")
.Help("The list of words.")
.IsRequired();
}
}
}
| 28.666667
| 81
| 0.515781
|
0d5f5fb7a46d715b9cc155a6da2844269163238d
| 723
|
rb
|
Ruby
|
lib/idcf/cli/controller/ilb.rb
|
idcf/idcfcloud-cli
|
b183f9fd7097e99e3ee48fa2dec0733d2a101c58
|
[
"MIT"
] | 3
|
2017-10-02T07:19:27.000Z
|
2017-12-26T05:24:20.000Z
|
lib/idcf/cli/controller/ilb.rb
|
idcf/idcfcloud-cli
|
b183f9fd7097e99e3ee48fa2dec0733d2a101c58
|
[
"MIT"
] | 4
|
2017-11-14T02:32:42.000Z
|
2021-07-06T09:01:59.000Z
|
lib/idcf/cli/controller/ilb.rb
|
idcf/idcfcloud-cli
|
b183f9fd7097e99e3ee48fa2dec0733d2a101c58
|
[
"MIT"
] | 5
|
2017-08-31T09:56:55.000Z
|
2019-06-05T08:43:58.000Z
|
require_relative './base'
module Idcf
module Cli
module Controller
# ILB
class Ilb < Base
default_command :help
class_option :region,
type: :string,
aliases: '-r',
require: true,
desc: 'region: jp-east/jp-east-2/jp-east-3/jp-west'
class << self
def description
'ILB Service'
end
end
protected
def do_async(_api, api_result, o, _executed_link)
job_id = api_result['job_id']
return nil unless do_command('check_job', job_id, o)
do_command('get_job', job_id, o)
end
end
end
end
end
| 21.264706
| 75
| 0.500692
|
b341c8d4f3558aa1d1b8c1ddb4a10c67adfa644a
| 1,335
|
py
|
Python
|
pccold/bypyrm.py
|
davidkingzyb/pccold
|
54a81bed5591f1a8dd1e48a60c29237cd391f6c6
|
[
"MIT"
] | 184
|
2016-08-17T07:13:40.000Z
|
2022-03-23T11:33:40.000Z
|
pccold/bypyrm.py
|
huhuhuni/pccold
|
bb1734a83c0456026b23a1086ad6f2e45a94138e
|
[
"MIT"
] | 23
|
2016-09-18T06:24:10.000Z
|
2021-05-12T08:34:00.000Z
|
pccold/bypyrm.py
|
huhuhuni/pccold
|
bb1734a83c0456026b23a1086ad6f2e45a94138e
|
[
"MIT"
] | 36
|
2016-08-17T07:13:43.000Z
|
2022-03-19T09:48:12.000Z
|
# 2018/12/31 by DKZ
from .tools import sendEmail
import psutil
import subprocess
import logging
from .config import conf
def doBypy():
global conf
logging.info('doBypy')
cmd='cd '+conf.download_path+';bypy upload'
logging.info('$ '+cmd)
shell=subprocess.Popen(cmd,shell=True)
return shell
def psCheck(name):
result=[p.info for p in psutil.process_iter(attrs=['pid', 'name']) if name in p.info['name']]
return result
def initBypyRmEmail(body):
global conf
subj='[pccold] bypyrm '+body
logging.info('[bypyrm] '+body)
try:
sendEmail(subj,conf.my_email,body+'\n'+conf.env+'\n'+conf.pccold_contact,conf.mail_sender,conf.mail_passwd,conf.mail_host,conf.mail_port)
except Exception as e:
logging.info('*** email fail',e)
def bypyrm():
global conf
logging.info('start bypyrm')
if not psCheck('bypy') and not psCheck('streamlink'):
shell=doBypy()
returncode=shell.wait()
if returncode==0:
cmd='cd '+conf.download_path+';rm *.mp4'
p=subprocess.Popen(cmd,shell=True)
if conf.bypy_mail:
initBypyRmEmail('ok')
else:
initBypyRmEmail('fail '+str(returncode))
else:
initBypyRmEmail('psCheck process is runing')
if __name__ == '__main__':
bypyrm()
| 27.244898
| 145
| 0.637453
|
a320d5774a8f2ba4b31570ed54cf38574a3cbf12
| 762
|
java
|
Java
|
src/main/java/ru/bbpax/keeper/configurarion/serialization/CustomBigDecimalSerializer.java
|
Bpaxio/things-keeper
|
eff24427911db94078a9e6e400240a85cc6ed400
|
[
"Apache-2.0"
] | 1
|
2019-05-14T20:31:25.000Z
|
2019-05-14T20:31:25.000Z
|
src/main/java/ru/bbpax/keeper/configurarion/serialization/CustomBigDecimalSerializer.java
|
Bpaxio/things-keeper
|
eff24427911db94078a9e6e400240a85cc6ed400
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/ru/bbpax/keeper/configurarion/serialization/CustomBigDecimalSerializer.java
|
Bpaxio/things-keeper
|
eff24427911db94078a9e6e400240a85cc6ed400
|
[
"Apache-2.0"
] | null | null | null |
package ru.bbpax.keeper.configurarion.serialization;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
import java.math.BigDecimal;
public class CustomBigDecimalSerializer extends StdSerializer<BigDecimal> {
public CustomBigDecimalSerializer() {
this(null);
}
public CustomBigDecimalSerializer(Class<BigDecimal> t) {
super(t);
}
@Override
public void serialize(BigDecimal value,
JsonGenerator jsonGen,
SerializerProvider serializerProvider) throws IOException {
jsonGen.writeString(value.toString());
}
}
| 27.214286
| 85
| 0.715223
|
b0d4346ab41da9a9c0e42731e3a0fa640fbd4eb5
| 24,312
|
c
|
C
|
jsrc/sc.c
|
jsoftware/j-playground
|
fec7be5a9dc92d45c7326556b6058e63fb4f979a
|
[
"MIT"
] | 4
|
2022-01-19T04:23:49.000Z
|
2022-03-28T18:55:38.000Z
|
jsrc/sc.c
|
jsoftware/j-playground
|
fec7be5a9dc92d45c7326556b6058e63fb4f979a
|
[
"MIT"
] | 15
|
2022-02-28T13:09:29.000Z
|
2022-03-11T01:15:39.000Z
|
jsrc/sc.c
|
jsoftware/j-playground
|
fec7be5a9dc92d45c7326556b6058e63fb4f979a
|
[
"MIT"
] | 2
|
2022-01-29T13:26:27.000Z
|
2022-02-23T02:43:31.000Z
|
/* Copyright 1990-2006, Jsoftware Inc. All rights reserved. */
/* Licensed use only. Any other use is in violation of copyright. */
/* */
/* Symbol Table: Named Function Call (unquote) */
#include "j.h"
// This function handles both valences: monad as (w,fs,fs), dyad as (a,w,fs). self is the name reference
//
// This routine calls a 'named' function, which was created by name~ or the equivalent for a stacked verb.
// It also handles pseudo-named functions, which are anonymous entities that need to be given a temporary name
// when they are running under debug. Pseudo-named functions are created by namerefop. We need to run them here so they get the debug side-effects of having a name.
DF2(jtunquote){A z;I flgd0cp; // flgs: 1=pseudofunction 2=cached lookup 8=execution of dyad
F2PREFIP; // We understand inplacing. We check inplaceability of the called function.
RE(0);
JATTN;
flgd0cp=w!=self?8:0; // if we were called with w,fs,fs, we are a monad. Otherwise (a,w,fs) dyad
V *v=FAV(self); // V block for this V/A/C reference
I callstackx=jt->callstacknext; // Remember where our stack frame starts. We may add an entry; execution may add more
A thisname=v->fgh[0]; A fs; A explocale; L *stabent;// the A block for the name of the function (holding an NM) - unless it's a pseudo-name fs is the 'named' function itself explocale=explicit locale if any stabent=symbol-table entry if any
A savname=jt->curname; // we stack the executing name
if(likely(thisname!=0)){ // normal names
jt->curname=thisname; // set failing name before we have value errors
// normal path for named functions
I4 cachedlkp=v->localuse.lu1.cachedref; // negative if cacheable; positive if cached
if(cachedlkp>0){
// There is a lookup for this nameref - use it
stabent=&JT(jt,sympv)[cachedlkp]; // the symbol block for the cached item
fs=stabent->val; // the value of the cached item
if(likely(fs!=0)){
// the lookup exists. If it has a (necessarily direct) locative, we must fetch the locative so we switch to it
if(unlikely(NAV(thisname)->flag&NMLOC)){RZ(explocale=stfindcre(AN(thisname)-NAV(thisname)->m-2,1+NAV(thisname)->m+NAV(thisname)->s,NAV(thisname)->bucketx));} // extract locale string, find/create locale
else explocale=0; // if no direct locative, set so
flgd0cp|=2; // indicate cached lookup
}else{cachedlkp=v->localuse.lu1.cachedref=SYMNONPERM; goto valgone;} // if the value vanished, it must have been erased by hand. Reenable caching but keep looking
}else{
valgone: ;
if(!(NAV(thisname)->flag&(NMLOC|NMILOC|NMIMPLOC))) { // simple name, and not u./v.
explocale=0; // flag no explicit locale
if(likely(!(stabent = probelocal(thisname,jt->locsyms)))){stabent=jtsyrd1((J)((I)jt+NAV(thisname)->m),NAV(thisname)->s,NAV(thisname)->hash,jt->global);} // Try local, then look up the name starting in jt->global
}else{ // locative or u./v.
if(likely(!(NAV(thisname)->flag&NMIMPLOC))){ // locative
RZ(explocale=sybaseloc(thisname)); // get the explicit locale. 0 if erroneous locale
stabent=jtsyrd1((J)((I)jt+NAV(thisname)->m),NAV(thisname)->s,NAV(thisname)->hash,explocale); // Look up the name starting in the locale of the locative
}else{ // u./v. We have to look at the assigned name/value to know whether this is an implied locative (it usually is)
if(stabent = probelocal(thisname,jt->locsyms)){
// u/v, assigned by xdefn. Implied locative. Use switching to the local table as a flag for restoring the caller's environment
explocale=jt->locsyms; // We have to use this flag trick, rather than stacking the locales here, because errors after the stack is set could corrupt the stack
}
}
}
// syrd1 returns bit 0 set if the value is from a named locale, i. e. is cachable. probelocal always returns with that flag off, since local symbols are never cachable
ASSERT(stabent!=0,EVVALUE); // name must be defined
I4 cacheable=(I4)(I)stabent&ARNAMED; stabent=(L*)((I)stabent&~ARNAMED); // extract cachable flag from stabent & clear it
fs=stabent->val; // fetch the value for the name
ASSERT(fs!=0,EVVALUE); // make sure the name's value is given also
ASSERT(PARTOFSPEECHEQACV(AT(self),AT(fs)),EVDOMAIN); // make sure its part of speech has not changed since the name was parsed
// if this reference allows caching (lI4[0]<0), save the value if it comes from a cachable source, and attach the primitive block to the name
if(unlikely((cachedlkp&(-cacheable))<0)){
// point the nameref to the lookup result. This prevents further changes to the lookup
v->localuse.lu1.cachedref=stabent-JT(jt,sympv); // convert symbol address back to index in case symbols are relocated
stabent->flag|=LCACHED; // protect the value from changes
// set the flags in the nameref to what they are in the value. This will allow compounds using this nameref (created in the parsing of later sentences)
// to use the flags. If we do PPPP, this will be too late
v->flag=FAV(fs)->flag&(VIRS1+VIRS2+VJTFLGOK1+VJTFLGOK2+VASGSAFE); // combining flags, do not require looking into id
v->flag2=FAV(fs)->flag2&(VF2WILLOPEN1+VF2USESITEMCOUNT1+VF2WILLOPEN2W+VF2WILLOPEN2A+VF2USESITEMCOUNT2W+VF2USESITEMCOUNT2A); // combining flags, do not require looking into id
// flag2: if we look through name(s) when replacing f[12] and fs, we could support VF2BOXATOP1+VF2BOXATOP2+VF2ATOPOPEN1+VF2ATOPOPEN2W+VF2ATOPOPEN2A+
// and we might be able to use VF2RANKATOP1+VF2RANKATOP2+VF2RANKONLY1+VF2RANKONLY2+ but we haven't checked the loops yet
// we could mark the lookup as cached, but if debug is on we want to display the lookup value first time through ???
// If the NM block is cachable, point it to the nameref. The NM block must be marked cachable AND still be pointed to by the explicit definition, which
// means that its usecount must be more than what comes from the nameref. If the explicit definition has been deleted, we must ensure that we don't put a loop
// in the chains, because there will never be a free from the non-nameref side to break the loop
if(NAV(thisname)->flag&NMCACHED && AC(thisname)>((AFLAG(self)&TRAVERSIBLE)!=0)){ // name from explicit definition, and definition still active
// This leads to a loop in the inclusion graph, as nameref and name point to each other. We have special code in fa() for names to break the loop.
// We must ensure that raising the nameref does not raise the usecount of the name, as it would if the nameref is not yet recursive. If the usecount of the
// name were raised, it would never go to 0 when the explicit definition is freed, and the block would leak. Likewise we must undo the situation where the
// nameref was raised before this caching: that would set the name usecount to 2 and freeing the explicit verb would not trigger revisiting the link to the
// nameref. In short, when there is a cached ref from the name, the count of the name is always 1, and the nameref has been incremented: so the name will
// not go away until the explicit does, and when that happens, the link will be removed in fa().
NAV(thisname)->cachedref=self; ra(self); ACSET(thisname,ACUC1); // exp def is ALWAYS recursive usecount, so we raise self when we store to it.
// This wipes out bucket info in self, but that will not be needed since we have cached the lookup
}
}
}
}else{
// here for pseudo-named function. The actual name is in g, and the function itself is pointed to by h. The verb is an anonymous explicit modifier that has received operands (but not arguments)
// The name is defined, but it has the value before the modifier operands were given, so ignore fields in it except for the name
jt->curname=thisname=v->fgh[1]; // get the original name
explocale=0; // flag no explicit locale
fs=v->fgh[2]; // point to the actual executable
ASSERT(fs!=0,EVVALUE); // make sure the name's value is given also
ASSERT(TYPESEQ(AT(self),AT(fs)),EVDOMAIN); // make sure its part of speech has not changed since the name was parsed
// The pseudo-named function was created under debug mode. If the same sequence had been parsed outside of debug, it would have been anonymous. This has
// implications: anonymous verbs do not push/pop the locale stack. If bstkreqd is set, ALL functions will push the stack here. That is bad, because
// it means that a function that modifies the current locale behaves differently depending on whether debug is on or not. We set a flag to indicate the case
flgd0cp|=1; // indicate pseudofunction
stabent=0; // no name lookup was performed
}
#if NAMETRACK
// bring out the name, locale, and script into easy-to-display name
C trackinfo[256]; // will hold name followed by locale
forcetomemory(&trackinfo);
mvc(sizeof(trackinfo),trackinfo,1,iotavec-IOTAVECBEGIN+' '); // clear name & locale
UI wx=0, wlen; // index/len we will write to
wlen=AN(thisname); wlen=wlen+wx>sizeof(trackinfo)-3?sizeof(trackinfo)-3-wx:wlen; MC(trackinfo+wx,NAV(thisname)->s,wlen); wx+=wlen+1; // copy in the full name
A locnm=LOCNAME(jt->global); // name of current global locale
wlen=AN(locnm); wlen=wlen+wx>sizeof(trackinfo)-2?sizeof(trackinfo)-2-wx:wlen; MC(trackinfo+wx,NAV(locnm)->s,wlen); wx+=wlen+1; // copy in the locale name
if(stabent&&stabent->sn>=0){
wlen=AN(AAV(JT(jt,slist))[stabent->sn]); wlen=wlen+wx>sizeof(trackinfo)-1?sizeof(trackinfo)-1-wx:wlen; MC(trackinfo+wx,CAV(AAV(JT(jt,slist))[stabent->sn]),wlen); wx+=wlen; // copy in the locale name
}
trackinfo[wx]=0; // null-terminate the info
#endif
v=FAV(fs); // repurpose v to point to the resolved verb block
#if !USECSTACK
I d=v->fdep; if(!d)RE(d=fdep(fs)); // get stack depth of this function, for overrun prevention
FDEPINC(d); // verify sufficient stack space - NO ERRORS until FDEPDEC below
#endif
STACKCHKOFL
if(unlikely(explocale!=0)){ // there is a locative or implied locative
// locative. switch to it, stacking the prev value. If the switch is to the current local symbol table, that means 'switch to caller's environment'
if(unlikely(explocale==jt->locsyms)){
pushcallstack1d(CALLSTACKPUSHLOCALSYMS,jt->locsyms); // save current locsyms
jt->locsyms=(A)AM(jt->locsyms); // get the local syms at the time u/v was assigned; make them current. Leave GST unchanged in it
explocale=AKGST(jt->locsyms); // fetch global syms for the caller's environment, so we stack it next
}
pushcallstack1d(CALLSTACKPOPLOCALE,jt->global); jt->global=explocale; // move to new implied locale. DO NOT change locale in lt->locsyms. It is set only by explicit action so that on a chain of locatives it stays unchanged
}
// ************** no errors till the stack has been popped
AF actionfn=v->valencefns[flgd0cp>>3]; // index is 'is dyad'. Load here to allow call address to settle
w=flgd0cp&8?w:(A)fs; // set up the bivalent argument with the new self, since fs may have been changed
// Execute the name. First check 4 flags at once to see if anything special is afoot: debug, pm, bstk, garbage collection
if(likely(!(jt->uflags.ui4))) {
// No special processing. Just run the entity
// We have to raise the usecount, in case the name is deleted while running. But that will be very rare. Plus, we know that the executable type is recursive and non-inplaceable.
// So, all we have to do is increment the usecount. If it's a PERMANENT symbol no harm will be done, since we decrement below
// CODING NOTE: after considerable trial and error I found this ordering, whose purpose is to start the load of the indirect branch address as early as
// possible before the branch. Check the generated code on any change of compiler.
if(unlikely(!(flgd0cp&2)))ACINCR(fs); // protect the entity ONLY if not cached. If it is cached it will never be truly deleted
// Recursion through $: does not go higher than the name it was defined in. We make this happen by pushing the name onto the $: stack
A s=jt->parserstackframe.sf; jt->parserstackframe.sf=fs; z=(*actionfn)((J)(((REPSGN(SGNIF(v->flag,(flgd0cp>>3)+VJTFLGOK1X)))|~JTFLAGMSK)&(I)jtinplace),a,w,fs); jt->parserstackframe.sf=s; // keep all flags in jtinplace
// Undo the protection. If, most unusually, the usecount goes to 0, back up and do the full recursive decrement
if(unlikely(!(flgd0cp&2))){ACDECR(fs); if(unlikely(AC(fs)<=0)){ACINCR(fs); fa(fs);}}
} else {
// Extra processing is required. Check each option individually
DC d=0; // pointer to debug stack frame, if one is allocated
if(jt->uflags.us.cx.cx_us){ // debug or pm
// allocate debug stack frame if we are debugging OR PM'ing. In PM, we need a way to get the name being executed in an operator
RZ(d=deba(DCCALL,flgd0cp&8?a:0,flgd0cp&8?w:a,fs)); d->dcn=(I)(flgd0cp&3?0:stabent); // save last sym lookup as debug parm if it is valid (not cached or pseudoname)
}
if(jt->uflags.us.cx.cx_c.pmctr)pmrecord(thisname,jt->global?LOCNAME(jt->global):0,-1L,flgd0cp&8?VAL2:VAL1); // Record the call to the name, if perf monitoring on
// If we are required to insert a marker for each call, do so (if it hasn't been done already). But not for pseudo-named functions
if(!(flgd0cp&1) && jt->uflags.us.uq.uq_c.bstkreqd && callstackx==jt->callstacknext){pushcallstack1d(CALLSTACKPOPLOCALE,jt->global);} // If cocurrent is about, make every call visible
if(jt->uflags.us.cx.cx_c.db&&!(jt->glock||VLOCK&v->flag)&&jt->recurstate<RECSTATEPROMPT){ // The verb is locked if it is marked as locked, or if the script is locked; if recursive JDo, can't enter debug suspension so ignore debug
z=dbunquote(flgd0cp&8?a:0,flgd0cp&8?w:a,fs,d); // if debugging, go do that.
}else{
if(unlikely(!(flgd0cp&2)))ACINCR(fs); // protect the entity if not cached
A s=jt->parserstackframe.sf; jt->parserstackframe.sf=fs; z=(*actionfn)((J)(((REPSGN(SGNIF(v->flag,(flgd0cp>>3)+VJTFLGOK1X)))|~JTFLAGMSK)&(I)jtinplace),a,w,fs); jt->parserstackframe.sf=s;
if(unlikely(!(flgd0cp&2))){ACDECR(fs); if(unlikely(AC(fs)<=0)){ACINCR(fs); fa(fs);}}
}
if(jt->uflags.us.cx.cx_c.pmctr)pmrecord(thisname,jt->global?LOCNAME(jt->global):0,-2L,flgd0cp&8?VAL2:VAL1); // record the return from call
if(jt->uflags.us.uq.uq_c.spfreeneeded)spfree(); // if garbage collection required, do it
if(d)debz(); // release stack frame if allocated
}
#if !USECSTACK
FDEPDEC(d);
#endif
// Now pop the stack. Execution may have added entries, but our stack frame always starts in the same place.
// We may add entries to the end of the caller's stack frame
jt->curname=savname; // restore the executing name
if(unlikely(callstackx!=jt->callstacknext)){ // normal case, with no stack, bypasses all this
// There are stack entries. Process them
if(likely(((jt->callstack[callstackx].type^CALLSTACKPOPLOCALE) | ((callstackx+1)^jt->callstacknext))==0)) { // jt->callstack[callstackx].type==CALLSTACKPOPLOCALE && callstackx+1==jt->callstacknext
// The only thing on the stack is a simple POP. Do the pop. This & the previous case account for almost all the calls here
SYMSETGLOBAL(jt->locsyms,jt->callstack[callstackx].value); // restore global locale
jt->callstacknext=(I4)callstackx; // restore stackpointer for caller
}else{
// Locales were changed or deleted. Process the stack fully
// Find the locale to return to. This will be the locale of the POP, or jt->global unchanged if there is a POPFROM or there is no POP.
// There can never be more than one POP.
I fromfound=0; A earlyloc=0; I i;
i=jt->callstacknext; // back to front
do{
--i;
fromfound|=jt->callstack[i].type&CALLSTACKPOPFROM&&!(jt->callstack[callstackx].type&CALLSTACKPUSHLOCALSYMS); // remember if FROM seen - but if we are processing u/v, always revert global, ignoring any hanging requests
if(jt->callstack[i].type&(CALLSTACKPOPFROM|CALLSTACKPOPLOCALE|CALLSTACKPOPLOCALEFIRST)){
earlyloc=jt->callstack[i].value; // remember earliest POP[FROM]
// When we remove the earliest POPFROM, we can go back to processing names without requiring stacking the return locale
if(jt->callstack[i].type&CALLSTACKPOPLOCALEFIRST){jt->uflags.us.uq.uq_c.bstkreqd = 0;}
}else if(jt->callstack[i].type&CALLSTACKPUSHLOCALSYMS)SYMSETLOCAL((A)jt->callstack[i].value); // restore locsyms if we stacked it, and restore possibly-changed global value therein
}while(i!=callstackx);
// if we encountered u./v., we have now restored the previous local symbols so that it is OK to restore the globals into it
if(earlyloc&&!fromfound){SYMSETGLOBAL(jt->locsyms,earlyloc);} // If there is a POP to do, do it
// Delete the deletable locales. If we encounter the (possibly new) current locale, remember that fact and don't delete it.
I delcurr=0; // set if we have to delete jt->global
i=jt->callstacknext; // back to front
do{
--i;
if(jt->callstack[i].type&CALLSTACKDELETE){
if(jt->callstack[i].value==jt->global)delcurr=1;else locdestroy(jt->callstack[i].value); // destroy or mark for later
}
}while(i!=callstackx);
jt->callstacknext=(I4)callstackx; // restore stackpointer for caller. The following pushes are onto the caller's stack
// NOTE: if there is no higher executing name, these pushes will never get popped. That would correspond to trying to delete the locale that is running at the console,
// or typing (cocurrent 'a') into the console, which would leave a POP on the stack, never to be executed because there is no higher function to return to base locale.
// There is no way to detect this, because names that don't change locales don't leave a trace, and there is no guarantee that the function-call stack will
// be at 0 when the last name returns, because the name might have been called from the middle of a tacit expression that already had a function-call depth when the
// name was called.
// So, we reset the name-stack pointer whenever we call from console level (jt->uflags.us.uq.uq_c.bstkreqd too)
// If there is a POPFROM, we have to make sure it is undone when the caller returns. If the caller has a POP already, we can leave it alone; otherwise we have to add one.
// To make sure we don't overflow the stack because of a sequence of cocurrents, we use jt->uflags.us.uq.uq_c.bstkreqd to indicate that a POPFROM is on the stack and in that case
// we ensure that there is a POP for every name (but don't create new ones for every cocurrent). Thus, if jt->uflags.us.cx.cx_c.bstkreqd is not set, we set it for future calls, and put a POPFIRST onto the caller's stack.
// When that is found, jt->uflags.us.uq.uq_c.bstkreqd will be reset
if(fromfound){
if(!(jt->uflags.us.uq.uq_c.bstkreqd)){pushcallstack1(CALLSTACKPOPLOCALEFIRST,earlyloc); jt->uflags.us.uq.uq_c.bstkreqd=1;}
}
// If the current locale was deletable, push an entry to that effect in the caller's stack. It will be deleted when it becomes un-current (if ever: if
// the locale is still in use back to console level, it will not be deleted. Invariant: if a locale is marked for destruction, it appears
// nowhere earlier on the call stack
if(delcurr)pushcallstack1(CALLSTACKCHANGELOCALE|CALLSTACKDELETE,jt->global);
}
}
// ************** errors OK now
R z;
}
// The monad calls the bivalent case with (w,self,self) so that the inputs can pass through to the executed function
static DF1(jtunquote1){R unquote(w,self,self);} // This just transfers to jtunquote. It passes jt, with inplacing bits, unmodified
// return ref to adv/conj/verb whose name is a and whose symbol-table entry is w
// if the value is a noun, we just return the value; otherwise we create a 'name~' block
// and return that; the name will be resolved when the name~ is executed.
// If the name is undefined, return a reference to [: (a verb that always fails)
A jtnamerefacv(J jt, A a, L* w){A y;V*v;
y=w?w->val:ds(CCAP); // If there is a slot, get the value; if not, treat as [: (verb that creates error)
if(!y||NOUN&AT(y))R y; // return if error or it's a noun
// This reference might escape into another context, either (1) by becoming part of a
// non-noun result; (2) being assigned to a global name; (3) being passed into an explicit modifier: so we clear the bucket info if we ra() the reference
v=FAV(y);
// We cannot be guaranteed that the definition in place when a reference is created is the same value that is there when the reference
// is used. Thus, we can't guarantee inplaceability by copying INPLACE bits from f to the result, and we just set INPLACE for everything
// and let unquote use the up-to-date value.
// ASGSAFE has a similar problem, and that's more serious, because unquote is too late to stop the inplacing. We try to ameliorate the
// problem by making [: unsafe.
A z=fdef(0,CTILDE,AT(y), jtunquote1,jtunquote, a,0L,0L, (v->flag&VASGSAFE)+(VJTFLGOK1|VJTFLGOK2), v->mr,lrv(v),rrv(v)); // create value of 'name~', with correct rank, part of speech, and safe/inplace bits
RZ(z);
// if the nameref is cachable, either because the name is cachable or name caching is enabled now, enable caching in lI4
// If the nameref is cached, we will fill in the flags in the reference after we first resolve the name
FAV(z)->localuse.lu1.cachedref=(NAV(a)->flag&NMCACHED || (jt->namecaching && !(NAV(a)->flag&(NMILOC|NMDOT|NMIMPLOC))))<<SYMNONPERMX; // 0x80.. to enable caching, otherwise 0
R z;
}
// return reference to the name given in w, used when moving from queue to stack
// For a noun, the reference points to the data, and has rank/shape info
// For other types, we build a function ref to 'name~', and fill in the type, rank, and a pointer to the name;
// the name will be dereferenced when the function is executed
A jtnameref(J jt,A w,A locsyms){
ARGCHK1(w);
R namerefacv(w,syrd(w,locsyms)); // get the symbol-table slot for the name (don't store the locale-name); return its 'value'
} /* argument assumed to be a NAME */
// Adverb 4!:8 create looked-up cacheable reference to (possibly boxed) literal name a
// The name must be defined. It supplies the type and rank of the reference. We require the name to be defined so that
// there will not be a circular reference if a name in a numbered locale is a reference to the same name
F1(jtcreatecachedref){
A nm; RZ(nm=onm(w)); // create name from arg
ASSERT(!(NAV(nm)->flag&(NMILOC|NMDOT|NMIMPLOC)),EVDOMAIN) // if special name or indirect locative, error
L *sym=syrd(nm,JT(jt,emptylocale)); // look up name, but not in local symbols. We start with the current locale (?? should start with the path?)
ASSERT(sym!=0,EVVALUE); // return if error or name not defined
A z=sym->val; if(unlikely(AT(z)&NOUN))R z; // if name is a noun, return its value
RZ(z=fdef(0,CTILDE,AT(z), jtunquote1,jtunquote, nm,0L,0L, (z->flag&VASGSAFE)+(VJTFLGOK1|VJTFLGOK2), FAV(z)->mr,lrv(FAV(z)),rrv(FAV(z))));// create reference
FAV(z)->localuse.lu1.cachedref=sym-JT(jt,sympv); // convert symbol address back to index in case symbols are relocated
sym->flag|=LCACHED; // protect the value from changes. We do not chain back from the name
RETF(z);
}
// Result has type ':' but goes to unquote. We mark a pseudo-named entity by having f=0, g=name, h=actual entity to execute
F2(jtnamerefop){V*v;
ARGCHK2(a,w);
v=FAV(w);
R fdef(0,CCOLON,VERB, jtunquote1,jtunquote, 0L,a,w, VXOPCALL|v->flag, v->mr,lrv(v),rrv(v));
}
/* namerefop() is used by explicit defined operators when: */
// - debug is on or PM is on
/* - operator arguments have been supplied */
/* - function arguments have not yet been supplied */
// w is an anonymous entity that we want to give the name a to for debug purposes
// u./v.
// We process this as 'u'~ where the name is flagged as NMIMPLOC
// Bivalent: called with (a,w,self) or (w,self). We treat as dyad but turn it into monad if input w is not a noun
DF2(jtimplocref){
self=AT(w)&NOUN?self:w;
self=JT(jt,implocref)[FAV(self)->id&1];
w=AT(w)&NOUN?w:self;
R unquote(a,w,self); // call as (w,self,self) or (a,w,self)
}
| 79.973684
| 244
| 0.715614
|
97bc37939dcbf9a37f73ca6f62b5f9c05e8e608c
| 2,454
|
podspec
|
Ruby
|
Tempo_ios_sdk.podspec
|
jesusgeographica/pruebaSDK
|
329f6b27674137fda682cd1e974c2bb6b5901d99
|
[
"MIT"
] | null | null | null |
Tempo_ios_sdk.podspec
|
jesusgeographica/pruebaSDK
|
329f6b27674137fda682cd1e974c2bb6b5901d99
|
[
"MIT"
] | null | null | null |
Tempo_ios_sdk.podspec
|
jesusgeographica/pruebaSDK
|
329f6b27674137fda682cd1e974c2bb6b5901d99
|
[
"MIT"
] | null | null | null |
#
# Be sure to run `pod lib lint Tempo_ios_sdk.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'Tempo_ios_sdk'
s.version = '0.1.2'
s.summary = 'iOS library for indoor mapping.'
s.description = 'iOS library for indoor mapping using GeoJSON.'
s.homepage = 'https://github.com/GeographicaGS'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Javier Aragón' => 'javier.aragon@geographica.gs',
'Jesús Victorio' => 'jesus.victorio@geographica.gs', }
s.source = { :git => 'git@github.com:jesusgeographica/pruebaSDK.git'}
s.ios.deployment_target = '10.0'
s.swift_version = '4.2'
s.source_files = 'Tempo_ios_sdk/src/**/*.{swift,h,m,xcdatamodeld,xcdatamodel}', 'Tempo_ios_sdk/src/Data/DB/Model.xcdatamodeld/*.xcdatamodel'
s.resources = "Tempo_ios_sdk/src/**/*.{xib,zip,png,xcdatamodeld,xcdatamodel,ttf}", 'Tempo_ios_sdk/src/Data/DB/Model.xcdatamodeld/*.xcdatamodel'
s.resource_bundles = {
'FloorView' => [
'Tempo_ios_sdk/**/*.xib'
],
'MapContentViewController' => [
'Tempo_ios_sdk/**/*.xib'
],
'HeaderCollectionFloorView' => [
'Tempo_ios_sdk/**/*.xib'
]
}
s.requires_arc = true
s.libraries = 'z', 'c++'
s.frameworks = 'Foundation', 'UIKit', 'GLKit', 'CoreData', 'CartoMobileSDK'
s.ios.vendored_frameworks = 'Tempo_ios_sdk/Frameworks/CartoMobileSDK.framework'
s.preserve_path = 'Tempo_ios_sdk/Frameworks/*', 'Tempo_ios_sdk/src/Data/DB/Model.xcdatamodeld'
s.dependency 'AlamofireObjectMapper', '~> 5.2'
s.dependency 'SwiftyJWT', '~> 0.0.3'
s.dependency 'SSZipArchive', '~> 2.1'
s.dependency 'BottomPopup', '~> 0.4'
s.prepare_command = <<-CMD
echo "Downloading CartoMobileSDK, please wait..."
curl --progress-bar "https://nutifront.s3.amazonaws.com/sdk_snapshots/sdk4-ios-build-4.1.4.zip" --output CartoMobileSDK.zip
unzip CartoMobileSDK.zip
rm CartoMobileSDK.zip
cp -r CartoMobileSDK.framework/* Tempo_ios_sdk/Frameworks/CartoMobileSDK.framework
rm -r CartoMobileSDK.framework
CMD
end
| 42.310345
| 150
| 0.627547
|
7dc0c8862bb6a33c24059bab1a8bb9c9fdbca4fc
| 1,760
|
rs
|
Rust
|
pallets/rewards/src/tests.rs
|
agustinustheo/debio-node
|
39a20b262b783f8e50f74faf72be033869a72287
|
[
"Unlicense"
] | null | null | null |
pallets/rewards/src/tests.rs
|
agustinustheo/debio-node
|
39a20b262b783f8e50f74faf72be033869a72287
|
[
"Unlicense"
] | null | null | null |
pallets/rewards/src/tests.rs
|
agustinustheo/debio-node
|
39a20b262b783f8e50f74faf72be033869a72287
|
[
"Unlicense"
] | null | null | null |
use crate::{mock::*, Error, PalletAccount, RewarderKey};
use frame_support::{assert_noop, assert_ok};
use frame_system::RawOrigin;
#[test]
fn reward_funds_works() {
ExternalityBuilder::build().execute_with(|| {
System::set_block_number(1);
assert_eq!(RewarderKey::<Test>::put(1), ());
assert_ok!(Balances::set_balance(
RawOrigin::Root.into(),
PalletAccount::<Test>::get(),
100,
0
));
assert_ok!(Rewards::reward_funds(Origin::signed(1), 2, 10));
System::assert_last_event(Event::Rewards(crate::Event::RewardFunds(2, 10, 1)));
assert_eq!(Balances::free_balance(PalletAccount::<Test>::get()), 90);
})
}
#[test]
fn reward_funds_bad_signature() {
ExternalityBuilder::build().execute_with(|| {
System::set_block_number(1);
assert_eq!(RewarderKey::<Test>::put(1), ());
assert_ok!(Balances::set_balance(
RawOrigin::Root.into(),
PalletAccount::<Test>::get(),
1,
0
));
assert_noop!(Rewards::reward_funds(Origin::signed(1), 2, 2), Error::<Test>::BadSignature);
})
}
#[test]
fn cant_reward_funds_when_not_admin() {
ExternalityBuilder::build().execute_with(|| {
System::set_block_number(1);
assert_eq!(RewarderKey::<Test>::put(1), ());
assert_noop!(Rewards::reward_funds(Origin::signed(2), 2, 1), Error::<Test>::Unauthorized);
})
}
#[test]
fn update_admin_key_works() {
ExternalityBuilder::build().execute_with(|| {
RewarderKey::<Test>::put(2);
assert_eq!(Rewards::admin_key(), 2);
assert_ok!(Rewards::update_admin_key(Origin::signed(2), 1,));
assert_eq!(Rewards::admin_key(), 1);
})
}
#[test]
fn sudo_update_admin_key_works() {
ExternalityBuilder::build().execute_with(|| {
assert_ok!(Rewards::sudo_update_admin_key(Origin::root(), 1));
assert_eq!(Rewards::admin_key(), 1);
})
}
| 23.466667
| 92
| 0.680682
|
0daac0f20f1ac557afee08fd5bb3eac9a745fb02
| 2,235
|
cs
|
C#
|
EXAMS/2016.05.22/Problem-1-LimitedMemory/LimitedMemory/LimitedMemoryCollection.cs
|
mayapeneva/Data-Structures
|
36ab58d89030353742ef8328f94284075a84dda4
|
[
"MIT"
] | null | null | null |
EXAMS/2016.05.22/Problem-1-LimitedMemory/LimitedMemory/LimitedMemoryCollection.cs
|
mayapeneva/Data-Structures
|
36ab58d89030353742ef8328f94284075a84dda4
|
[
"MIT"
] | null | null | null |
EXAMS/2016.05.22/Problem-1-LimitedMemory/LimitedMemory/LimitedMemoryCollection.cs
|
mayapeneva/Data-Structures
|
36ab58d89030353742ef8328f94284075a84dda4
|
[
"MIT"
] | null | null | null |
using System.Collections;
using System.Collections.Generic;
namespace LimitedMemory
{
public class LimitedMemoryCollection<TK, TV> : ILimitedMemoryCollection<TK, TV>
{
private readonly LinkedList<Pair<TK, TV>> priorityCollection;
private readonly Dictionary<TK, LinkedListNode<Pair<TK, TV>>> collection;
public LimitedMemoryCollection(int capacity)
{
this.Capacity = capacity;
this.priorityCollection = new LinkedList<Pair<TK, TV>>();
this.collection = new Dictionary<TK, LinkedListNode<Pair<TK, TV>>>();
}
public int Capacity { get; }
public int Count => this.collection.Count;
public void Set(TK key, TV value)
{
if (this.collection.ContainsKey(key))
{
var pair = this.collection[key];
this.priorityCollection.Remove(pair);
pair.Value.Value = value;
this.priorityCollection.AddFirst(pair);
}
else
{
if (this.Count >= this.Capacity)
{
var pairToRemove = this.priorityCollection.Last;
this.collection.Remove(pairToRemove.Value.Key);
this.priorityCollection.RemoveLast();
}
var newPair = new LinkedListNode<Pair<TK, TV>>(new Pair<TK, TV>(key, value));
this.collection.Add(key, newPair);
this.priorityCollection.AddFirst(newPair);
}
}
public TV Get(TK key)
{
if (!this.collection.ContainsKey(key))
{
throw new KeyNotFoundException();
}
var pair = this.collection[key];
this.priorityCollection.Remove(pair);
this.priorityCollection.AddFirst(pair);
return pair.Value.Value;
}
public IEnumerator<Pair<TK, TV>> GetEnumerator()
{
foreach (var kvp in this.priorityCollection)
{
yield return kvp;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
| 31.041667
| 93
| 0.54094
|
bb29783b46739dedc70a73751c083e696b2e4ebb
| 1,317
|
cs
|
C#
|
src/System.Private.ServiceModel/src/System/ServiceModel/AuditLogLocation.cs
|
richamo/wcf
|
c0dd90a124d8d91ed07568bb9ab03f23aecf7597
|
[
"MIT"
] | 1,794
|
2015-05-20T11:18:59.000Z
|
2022-03-28T11:57:09.000Z
|
src/System.Private.ServiceModel/src/System/ServiceModel/AuditLogLocation.cs
|
richamo/wcf
|
c0dd90a124d8d91ed07568bb9ab03f23aecf7597
|
[
"MIT"
] | 3,867
|
2015-05-20T11:41:26.000Z
|
2022-03-31T21:38:37.000Z
|
src/System.Private.ServiceModel/src/System/ServiceModel/AuditLogLocation.cs
|
richamo/wcf
|
c0dd90a124d8d91ed07568bb9ab03f23aecf7597
|
[
"MIT"
] | 661
|
2015-05-20T11:18:35.000Z
|
2022-03-10T07:11:45.000Z
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ServiceModel.Security;
using System.ComponentModel;
namespace System.ServiceModel
{
public enum AuditLogLocation
{
Default,
Application,
Security,
}
internal static class AuditLogLocationHelper
{
public static bool IsDefined(AuditLogLocation auditLogLocation)
{
if (auditLogLocation == AuditLogLocation.Security && !SecurityAuditHelper.IsSecurityAuditSupported)
{
throw ExceptionHelper.PlatformNotSupported(SR.SecurityAuditPlatformNotSupported);
}
return auditLogLocation == AuditLogLocation.Default
|| auditLogLocation == AuditLogLocation.Application
|| auditLogLocation == AuditLogLocation.Security;
}
public static void Validate(AuditLogLocation value)
{
if (!IsDefined(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("value", (int)value,
typeof(AuditLogLocation)));
}
}
}
}
| 31.357143
| 127
| 0.651481
|
7d264dcb2b4d5faa72cd7974bd82a53ddd0a9bd1
| 2,721
|
rs
|
Rust
|
src/expression/utils.rs
|
Trouv/imex
|
8e1cb9cfddb942232012a6bea3bb34c3e0986d33
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
src/expression/utils.rs
|
Trouv/imex
|
8e1cb9cfddb942232012a6bea3bb34c3e0986d33
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
src/expression/utils.rs
|
Trouv/imex
|
8e1cb9cfddb942232012a6bea3bb34c3e0986d33
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
use crate::IMExIterator;
/// An IMExIterator that keeps track of how many times it has iterated with some result.
/// Used by QuantifiedIMExVal to keep track of inner IMExVal iterations.
#[derive(PartialEq, Debug, Clone)]
pub struct IMExIterCounter<X: IMExIterator> {
imex_iter: X,
counter: u32,
}
impl<X: IMExIterator> IMExIterator for IMExIterCounter<X> {
fn iterate<T, I>(&mut self, iters: &mut Vec<T>) -> Option<I>
where
T: Iterator<Item = I>,
{
match self.imex_iter.iterate(iters) {
Some(res) => {
self.counter += 1;
Some(res)
}
None => None,
}
}
}
impl<X: IMExIterator> IMExIterCounter<X> {
/// Construct a new IMExIterCounter from any IMExIterator
pub fn new(imex_iter: X) -> IMExIterCounter<X> {
IMExIterCounter {
imex_iter,
counter: 0,
}
}
/// Get the current number of times that this IMExIterCounter was iterated with some result.
pub fn count(&self) -> u32 {
self.counter
}
}
use nom::{error::VerboseError, IResult};
/// Trait for implementing parser-combinator-style parse functions
pub trait ParserCombinator {
/// Defines how an object is parsed from a string.
///
/// Returns a nom::IResult containing the Self that was parsed and the remainder of the input
/// string that wasn't parsed.
fn parse(input: &str) -> IResult<&str, Self, VerboseError<&str>>
where
Self: std::marker::Sized;
}
#[cfg(test)]
mod iter_counter_tests {
use super::super::IMEx;
use super::*;
use std::{convert::TryFrom, io::Result};
#[test]
fn iter_counter_counts_iterations() -> Result<()> {
let mut iter_counter = IMExIterCounter::new(IMEx::try_from("0*")?);
let mut iters = vec!["123".chars()];
assert_eq!(iter_counter.count(), 0);
iter_counter.iterate(&mut iters);
assert_eq!(iter_counter.count(), 1);
iter_counter.iterate(&mut iters);
assert_eq!(iter_counter.count(), 2);
iter_counter.iterate(&mut iters);
assert_eq!(iter_counter.count(), 3);
iter_counter.iterate(&mut iters);
assert_eq!(iter_counter.count(), 3);
Ok(())
}
#[test]
fn iter_counter_wont_count_past_zero_on_empty_imex() -> Result<()> {
let mut iter_counter = IMExIterCounter::new(IMEx::try_from("")?);
let mut iters = vec!["123".chars()];
assert_eq!(iter_counter.count(), 0);
iter_counter.iterate(&mut iters);
assert_eq!(iter_counter.count(), 0);
iter_counter.iterate(&mut iters);
assert_eq!(iter_counter.count(), 0);
Ok(())
}
}
| 27.765306
| 97
| 0.608967
|
aa8aa0ffdd37365405f647ff65cc69c27bf9185f
| 931
|
dart
|
Dart
|
tests/language_2/const/constructor3_test.dart
|
lfkdsk/sdk
|
07aa9ec332600b585b0edc8d3805fb413e4370bd
|
[
"BSD-3-Clause"
] | null | null | null |
tests/language_2/const/constructor3_test.dart
|
lfkdsk/sdk
|
07aa9ec332600b585b0edc8d3805fb413e4370bd
|
[
"BSD-3-Clause"
] | null | null | null |
tests/language_2/const/constructor3_test.dart
|
lfkdsk/sdk
|
07aa9ec332600b585b0edc8d3805fb413e4370bd
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
class C {
final double d;
const C(this.d);
}
class D extends C {
const D(var d) : super(d);
}
const intValue = 0;
const c = const C(0.0);
const d = const C(intValue);
// ^^^^^^^^
// [analyzer] CHECKED_MODE_COMPILE_TIME_ERROR.CONST_CONSTRUCTOR_PARAM_TYPE_MISMATCH
// [cfe] The argument type 'int' can't be assigned to the parameter type 'double'.
// ^^^^^^^^
// [analyzer] COMPILE_TIME_ERROR.ARGUMENT_TYPE_NOT_ASSIGNABLE
const e = const D(0.0);
const f = const D(intValue);
// ^^^^^^^^^^^^^^^^^
// [analyzer] COMPILE_TIME_ERROR.CONST_EVAL_THROWS_EXCEPTION
// ^
// [cfe] Constant evaluation error:
main() {
print(c);
print(d);
print(e);
print(f);
}
| 26.6
| 83
| 0.643394
|
20b828b7c092234873dbfa35a11bee93ea5bcd17
| 3,513
|
cs
|
C#
|
src/Lykke.Service.PayInvoice.Core/Domain/HistoryItem.cs
|
NovichikhinAlexey/Lykke.Service.PayInvoice
|
c73d1cd4bf9949d74c07cf5f450d64f2cd971b2f
|
[
"MIT"
] | null | null | null |
src/Lykke.Service.PayInvoice.Core/Domain/HistoryItem.cs
|
NovichikhinAlexey/Lykke.Service.PayInvoice
|
c73d1cd4bf9949d74c07cf5f450d64f2cd971b2f
|
[
"MIT"
] | null | null | null |
src/Lykke.Service.PayInvoice.Core/Domain/HistoryItem.cs
|
NovichikhinAlexey/Lykke.Service.PayInvoice
|
c73d1cd4bf9949d74c07cf5f450d64f2cd971b2f
|
[
"MIT"
] | 1
|
2019-12-03T20:53:41.000Z
|
2019-12-03T20:53:41.000Z
|
using System;
using System.Collections.Generic;
namespace Lykke.Service.PayInvoice.Core.Domain
{
/// <summary>
/// Represents an invoice state.
/// </summary>
public class HistoryItem
{
/// <summary>
/// The unique identified of state.
/// </summary>
public string Id { get; set; }
/// <summary>
/// The related invoice id.
/// </summary>
public string InvoiceId { get; set; }
/// <summary>
/// The payment request id.
/// </summary>
public string PaymentRequestId { get; set; }
/// <summary>
/// The invoice number which provided when it created.
/// </summary>
public string Number { get; set; }
/// <summary>
/// The client name.
/// </summary>
public string ClientName { get; set; }
/// <summary>
/// The client email address.
/// </summary>
public string ClientEmail { get; set; }
/// <summary>
/// The invoice status.
/// </summary>
public InvoiceStatus Status { get; set; }
/// <summary>
/// The invoice payment amount.
/// </summary>
public decimal PaymentAmount { get; set; }
/// <summary>
/// The invoice settlement amount.
/// </summary>
public decimal SettlementAmount { get; set; }
/// <summary>
/// The invoice paid amount.
/// </summary>
public decimal PaidAmount { get; set; }
/// <summary>
/// The payment asset id.
/// </summary>
public string PaymentAssetId { get; set; }
/// <summary>
/// The settlement asset id.
/// </summary>
public string SettlementAssetId { get; set; }
/// <summary>
/// The payment request order exchange rate.
/// </summary>
public decimal ExchangeRate { get; set; }
/// <summary>
/// The destination wallet address.
/// </summary>
public string WalletAddress { get; set; }
/// <summary>
/// A collection of source wallet address.
/// </summary>
public List<string> SourceWalletAddresses { get; set; }
/// <summary>
/// The wallet address for refund.
/// </summary>
public string RefundWalletAddress { get; set; }
/// <summary>
/// The refund amount.
/// </summary>
public decimal RefundAmount { get; set; }
/// <summary>
/// The invoice due date in UTC.
/// </summary>
public DateTime DueDate { get; set; }
/// <summary>
/// The invoice paid date in UTC.
/// </summary>
public DateTime? PaidDate { get; set; }
/// <summary>
/// The employee id that was changed invoice or <c>null</c> if invoice was changed by payment system.
/// </summary>
public string ModifiedById { get; set; }
/// <summary>
/// The reason for changes.
/// </summary>
public string Reason { get; set; }
/// <summary>
/// The changes date.
/// </summary>
public DateTime Date { get; set; }
/// <summary>
/// The Billing Category
/// </summary>
public string BillingCategory { get; set; }
/// <summary>
/// The dispute attribute
/// </summary>
public bool Dispute { get; set; }
}
}
| 26.613636
| 109
| 0.506974
|
9970bdf765a4e1e6b6d39643d10f92de103f39ba
| 1,700
|
swift
|
Swift
|
Package.swift
|
HackingGate/CrunchyrollSwift
|
6a8c20ea1ecabb6c9b8c5ec49316c8250f40bb1e
|
[
"MIT"
] | 3
|
2020-08-16T12:05:38.000Z
|
2021-01-02T02:42:09.000Z
|
Package.swift
|
HackingGate/CrunchyrollSwift
|
6a8c20ea1ecabb6c9b8c5ec49316c8250f40bb1e
|
[
"MIT"
] | 2
|
2020-12-27T13:41:44.000Z
|
2021-08-25T05:06:11.000Z
|
Package.swift
|
HackingGate/CrunchyrollSwift
|
6a8c20ea1ecabb6c9b8c5ec49316c8250f40bb1e
|
[
"MIT"
] | null | null | null |
// swift-tools-version:5.2
import PackageDescription
let package = Package(
name: "CrunchyrollSwift",
platforms: [
.iOS(.v11),
.macOS(.v10_13),
.tvOS(.v11),
.watchOS(.v4)
],
products: [
.library(
name: "CrunchyrollSwift",
targets: ["CrunchyrollSwift"]),
.library(
name: "CrunchyrollSwiftWeb",
targets: ["CrunchyrollSwiftWeb"]),
.executable(
name: "crunchyrollswift-dl",
targets: ["CrunchyrollSwift-DL"])
],
dependencies: [
.package(
url: "https://github.com/tid-kijyun/Kanna",
from: "5.2.7"),
.package(
url: "https://github.com/apple/swift-argument-parser",
from: "0.4.4"),
.package(
url: "https://github.com/pvieito/PythonKit.git",
.branch("master"))
],
targets: [
.target(
name: "CrunchyrollSwift",
dependencies: [],
path: "Sources/CrunchyrollSwift"),
.target(
name: "CrunchyrollSwiftWeb",
dependencies: ["Kanna"],
path: "Sources/CrunchyrollSwiftWeb"),
.target(
name: "CrunchyrollSwift-DL",
dependencies: [
.product(
name: "ArgumentParser",
package: "swift-argument-parser"),
"CrunchyrollSwift",
"CrunchyrollSwiftWeb",
"PythonKit"
],
path: "Sources/CrunchyrollSwift-DL"),
.testTarget(
name: "CrunchyrollSwiftTests",
dependencies: ["CrunchyrollSwift"])
]
)
| 28.333333
| 66
| 0.491176
|
8e7116d6099f5299956483adc52084bb054580f5
| 8,602
|
js
|
JavaScript
|
public/js/controllers/manageCatalogCtrl.js
|
Yichang812/Catalog-Browser
|
297876fe61746edf97421ccbbef28dc9094eed7b
|
[
"Unlicense",
"MIT"
] | null | null | null |
public/js/controllers/manageCatalogCtrl.js
|
Yichang812/Catalog-Browser
|
297876fe61746edf97421ccbbef28dc9094eed7b
|
[
"Unlicense",
"MIT"
] | null | null | null |
public/js/controllers/manageCatalogCtrl.js
|
Yichang812/Catalog-Browser
|
297876fe61746edf97421ccbbef28dc9094eed7b
|
[
"Unlicense",
"MIT"
] | null | null | null |
'use strict';
angular.module('ace.catalog').controller(
'manageCatalogCtrl', ['$scope', 'Global', 'CatalogAPI', '_' ,'$modal', '$rootScope', function ($scope, Global, CatalogAPI, underscore, $modal, $rootScope) {
$scope.global = Global;
$scope.fields = [];
$scope._ = underscore;
$scope.pageItemLimit = 15;
$scope.searchMode = false;
$scope.lower = 0;
$scope.upper = $scope.lower + $scope.pageItemLimit;
$scope.sort = null;
$scope.sort = null;
$scope.defaultFilters = [
'Catalog',
'Assembly Code',
'Description'
];
$scope.filters = [];
$scope.searchText = {};
$scope.typeAheadValues = [];
$scope.fields = [];
$scope.cols = [
{
title: 'Catalog',
field: 'catalog',
sort: null
},
{
title: 'Manufacturer',
field: 'manufacturer',
sort: null
},
{
title: 'Assembly Code',
field: 'assemblyCode',
sort: null
}
];
$rootScope.tab1 = true;
$rootScope.tab2 = false;
$scope.authorized = function() {
if($scope.global.authenticated && ($scope.global.user.isAdmin || $scope.global.user.isManufacturer))
return true;
return false;
};
$scope.manufacturer = $scope.authorized()?($scope.global.user.isAdmin?null:$scope.global.user.codeName):null;
$scope.showConfigureModal = function () {
$modal.open({
templateUrl: 'views/Catalog/configureTableModal.html',
controller: 'configureTableModalCtrl',
resolve: {
data: function () {
return {
fields: $scope.fields,
cols: $scope.cols,
toggleField: $scope.toggleField,
toggleAll: $scope.toggleAll
};
}
}
});
};
$scope.showFilterModal = function () {
$modal.open({
templateUrl: 'views/Catalog/filterModal.html',
controller: 'filterModalCtrl',
resolve: {
data: function () {
return {
filters: $scope.filters,
type: $scope.selected,
search: $scope.searchText
};
}
}
});
};
$scope.init = function() {
$scope.showTypes = true;
CatalogAPI.types.query(function(response){
if(response) {
$scope.types = response;
$scope.target = $scope.types.length? $scope.types[0]: null;
}
});
$scope.showList = false;
var current_url = document.URL;
if (current_url.indexOf('code') > -1) {
$rootScope.tab1 = false;
$rootScope.tab2 = true;
$rootScope.uploadOpt = 'fromBox';
$rootScope.boxLoginStatus = true;
}
if (current_url.indexOf('error') > -1) {
$rootScope.tab1 = false;
$rootScope.tab2 = true;
$rootScope.uploadOpt = 'fromBox';
$rootScope.boxLoginStatus = false;
}
};
$scope.addFilter = function (f) {
for (var i in $scope.filters)
if ($scope.filters[i].field === f)
return;
$scope.filters.push({
'field': f,
'value': ''
});
};
$scope.removeFilter = function (f) {
if ($scope.filters.indexOf(f) !== -1)
$scope.filters.splice(f, 1);
};
$scope.showTypeList = function(){
var type = $scope.target;
if (!type) {return;}
$scope.showList = true;
$scope.showTypes = false;
function parseCamelCase(input)
{
return input.charAt(0).toUpperCase() + input.substr(1).replace(/[A-Z0-9]/g, ' $&');
}
$scope.fields = [];
$scope.cols = [{title: 'Catalog', field: 'catalog', sort: null},{title: 'Manufacturer', field: 'manufacturer', sort: null},{title: 'Assembly Code', field: 'assemblyCode', sort: null}];
CatalogAPI.fields.query({type: type.code}, function(response) {
if(response)
{
for (var i = 0; i < response.length; i++) {
var field = $scope._.values(response[i]).join('');
var displayed_field = field;
if(displayed_field.indexOf('additionalInfo') > -1)
{
displayed_field = displayed_field.replace('additionalInfo.', '');
displayed_field = displayed_field.replace('_', ' ');
displayed_field = parseCamelCase(displayed_field);
$scope.fields.push({title: displayed_field, field: field, sort: null});
}
}
}
});
$scope.currentPage = 1;
$scope.getPage(1, true);
};
$scope.processFilters = function (filters) {
if (!filters)
return null;
var newObj = {};
var non_additional = ['Catalog', 'Manufacturer', 'Assembly Code'];
for (var i = 0; i < filters.length; i++) {
var filter = filters[i];
if(!filter.value)
continue;
if(non_additional.indexOf(filter.field) > -1)
newObj[filter.field[0].toLowerCase()+filter.field.substring(1).replace(' ', '')] = filter.value;
else
newObj['additionalInfo.'+filter.field.toLowerCase().replace(' ','')] = filter.value;
}
return newObj;
};
function queryForEntries(fields, cb) {
CatalogAPI.entries.query({
type: $scope.target.code,
lower: $scope.lower,
sortField: $scope.sort,
upper: $scope.upper,
fields: fields,
manufacturer: $scope.manufacturer,
search: $scope.prepareSearchString($scope.searchText.value),
filters: $scope.processFilters($scope.filters)
}, function (response) {
cb(response);
});
}
$scope.toggleField = function(field){
if ($scope.cols.indexOf(field) === -1) {
$scope.cols.push(field);
if($scope.searchText || $scope.filters.length > 0)
{
$scope.getPage(1, true);
return;
}
$scope.getPage($scope.currentPage, true);
} else {
$scope.cols.splice($scope.cols.indexOf(field), 1);
}
};
$scope.getPage = function (page, totalFlag) {
$scope.lower = (page ? page - 1 : 0) * $scope.pageItemLimit;
$scope.upper = (page ? page : 1) * $scope.pageItemLimit;
var cols = $scope._.map($scope.cols, function (value) {
return value.field;
});
queryForEntries(cols.join(' '), function (response) {
$scope.items = $scope._.map(response.data, function (value) {
return $scope._.omit(value, [
'additionalInfo',
'__v'
]);
});
if ($scope.fields.length > 0) {
for (var i = 0; i < $scope.fields.length; i++) {
var field = $scope.fields[i];
for (var j = 0; j < $scope.items.length; j++) {
var newField = $scope._.findWhere(response.data, { _id: $scope.items[j]._id });
if (newField && newField.additionalInfo)
$scope.items[j][field.field] = newField.additionalInfo[field.field.replace('additionalInfo.', '')];
else
$scope.items[j][field.field] = '';
}
}
}
if(page === 1 && totalFlag)
{
if (response.data.length === $scope.pageItemLimit) {
CatalogAPI.entries.query({
type: $scope.target.code,
search: $scope.prepareSearchString($scope.searchText.value),
total: true,
manufacturer: $scope.manufacturer,
fields: cols.join(' '),
filters: $scope.processFilters($scope.filters)
}, function (response) {
if (response) {
$scope.total = response.count;
}
});
} else
$scope.total = response.data.length;
}
});
};
$scope.sortedValues = function(data) {
var cols = $scope._.map($scope.cols, function(value) {return value.field;});
var val_array = new Array(cols.length+1).join('-').split('');
for(var key in data)
{
var index = cols.indexOf(key);
if(index > -1)
{
if(data[key])
{
val_array[index] = data[key];
}
}
}
return val_array;
};
$scope.prepareSearchString = function (copy) {
return copy;
};
$scope.toggleAll = function() {
if(($scope.fields.length+3) !== $scope.cols.length)
{
for (var i = 0; i < $scope.fields.length; i++) {
var field = $scope.fields[i];
if($scope.cols.indexOf(field) === -1)
$scope.toggleField(field);
}
return;
}
for (var j = 0; j < $scope.fields.length; j++) {
var remove_field = $scope.fields[j];
$scope.cols.splice($scope.cols.indexOf(remove_field),1);
}
};
$scope.sortTable = function(col) {
var order = col.sort;
for (var i = 0; i < $scope.cols.length; i++) {
$scope.cols[i].sort = null;
}
col.sort = (order === 1)? -1: 1;
$scope.sort = col;
$scope.getPage($scope.currentPage? $scope.currentPage: 1);
};
$scope.showComingModal = function(){
$modal.open({
templateUrl: 'views/ComingModal.html',
controller: 'ComingModalCtrl',
});
};
$scope.showEditItemModal = function(item){
var modalInstance = $modal.open({
templateUrl: 'views/Catalog/editItemForm.html',
controller: 'editItemFormCtrl',
resolve:{
item: function() {
return (item);
}
}
});
modalInstance.result.then(function(){
$scope.showTypeList();
});
};
}]);
| 26.965517
| 187
| 0.596954
|
0d8cf081ea2bc1df946ed38fa1ebe1648a242583
| 172
|
cs
|
C#
|
packages/implementations/OneLang-Core-v0.1/CSharp/src/Array.cs
|
onelang/onelang
|
76a968978e3014e475d0983411d32fd99aa491d3
|
[
"MIT"
] | 267
|
2019-12-28T18:29:38.000Z
|
2022-03-30T16:54:02.000Z
|
packages/implementations/OneLang-Core-v0.1/CSharp/src/Array.cs
|
00mjk/OneLang
|
0e6627bced4426a34d560159326b31f41f8a74ac
|
[
"MIT"
] | 4
|
2020-02-16T11:12:15.000Z
|
2021-12-21T00:16:57.000Z
|
packages/implementations/OneLang-Core-v0.1/CSharp/src/Array.cs
|
00mjk/OneLang
|
0e6627bced4426a34d560159326b31f41f8a74ac
|
[
"MIT"
] | 40
|
2020-03-10T10:15:24.000Z
|
2022-02-22T03:48:36.000Z
|
using System.Collections.Generic;
using System.Linq;
public static class Array {
public static T[] from<T>(IEnumerable<T> obj) {
return obj.ToArray();
}
}
| 19.111111
| 51
| 0.668605
|
ef44fddf32760cfa4c44c6b763cdfa61c1f7b38b
| 235
|
rs
|
Rust
|
repo/src/connect.rs
|
songxuexian/meta
|
235ec01d4ef5723fc999aa0ebf0a5ab5db89a2ed
|
[
"Apache-2.0"
] | null | null | null |
repo/src/connect.rs
|
songxuexian/meta
|
235ec01d4ef5723fc999aa0ebf0a5ab5db89a2ed
|
[
"Apache-2.0"
] | null | null | null |
repo/src/connect.rs
|
songxuexian/meta
|
235ec01d4ef5723fc999aa0ebf0a5ab5db89a2ed
|
[
"Apache-2.0"
] | null | null | null |
use rbatis::rbatis::Rbatis;
pub async fn connect_db() -> Rbatis {
let rb = Rbatis::new();
rb.link("mysql://bytom_dev:Bytom!Dev@rm-uf6k0307eqv8pb7hd1o.mysql.rds.aliyuncs.com:3306/blockcenter_bytom2.0").await.unwrap();
rb
}
| 29.375
| 130
| 0.702128
|
dbc5edfe00a2bfbbec995f780f4d0d53f2955fea
| 378
|
php
|
PHP
|
production/admin/hapus_ajar.php
|
mariocahyo821/absensiqrcode
|
9cb52947eb59654b3f05abd5d2c07eabba2b5c0c
|
[
"MIT"
] | null | null | null |
production/admin/hapus_ajar.php
|
mariocahyo821/absensiqrcode
|
9cb52947eb59654b3f05abd5d2c07eabba2b5c0c
|
[
"MIT"
] | null | null | null |
production/admin/hapus_ajar.php
|
mariocahyo821/absensiqrcode
|
9cb52947eb59654b3f05abd5d2c07eabba2b5c0c
|
[
"MIT"
] | null | null | null |
<?php
require 'function.php';
$id_ajar = $_GET["id_ajar"];
if (hapus_ajar ($id_ajar) > 0) {
echo "<script>
alert('Data Berhasil diHapus');
document.location.href = 'ajar.php';
</script>";
} else {
echo "<script>
alert('Data Gagal diHapus');
document.location.href = 'ajar.php';
</script>";
}
?>
| 19.894737
| 48
| 0.513228
|
3f3dfafb4c382217bf6ebb867185b91b4ea34aa5
| 9,204
|
ctp
|
PHP
|
app/View/DeshBoard/bulk_salse.ctp
|
testVikran/nextstep
|
0f800f9933f8f351f7f234bf34ec7f55723f0ed3
|
[
"Apache-2.0"
] | null | null | null |
app/View/DeshBoard/bulk_salse.ctp
|
testVikran/nextstep
|
0f800f9933f8f351f7f234bf34ec7f55723f0ed3
|
[
"Apache-2.0"
] | null | null | null |
app/View/DeshBoard/bulk_salse.ctp
|
testVikran/nextstep
|
0f800f9933f8f351f7f234bf34ec7f55723f0ed3
|
[
"Apache-2.0"
] | null | null | null |
<script type="text/javascript" src="<?php echo ABSOLUTE_URL;?>/js/jquery.min.js"></script>
<script type="text/javascript" src="<?php echo ABSOLUTE_URL;?>/js/moment.min.js"></script>
<script type="text/javascript" src="<?php echo ABSOLUTE_URL;?>/js/bootstrap-datetimepicker.min.js"></script>
<script type="text/javascript" src="<?php echo ABSOLUTE_URL;?>/js/jquery.validate.js"></script>
<link rel="stylesheet" href="<?php echo ABSOLUTE_URL;?>/css/bootstrap-datetimepicker.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.devbridge-autocomplete/1.2.26/jquery.autocomplete.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$('.selector').autocomplete({
source: '<?php echo ABSOLUTE_URL;?>/desh_board/seachAutoComplete',
select: function (event, ui) {
var id = this.id;
$("#" + id).val(ui.item.label); // display the selected text
SubmitAndDetails(ui.item.id, id);
}
});
});
</script>
<body>
<div class="container col-lg-12 well">
<div class="row">
<div class="clearfix"></div>
<div class="col-md-3 col-md-offset-5 margin-bottom-20"><h3 class="text-info" ><strong>sales</strong></h3></div>
<div class="clearfix"></div>
<div class=" border-2">
<div class="">
<form class="form-inline" action="javascript:void(0);" id="productForm">
<div class="row" id="formDiv">
<div class="form-group control-group controls col-sm-12 col-md-12 padding-right-15" id="productRow">
<div class="col-sm-2 col-md-2">
<label for="input1" class="control-label">Name of product</label>
</div>
<div class="col-sm-2 col-md-2">
<label for="input1" class="control-label">Quantity</label>
</div>
<div class="col-sm-2 col-md-2">
<label for="input1" class="control-label">Brand</label>
</div>
<div class="col-sm-2 col-md-2">
<label for="input1" class="control-label">Price</label>
</div>
<div class="col-sm-2 col-md-2">
<label for="input1" class="control-label">Discount</label>
</div>
<div class="col-sm-2 col-md-2">
<label for="input1" class="control-label">Totel</label>
</div>
</div>
<div class="clearfix"></div>
<div class="form-group control-group controls col-sm-12 col-md-12 " id="productRow">
<div class="col-sm-2" id="div<?php echo $newRow;?>name">
<input type="text" class="form-control selector required padding-right-0" title="Please Enter the name of product" value="" name="name<?php echo $newRow;?>" id="<?php echo $newRow;?>" >
</div>
<div class="col-sm-2" id="div<?php echo $newRow;?>quanity">
<input name="quanity<?php echo $newRow;?>" class="form-control padding-right-0" id="quanity<?php echo $newRow;?>" onchange="quantity(this.value,$('#<?php echo $newRow;?>').attr('id'));">
</div>
<div class="col-sm-2" id="div<?php echo $newRow;?>brand">
<input name="brand<?php echo $newRow;?>" readonly class=" form-control input-group-addon padding-right-0" id="brand<?php echo $newRow;?>">
</div>
<div class="col-sm-2" id="div<?php echo $newRow;?>price">
<input name="price<?php echo $newRow;?>" readonly class=" form-control input-group-addon padding-right-0" id="price<?php echo $newRow;?>">
</div>
<div class="col-sm-2" id="div<?php echo $newRow;?>discount">
<input name="discount<?php echo $newRow;?>" class=" form-control padding-right-0" id="discount<?php echo $newRow;?>" onchange="getDiscount(this.value,$('#<?php echo $newRow;?>').attr('id'));">
</div>
<div class="col-sm-2" id="div<?php echo $newRow;?>productGroup">
<input name="totel<?php echo $newRow;?>" readonly class=" form-control input-group-addon padding-right-0" id="totel<?php echo $newRow;?>">
</div>
</div>
<div class="clearfix"></div>
</div>
<div class="clearfix"></div>
<br />
<div class="form-group control-group controls col-sm-12">
</div>
</form>
</div>
</div>
<div class="clearfix"></div>
<div class="row pull-right margin-right-40">
<button type="submit" class="btn btn-default btn-lg" onclick="javascript:saleList();" >Submit</button>
</div>
<div class="row pull-left margin-left-40">
<button type="submit" class="btn btn-default btn-lg" onclick="javascript:resetForm();" >Reset</button>
</div>
</div>
</div>
</body>
<script type="text/javascript">
var row =0;
$(document).ready(function () {
product = [];
discount = [];
quant = [];
});
/*
* @Function : ajax post request to post the data to backend php code and get responce
* @param : array Form data
* @Return : successMessage as responce
* @Author : Vikrant Agrawal
* @creted on : 2016-08-27
*/
function SubmitAndDetails(val,id){
$.ajax({
type: "POST",
url: "<?php echo ABSOLUTE_URL;?>/desh_board/getProductDetails",
data: {productId : val},
success: function(result){
var data = $.trim(result);
if(data === 'There is no data for this product Please add first'){
//$( "#name"+ id).html(' ').addClass('has-error');
$( "#brand"+ id).attr('value','N/A');
$( "#price"+ id).attr('value','N/A');
$( "#div"+ id + "brand").removeClass('has-success').addClass('has-error');
$( "#div"+ id + "price").removeClass('has-success').addClass('has-error');
} else {
product[id] = JSON.parse(data);
window.txt = JSON.parse(data);
for (var index in txt) {
$( "#" +index + id).attr('value',txt[index]);
if($("#div"+id+"quanity").val()){
var totle = ($("#div"+id+"quanity").val())*txt['price'];
$( "#totel" + id).attr('value',totle);
} else {
$( "#totel" + id).attr('value',txt['price']);
}
$( "#div" + id +index).removeClass('has-error').addClass('has-success');
}
$.ajax({
type: "POST",
url: "<?php echo ABSOLUTE_URL;?>/desh_board/createRow",
data: {newrow : id},
success: function(data){
$('#formDiv').append(data);
}, error: function (request, status, error) {
alert("Something went wrong");
}
});
}
}, error: function (request, status, error) {
alert("Something went wrong");
}
});
}
function saleList(){
$.ajax({
type: "POST",
url: "<?php echo ABSOLUTE_URL;?>/desh_board/saleList",
data: $('#productForm').serialize(true),
success: function(data){
}, error: function (request, status, error) {
alert("Something went wrong");
}
});
}
function getDiscount(dis,id){
if(!$.trim(quant[id])){
quant[id] = 1;
}
var verifie = dis/quant[id];
if(verifie <= product[id]['max_discount']) {
var newVal = (product[id]['price']*quant[id]) - dis;
$( "#totel" + id).attr('value',newVal);
discount[id] = dis;
} else {
$( "#discount" + id).val(0);
alert("Discount not possible maximum discount per piece is =" + product[id]['max_discount']);
}
}
function quantity(val,id){
if(!$.trim(discount[id])){
discount[id] = 0;
}
if(val){
var totle = (val*product[id]['price'])-discount[id];
$( "#totel" + id).attr('value',totle);
quant[id] = val;
}
}
function resetForm(){
//$('#productForm')[0].reset();
$('#productForm').trigger("reset");
$('input[readonly]').val("");
$('div').removeClass('has-success');
}
</script>
| 46.720812
| 207
| 0.495763
|
4455bd06ae682dfc626ad7fc153b5eb489c47521
| 11,521
|
py
|
Python
|
bips/workflows/workflow5.py
|
FCP-INDI/BrainImagingPipelines
|
2b0da2b50814cc685f15fefbae8144624308ebfc
|
[
"Apache-2.0"
] | 1
|
2015-07-15T19:48:09.000Z
|
2015-07-15T19:48:09.000Z
|
bips/workflows/workflow5.py
|
FCP-INDI/BrainImagingPipelines
|
2b0da2b50814cc685f15fefbae8144624308ebfc
|
[
"Apache-2.0"
] | null | null | null |
bips/workflows/workflow5.py
|
FCP-INDI/BrainImagingPipelines
|
2b0da2b50814cc685f15fefbae8144624308ebfc
|
[
"Apache-2.0"
] | null | null | null |
import os
from ..utils.reportsink.io import ReportSink
from .base import MetaWorkflow, load_config, register_workflow
from scripts.u0a14c5b5899911e1bca80023dfa375f2.QA_utils import corr_image, vol2surf
from .scripts.u0a14c5b5899911e1bca80023dfa375f2.utils import pickfirst
"""
Part 1: Define a MetaWorkflow
"""
desc = """
Resting State correlation QA workflow
=====================================
This workflow outputs a PDF with surface corellation images preprocessed resting state data with the seed as the average timeseries of the left hemisphere precuneus.
Click_ for more documentation.
.. _Click: ../../interfaces/generated/bips.workflows.workflow5.html
"""
mwf = MetaWorkflow()
mwf.uuid = '62aff7328b0a11e1be5d001e4fb1404c'
mwf.tags = ['resting','fMRI','QA','correlation']
mwf.uses_outputs_of = ['7757e3168af611e1b9d5001e4fb1404c']
mwf.help = desc
"""
Part 2: Define the config class & create_config function
"""
from .workflow3 import config
def create_config():
c = config()
c.uuid = mwf.uuid
c.desc = mwf.help
return c
mwf.config_ui = create_config
"""
Part 3: Create a View
"""
def create_view():
from traitsui.api import View, Item, Group, CSVListEditor
from traitsui.menu import OKButton, CancelButton
view = View(Group(Item(name='uuid', style='readonly'),
Item(name='desc', style='readonly'),
label='Description', show_border=True),
Group(Item(name='working_dir'),
Item(name='sink_dir'),
Item(name='crash_dir'),
Item(name='json_sink'),
label='Directories', show_border=True),
Group(Item(name='run_using_plugin'),
Item(name='plugin', enabled_when="run_using_plugin"),
Item(name='plugin_args', enabled_when="run_using_plugin"),
Item(name='test_mode'),
label='Execution Options', show_border=True),
Group(Item(name='subjects', editor=CSVListEditor()),
label='Subjects', show_border=True),
Group(Item(name='preproc_config'),
label = 'Preprocessing Info'),
buttons = [OKButton, CancelButton],
resizable=True,
width=1050)
return view
mwf.config_view = create_view
"""
Part 4: Workflow Construction
"""
# Define Workflow
addtitle = lambda x: "Resting_State_Correlations_fwhm%s"%str(x)
def start_config_table(c):
"""Generated 2D list with configuration parameters
Parameters
----------
c: config object from workflow2_
.._workflow2: bips.workflows.workflow2
Outputs
-------
table : List
2D list with configuration parameters
"""
import numpy as np
param_names = np.asarray(['motion', 'composite norm', 'compcorr components','global_signal', 'outliers', 'motion derivatives'])
boolparams=np.asarray(c.reg_params)
params = param_names[boolparams]
table = []
table.append(['TR',str(c.TR)])
table.append(['Slice Order',str(c.SliceOrder)])
if c.use_fieldmap:
table.append(['Echo Spacing',str(c.echospacing)])
table.append(['Fieldmap Smoothing',str(c.sigma)])
table.append(['TE difference',str(c.TE_diff)])
table.append(['Art: norm thresh',str(c.norm_thresh)])
table.append(['Art: z thresh',str(c.z_thresh)])
table.append(['fwhm',str(c.fwhm)])
table.append(['highpass freq',str(c.highpass_freq)])
table.append(['lowpass freq',str(c.lowpass_freq)])
table.append(['Regressors',str(params)])
return [[table]]
def resting_datagrab(c,name="resting_datagrabber"):
"""Returns a datagrabber nipype node. The datagrabber looks for the following files:
* reg_file : bbregister file
* mean_image : mean image after motion correction
* mask : mask image
* func : functional output of preprocessing
.. admonition:: Warning
This function only works for directories with the directory structure from the output of workflow2_. Changing the directory structure will cause the datagrabber to fail
Parameters
----------
c : cofig object form workfow2_
Returns
-------
Datagrabber nipype node
.._workflow2: bips.workflows.workflow2.html
"""
import nipype.pipeline.engine as pe
import nipype.interfaces.io as nio
datasource = pe.Node(interface=nio.DataGrabber(infields=['subject_id',
'fwhm'],
outfields=['reg_file',
'mean_image',
"mask",
"func"]),
name = name)
datasource.inputs.base_directory = os.path.join(c.sink_dir)
datasource.inputs.sort_filelist = True
datasource.inputs.template ='*'
datasource.inputs.field_template = dict(reg_file='%s/preproc/bbreg/*.dat',
mean_image='%s/preproc/mean/*.nii.gz',
mask='%s/preproc/mask/*_brainmask.nii',
func="%s/preproc/output/fwhm_%s/*bandpassed.nii.gz")
datasource.inputs.template_args = dict(reg_file=[['subject_id']],
mean_image=[['subject_id']],
mask=[['subject_id']],
func=[['subject_id','fwhm']])
return datasource
from .workflow2 import create_config as prep_config
foo=prep_config()
def resting_QA(QA_c,c=foo, name="resting_QA"):
"""Returns resting-state quality assurance workflow.
Inputs
------
inputspec.in_files : preprocessed functional runs
inputspec.reg_file : bbregister file
inputspec.subjects_dir : Freesurfer SUBJECTS_DIR
inputspec.mean_image : Mean image after motion correction
Outputs
-------
QA PDF
Parameters
----------
QA_c : config object
c : config object from workflow2_
name : workflow name
Returns
-------
Nipype workflow object : resting state QA workflow
"""
import nipype.pipeline.engine as pe
import nipype.interfaces.utility as util
import nipype.interfaces.io as nio
workflow=pe.Workflow(name=name)
inputspec = pe.Node(interface=util.IdentityInterface(fields=["in_files",
"reg_file",
"subjects_dir",
"mean_image"]), name="inputspec")
infosource = pe.Node(util.IdentityInterface(fields=['subject_id']),
name='subject_names')
if QA_c.test_mode:
infosource.iterables = ('subject_id', [c.subjects[0]])
else:
infosource.iterables = ('subject_id', c.subjects)
fwhmsource = pe.Node(util.IdentityInterface(fields=['fwhm']),
name='fwhm_source')
fwhmsource.iterables = ('fwhm',c.fwhm)
dataflow = resting_datagrab(c)
workflow.connect(fwhmsource,'fwhm',dataflow,'fwhm')
workflow.connect(infosource,'subject_id',dataflow,'subject_id')
workflow.connect(dataflow,('func',pickfirst), inputspec,'in_files')
workflow.connect(dataflow,'reg_file', inputspec, 'reg_file')
workflow.inputs.inputspec.subjects_dir = c.surf_dir
workflow.connect(dataflow,'mean_image', inputspec,'mean_image')
tosurf = pe.MapNode(util.Function(input_names=['input_volume',
'ref_volume',
'reg_file',
'trg',
'hemi'],
output_names=["out_file"],
function=vol2surf), name='vol2surf',iterfield=["input_volume"])
tosurf.inputs.hemi = 'lh'
tosurf.inputs.trg = 'fsaverage5'
workflow.connect(inputspec,'in_files',tosurf,'input_volume')
workflow.connect(inputspec,'reg_file',tosurf,'reg_file')
workflow.connect(inputspec,'mean_image', tosurf,'ref_volume')
to_img = pe.MapNode(util.Function(input_names=['resting_image','fwhm'],
output_names=["corr_image",
"ims",
"roitable",
"histogram",
"corrmat_npz"],
function=corr_image),
name="image_gen",iterfield=["resting_image"])
workflow.connect(tosurf,'out_file',to_img,'resting_image')
workflow.connect(fwhmsource,'fwhm',to_img,'fwhm')
sink = pe.Node(ReportSink(orderfields=["Introduction",
"Subject",
"Configuration",
"Correlation_Images",
"Other_Views",
"ROI_Table",
"Histogram"]),
name="write_report")
sink.inputs.base_directory = os.path.join(QA_c.sink_dir)
sink.inputs.json_sink = QA_c.json_sink
sink.inputs.Introduction = "Resting state correlations with seed at precuneus"
sink.inputs.Configuration = start_config_table(c)
corrmat_sinker = pe.Node(nio.DataSink(),name='corrmat_sink')
corrmat_sinker.inputs.base_directory = QA_c.json_sink
def get_substitutions(subject_id):
subs = [('_fwhm_','fwhm'),('_subject_id_%s'%subject_id,'')]
for i in range(20):
subs.append(('_image_gen%d/corrmat.npz'%i,'corrmat%02d.npz'%i))
return subs
workflow.connect(infosource,('subject_id',get_substitutions),corrmat_sinker,'substitutions')
workflow.connect(infosource,'subject_id',corrmat_sinker,'container')
workflow.connect(to_img,'corrmat_npz',corrmat_sinker,'corrmats')
#sink.inputs.report_name = "Resting_State_Correlations"
workflow.connect(infosource,'subject_id',sink,'Subject')
workflow.connect(fwhmsource,('fwhm',addtitle),sink,'report_name')
workflow.connect(infosource,'subject_id',sink,'container')
workflow.connect(to_img,"corr_image",sink,"Correlation_Images")
workflow.connect(to_img,"ims",sink,"Other_Views")
workflow.connect(to_img,"roitable",sink,"ROI_Table")
workflow.connect(to_img,"histogram",sink,"Histogram")
return workflow
mwf.workflow_function = resting_QA
"""
Part 5: Define the main function
"""
# Define Main
def main(config):
"""Runs resting state QA workfow
Parameters
----------
config : String
Filename of .json configuration file
"""
QA_config = load_config(config,create_config)
c = load_config(QA_config.preproc_config, prep_config)
a = resting_QA(QA_config,c)
a.base_dir = QA_config.working_dir
if QA_config.test_mode:
a.write_graph()
a.config = {'execution' : {'crashdump_dir' : QA_config.crash_dir}}
if not os.environ['SUBJECTS_DIR'] == c.surf_dir:
print "Your SUBJECTS_DIR is incorrect!"
print "export SUBJECTS_DIR=%s"%c.surf_dir
else:
if QA_config.run_using_plugin:
a.run(plugin=QA_config.plugin,plugin_args=QA_config.plugin_args)
else:
a.run()
mwf.workflow_main_function = main
"""
Part 6: Register the Workflow
"""
register_workflow(mwf)
| 35.018237
| 171
| 0.601337
|
58caa9295d23010879a0de79e0ddf5e41099def1
| 5,702
|
php
|
PHP
|
application/views/main_navigation/v_checkout_act.php
|
aliffurqon/hotel
|
abf1f97c5f264987441e59743ce5b6b4eb7c8550
|
[
"MIT"
] | null | null | null |
application/views/main_navigation/v_checkout_act.php
|
aliffurqon/hotel
|
abf1f97c5f264987441e59743ce5b6b4eb7c8550
|
[
"MIT"
] | null | null | null |
application/views/main_navigation/v_checkout_act.php
|
aliffurqon/hotel
|
abf1f97c5f264987441e59743ce5b6b4eb7c8550
|
[
"MIT"
] | null | null | null |
<div class="container-fluid">
<ol class="breadcrumb">
<li class="breadcrumb-item">
<h1>Check out <span class="small">Halaman proses checkout</span></h1>
</li>
</ol>
<section class="content">
<?php foreach ($kamar_tidaktersedia as $ktd) {?>
<?php } ?>
<div class="box">
<div class="box-header">
<h3 class="box-title">KAMAR NOMOR : <b><?php echo $ktd->nomor_kamar; ?></b></h3>
</div>
<form action="<?php echo base_url().'checkout/checkout_act' ?>" method="post">
<input type="hidden" name="id_user" value="<?php echo $ktd->id_tamu; ?>" />
<input type="hidden" name="id_kamar" value="<?php echo $ktd->id_kamar; ?>" />
<div class="box-body">
<div class="row">
<div class="col-sm-3">
<div class="form-group">
<label># INVOICE</label>
<input class="form-control" name="nomor_invoice" value="<?php echo $ktd->nomor_invoice; ?>" readonly />
</div>
<div class="alert alert-info">
<h4><?php echo $ktd->nama_kamar_tipe; ?></h4>
<ul class="list-unstyled">
<li>Harga / Malam : <b>Rp <?php echo $ktd->harga_malam; ?></b></li>
<li>Maximal Orang Dewasa : <b><?php echo $ktd->max_dewasa; ?> Orang</b></li>
<li>Maximal Anak-anak : <b><?php echo $ktd->max_anak; ?> Orang</b></li>
</ul>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<label>Nama Tamu</label>
<input class="form-control" name="nomor_invoice" value="<?php echo $ktd->prefix;?>. <?php echo $ktd->nama_depan?> <?php echo $ktd->nama_belakang; ?> " readonly/>
</div>
</div>
<div class="col-sm-5">
<div class="form-group">
<label>Jumlah Tamu</label>
<div class="row">
<div class="col-sm-6">
<input class="form-control" name="nomor_invoice" value="<?php echo $ktd->jumlah_anak; ?>" readonly/>
</div>
<div class="col-sm-6">
<input class="form-control" name="nomor_invoice" value="<?php echo $ktd->jumlah_dewasa; ?>" readonly/>
</div>
</div>
</div>
<div class="form-group">
<label>Tanggal / Waktu Check-In</label>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="date" name="tanggal_checkin" value="<?php echo $ktd->tanggal_checkin; ?>" readonly/>
</div>
<div class="col-sm-6">
<input class="form-control" name="waktu_checkin" value="<?php echo $ktd->waktu_checkin?>" readonly />
</div>
</div>
</div>
<div class="form-group">
<label>Tanggal / Waktu Check-Out</label>
<div class="row">
<div class="col-sm-6">
<input id="checkout" type="date" class="form-control" name="tanggal_checkout" value="<?php echo $ktd->tanggal_checkout?>"readonly/>
</div>
<div class="col-sm-6">
<input class="form-control" name="waktu_checkout" value="<?php echo $ktd->waktu_checkout?>" readonly/>
</div>
</div>
</div>
<div class="form-group">
<label>Jumlah Deposit (Rp)</label>
<input class="form-control" name="deposit" value="<?php echo $ktd->deposit?>" readonly>
</div>
</div>
</div>
</div>
<?php
$checkin=$ktd->tanggal_checkin;
$checkout=$ktd->tanggal_checkout;
$tanggal_datang = strtotime($checkin);
$tanggal_pulang = strtotime($checkout);
$durasi = abs(($tanggal_pulang-$tanggal_datang)/(60*60*24));;
$subtotal_kamar=$durasi * $ktd->harga_malam;
$subtotal=$subtotal_kamar;
$ppn=$subtotal * 0.10;
$grand_total=$subtotal + $ppn - $ktd->deposit; ?>
<h3>Rincian Tagihan</h3>
<hr/>
<table class="table table-striped">
<thead>
<tr>
<th>Keterangan Layanan / Produk</th>
<th>Harga</th>
<th>Qty</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>Room reserved type : <?php echo $ktd->nama_kamar_tipe; ?> <?php $ktd->nomor_kamar ?></td>
<td>Rp <?php echo $ktd->harga_malam; ?></td>
<td><?php echo $durasi.' malam'; ?></td>
<td>Rp <?php echo $subtotal_kamar ; ?></td>
</tr>
<tr>
<td rowspan="4"></td>
<td colspan="2"><b>Sub-Total</b></td>
<td><b>Rp <?php echo number_format($subtotal); ?></b></td>
</tr>
<tr>
<td colspan="2">PPn 10%</td>
<td>Rp <?php echo number_format($ppn); ?></td>
</tr>
<tr>
<td colspan="2">Jumlah Deposit</td>
<td class="text-red">Rp <?php echo number_format($ktd->deposit); ?></td>
</tr>
<tr>
<td colspan="2"><b>Grand Total</b></td>
<td><b>Rp <?php echo number_format($ktd->total_biaya_kamar); ?></b></td>
</tr>
</tbody>
</table>
</div>
<div class="box-footer">
<p><font color="red">* Pastikan anda mencetak invoice terlebih dahulu sebelum ada menekan tombol checkout karena jika anda sudah menekan tombol checkout terlebih dahulu invoice tidak dapat dicetak <br>
* Jika transaksi cek_out berhasil maka anda akan dialihkan kehalaman utama check out<br>
* jika halaman ini merefresh maka input data gagal, silahkan coba lagi<br>
</font></p>
<input type="hidden" name="id_transaksi_kamar" value="<?php echo $ktd->id_transaksi_kamar; ?>" />
<input type="hidden" name="id_kamar" value="<?php echo $ktd->id_kamar; ?>" />
<button class="btn btn-success" type="submit">Check Out</button>
<a class="btn btn-primary" href="<?php echo base_url().'checkout/printinvoice' ?>" target="_blank">Cetak Invoice</a>
<a class="btn btn-warning" href="<?php echo base_url().'checkout' ?>">Batal</a>
</div>
</div>
</form>
</section>
</div>
| 39.874126
| 205
| 0.576815
|
9b8ddbb758203a16e10a60aabb56a1cbbbd38621
| 224
|
sh
|
Shell
|
script/run.sh
|
tenmihi/golf-it-bot
|
2d1514d759ff73a4052039ae5ff86cab176b2179
|
[
"MIT"
] | 1
|
2019-04-11T07:19:35.000Z
|
2019-04-11T07:19:35.000Z
|
script/run.sh
|
tenmihi/GolfItBot
|
2d1514d759ff73a4052039ae5ff86cab176b2179
|
[
"MIT"
] | null | null | null |
script/run.sh
|
tenmihi/GolfItBot
|
2d1514d759ff73a4052039ae5ff86cab176b2179
|
[
"MIT"
] | null | null | null |
#! /bin/zsh
set -eu
# script directory path
DIR=$(cd "$(dirname "$0")" && pwd)
# log file store path
LOG_PATH=$DIR/../log
mkdir -p $LOG_PATH
# launch bot
ruby $DIR/../lib/bot.rb -D |& tee $LOG_PATH/stdout_and_stderr.txt
| 16
| 65
| 0.651786
|
ea3f8005265a354cbaf7ff167149652573429436
| 810
|
go
|
Go
|
bitbucket/teams_search_code.go
|
davidji99/go-bb
|
91c05bd118ac9566be26251b71cba9bc05ce43e1
|
[
"BSD-3-Clause"
] | 6
|
2020-01-03T01:41:18.000Z
|
2020-11-05T02:43:20.000Z
|
bitbucket/teams_search_code.go
|
davidji99/go-bb
|
91c05bd118ac9566be26251b71cba9bc05ce43e1
|
[
"BSD-3-Clause"
] | 41
|
2018-12-20T08:40:18.000Z
|
2019-07-12T08:25:46.000Z
|
bitbucket/teams_search_code.go
|
davidji99/go-bb
|
91c05bd118ac9566be26251b71cba9bc05ce43e1
|
[
"BSD-3-Clause"
] | 3
|
2020-03-09T20:36:49.000Z
|
2020-06-27T04:01:21.000Z
|
package bitbucket
import (
"fmt"
"github.com/davidji99/simpleresty"
)
// SearchCode searches for code in the repositories of the specified team.
//
// Accepts the user's UUID, account_id, or username. Recommend to use UUID or account_id.
//
// Bitbucket API docs: https://developer.atlassian.com/bitbucket/api/2/reference/resource/teams/%7Busername%7D/search/code#get
func (t *TeamsService) SearchCode(teamUsername string, opts ...interface{}) (*SearchCodeResults, *simpleresty.Response, error) {
results := new(SearchCodeResults)
urlStr, urlStrErr := t.client.http.RequestURLWithQueryParams(
fmt.Sprintf("/teams/%s/search/code", teamUsername), opts...)
if urlStrErr != nil {
return nil, nil, urlStrErr
}
response, err := t.client.http.Get(urlStr, results, nil)
return results, response, err
}
| 32.4
| 128
| 0.745679
|
e75887386be5eacad54c4d1efaaa4cfdb0de20a7
| 381
|
php
|
PHP
|
application/controllers/test/Email.php
|
junggc/cleandpg
|
67db0f88cb891742d034c5ed22de5f9e2eacd71c
|
[
"MIT"
] | null | null | null |
application/controllers/test/Email.php
|
junggc/cleandpg
|
67db0f88cb891742d034c5ed22de5f9e2eacd71c
|
[
"MIT"
] | null | null | null |
application/controllers/test/Email.php
|
junggc/cleandpg
|
67db0f88cb891742d034c5ed22de5f9e2eacd71c
|
[
"MIT"
] | null | null | null |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Email extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('email_l');
}
public function email_send()
{
echo $res = $this->email_l->email_send('test@test.com', 'test', 'ccnp.rjh@gmail.com', '제목 test', '내용 test');
// print_r($res);
}
}
| 20.052632
| 110
| 0.653543
|
ff5cc8a165fd22d7ca2bd7d72c0fb3b5807f48d5
| 241
|
py
|
Python
|
app/biodata/admin.py
|
CharaD7/biodata-python
|
b03f3edff25d6a9b38000e9964537dd81e193a68
|
[
"MIT"
] | null | null | null |
app/biodata/admin.py
|
CharaD7/biodata-python
|
b03f3edff25d6a9b38000e9964537dd81e193a68
|
[
"MIT"
] | 4
|
2019-10-19T17:18:00.000Z
|
2021-06-10T22:12:30.000Z
|
app/biodata/admin.py
|
CharaD7/biodata-python
|
b03f3edff25d6a9b38000e9964537dd81e193a68
|
[
"MIT"
] | null | null | null |
from django.contrib import admin
from .models import Biodata, UserProfile
# Register your models here.
@admin.register(Biodata)
@admin.register(UserProfile)
# admin.site.register(UserProfile)
class BiodataAdmin(admin.ModelAdmin):
pass
| 21.909091
| 40
| 0.79668
|
38608b582ac5f12a36ccd52863f362fd5b274b70
| 6,458
|
php
|
PHP
|
resources/views/menu/shop/products.blade.php
|
robertmcbathin/etk-admin
|
4c72033ab914a7e19fec9b792023285c780b1af5
|
[
"MIT"
] | null | null | null |
resources/views/menu/shop/products.blade.php
|
robertmcbathin/etk-admin
|
4c72033ab914a7e19fec9b792023285c780b1af5
|
[
"MIT"
] | null | null | null |
resources/views/menu/shop/products.blade.php
|
robertmcbathin/etk-admin
|
4c72033ab914a7e19fec9b792023285c780b1af5
|
[
"MIT"
] | null | null | null |
@extends('layouts.master')
@section('title')
Магазин | Товары
@endsection
@section('content')
<div class="page-title">
<div class="title_left">
<h3>Товары</h3>
</div>
<div class="title_right">
<div class="col-md-5 col-sm-5 col-xs-12 form-group pull-right top_search"></div>
</div>
</div>
@foreach ($categories as $category)
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2><i class="fa fa-align-left"></i> {{ $category->name }} </h2>
<div class="clearfix"></div>
</div>
<div class="x_content">
<!-- start accordion -->
<div class="accordion" id="accordion" role="tablist" aria-multiselectable="true">
@foreach ($subcategories as $subcategory)
@if ($subcategory->category_id == $category->id)
<div class="panel">
<a class="panel-heading collapsed" role="tab" id="heading{{ $subcategory->id }}" data-toggle="collapse" data-parent="#accordion" href="#collapse{{ $subcategory->id }}" aria-expanded="false" aria-controls="collapseOne">
<h4 class="panel-title">{{ $subcategory->name }}</h4>
</a>
<div id="collapse{{ $subcategory->id }}" class="panel-collapse collapse" role="tabpanel" aria-labelledby="heading{{ $subcategory->id }}" aria-expanded="false" style="height: 0px;">
<div class="panel-body">
<div class="table-responsive">
<table class="table table-striped jambo_table bulk_action">
<thead>
<tr class="headings">
<th class="column-title">#</th>
<th class="column-title">Наименование</th>
<th class="column-title">Изображение</th>
<th class="column-title">Цена (от поставщика)</th>
<th class="column-title">Цена (розница)</th>
<th class="column-title">Цена (по карте)</th>
<th class="column-title">Наличие</th>
<th class="column-title">На складе</th>
<th class="column-title">Приоритет</th>
<th class="column-title">Опубликовано</th>
<th class="column-title no-link last">
<span class="nobr">Действие</span>
</th>
<th class="bulk-actions" colspan="7">
<a class="antoo" style="color:#fff; font-weight:500;">
Bulk Actions (
<span class="action-cnt"></span>
)
<i class="fa fa-chevron-down"></i>
</a>
</th>
</tr>
</thead>
<tbody>
@foreach ($products as $product)
@if ($product->subcategory_id == $subcategory->id)
<tr>
<th scope="row">{{ $product->id }}</th>
<td>{{ $product->name }}</td>
<td>
<img src="{{ $product->path_to_img }}" alt="" height="50">
</td>
<td>{{ $product->price_by_supplier }}</td>
<td>{{ $product->price }}</td>
<td>{{ $product->price_by_card }}</td>
@if ($product->in_stock == 1)
<td>В наличии</td>
@endif
@if ($product->in_stock == 2)
<td>На заказ</td>
@endif
@if ($product->in_stock == 3)
<td>По закупке</td>
@endif
@if ($product->in_stock == 4)
<td>Снято с продажи</td>
@endif
<td>{{ $product->availability }}</td>
<td>{{ $product->priority }}</td>
<td>
@if ($product->published == 1)
<i class="fa fa-circle" style="color:#00ff00"></i>
@endif
@if ($product->published == 0)
<i class="fa fa-circle" style="color:#ff0000"></i>
@endif
</td>
<td class=" last">
<a href="/shop/products/{{$product->
id}}/delete" class="btn btn-danger">
<i class="fa fa-trash"></i>
</a>
<a href="/shop/products/{{ $category->id }}/{{$subcategory->id}}/{{$product->
id}}/edit" class="btn btn-primary">
<i class="fa fa-pencil"></i>
</a>
@if ($product->published == 1)
<a href="/shop/products/{{$product->
id}}/lock" class="btn btn-primary">
<i class="fa fa-lock"></i>
</a>
@endif
@if ($product->published == 0)
<a href="/shop/products/{{$product->
id}}/unlock" class="btn btn-primary">
<i class="fa fa-unlock"></i>
</a>
@endif
</td>
</tr>
@endif
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
@endif
@endforeach
<a class="btn btn-primary" href="http://etk-admin.ru/shop/products/{{$category->id}}/add"><i class="fa fa-plus"></i>Добавить</a>
</div>
<!-- end of accordion -->
</div>
</div>
</div>
@endforeach
<div class="clearfix"></div>
<div class="row"></div>
<div class="clearfix"></div>
@endsection
| 45.160839
| 242
| 0.391607
|
33a4e83ae4e333086dc3160e232d04caa964dcd6
| 6,434
|
h
|
C
|
include/simple_i2c.h
|
mrrb/esp8266_co2_logger
|
d3c42a073276b4b2323e412d4e970165a897b681
|
[
"MIT"
] | null | null | null |
include/simple_i2c.h
|
mrrb/esp8266_co2_logger
|
d3c42a073276b4b2323e412d4e970165a897b681
|
[
"MIT"
] | null | null | null |
include/simple_i2c.h
|
mrrb/esp8266_co2_logger
|
d3c42a073276b4b2323e412d4e970165a897b681
|
[
"MIT"
] | null | null | null |
/**
* \file simple_i2c.h
* \author Mario Rubio (mario@mrrb.eu)
* \brief Functions to quickly use the SW_I2C communication. Header file.
* \version 0.1
* \date 2020-12-15
*
*/
#ifndef SIMPLE_I2C_H
#define SIMPLE_I2C_H
#include <c_types.h>
#include "driver/i2c_master.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
typedef enum i2c_start_op {
I2C_OP_WRITE = 0,
I2C_OP_READ = 1,
} i2c_start_op_t;
/**
* \brief Init the software I2C bus
* \param[out] p_result: Result of the operation
* \hideinitializer
*/
#define I2C_INIT(p_result) do { \
i2c_master_gpio_init(); \
i2c_master_init(); \
*p_result = 1; \
} while(0)
/**
* \brief Start a I2C transaction
* \param[in] addr: I2C slave address
* \param[in] op: i2c_start_op_t. I2C operation read/write
* \param[out] p_result: Result of the operation
* \hideinitializer
*/
#define I2C_START(addr, op, p_result) do { \
i2c_master_start(); \
i2c_master_writeByte((addr<<1) + op); \
*p_result = i2c_master_checkAck(); \
} while(0)
/**
* \brief Start a READ I2C transaction
* \param[in] addr: I2C slave address
* \param[out] p_result: Result of the operation
* \hideinitializer
*/
#define I2C_START_READ(addr, p_result) do { \
I2C_START(addr, I2C_OP_READ, p_result); \
} while(0)
/**
* \brief Start a WRITE I2C transaction
* \param[in] addr: I2C slave address
* \param[out] p_result: Result of the operation
* \hideinitializer
*/
#define I2C_START_WRITE(addr, p_result) do { \
I2C_START(addr, I2C_OP_WRITE, p_result); \
} while(0)
/**
* \brief Stop the I2C transaction
* \param[out] p_result: Result of the operation
* \hideinitializer
*/
#define I2C_STOP(p_result) do { \
i2c_master_stop(); \
*p_result = 1; \
} while(0)
/**
* \brief Send a byte to the I2C slave
* \param[in] data: Byte to send
* \param[out] p_result: Result of the operation
* \hideinitializer
*/
#define I2C_WRITE_BYTE(data, p_result) do { \
i2c_master_writeByte(data); \
*p_result = i2c_master_checkAck(); \
} while(0)
/**
* \brief Send `data_len` byte(s) to the I2C slave
* \param[in] p_data: Byte(s) to send
* \param[in] data_len: Number of bytes
* \param[out] p_result: Result of the operation
* \hideinitializer
*/
#define I2C_WRITE_BYTES(p_data, data_len, p_result) do { \
if (p_data == NULL || data_len < 1) { \
*p_result = 0; \
} else { \
for (size_t i = 0; i < data_len; ++i) { \
I2C_WRITE_BYTE(*(p_data+i), p_result); \
if (!(*p_result)) { \
break; \
} \
} \
} \
} while(0)
/**
* \brief Read a byte from the I2C slave
* \param[in] p_data: Readed byte
* \param[out] p_result: Result of the operation
* \hideinitializer
*/
#define I2C_READ_BYTE(p_data, p_result) do { \
if (p_data == NULL) { \
*p_result = 0; \
} else { \
*p_data = i2c_master_readByte(); \
i2c_master_send_nack(); \
*p_result = 1; \
} \
} while(0)
/**
* \brief Read `data_len` byte(s) from the I2C slave
* \param[in] p_data: Readed bytes(s)
* \param[in] data_len: Number of bytes
* \param[out] p_result: Result of the operation
* \hideinitializer
*/
#define I2C_READ_BYTES(p_data, data_len, p_result) do { \
if (p_data == NULL || data_len < 1) { \
*p_result = 0; \
} else { \
for (size_t i = 0; i < data_len - 1; ++i) { \
p_data[i] = i2c_master_readByte(); \
i2c_master_send_ack(); \
} \
p_data[data_len-1] = i2c_master_readByte(); \
i2c_master_send_nack(); \
*p_result = 1; \
} \
} while(0)
#define I2C_DELAY i2c_master_wait
// inline uint8_t
// I2C_INIT() {
// i2c_master_gpio_init();
// i2c_master_init();
// return 1;
// }
// inline uint8_t
// I2C_START(uint8_t addr, i2c_start_op_t op) {
// i2c_master_start();
// i2c_master_writeByte((addr<<1) + op);
// return i2c_master_checkAck();
// }
// inline uint8_t
// I2C_START_READ(uint8_t addr) {
// return I2C_START(addr, I2C_OP_READ);
// }
// inline uint8_t
// I2C_START_WRITE(uint8_t addr) {
// return I2C_START(addr, I2C_OP_WRITE);
// }
// inline uint8_t
// I2C_STOP() {
// i2c_master_stop();
// return 1;
// }
// inline uint8_t
// I2C_WRITE_BYTE(uint8_t data) {
// i2c_master_writeByte(data);
// return i2c_master_checkAck();
// }
// inline uint8_t
// I2C_WRITE_BYTES(uint8_t* data, size_t data_len) {
// if (data == NULL || data_len < 1) {
// return 0;
// }
// uint8_t result;
// for (size_t i = 0; i < data_len; ++i) {
// result = I2C_WRITE_BYTE(*(data++));
// if (!result) {
// return result;
// }
// }
// return result;
// }
// inline uint8_t
// I2C_READ_BYTE(uint8_t* data) {
// if (data == NULL) {
// return 0;
// }
// *data = i2c_master_readByte();
// i2c_master_send_nack();
// return 1;
// }
// inline uint8_t
// I2C_READ_BYTES(uint8_t* data, size_t data_len) {
// if (data == NULL || data_len < 1) {
// return 0;
// }
// for (size_t i = 0; i < data_len - 1; ++i) {
// data[i] = i2c_master_readByte();
// i2c_master_send_ack();
// }
// data[data_len-1] = i2c_master_readByte();
// i2c_master_send_nack();
// return 1;
// }
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* SIMPLE_I2C_H */
| 27.147679
| 73
| 0.504974
|
875de5b486b7093d2575e385761576ceec515e8f
| 199
|
rb
|
Ruby
|
examples/hash_key.rb
|
raviqqe/sub-elems.rb
|
fece3b24895b6843313ea5734abe8bf77c0f0023
|
[
"Unlicense"
] | null | null | null |
examples/hash_key.rb
|
raviqqe/sub-elems.rb
|
fece3b24895b6843313ea5734abe8bf77c0f0023
|
[
"Unlicense"
] | null | null | null |
examples/hash_key.rb
|
raviqqe/sub-elems.rb
|
fece3b24895b6843313ea5734abe8bf77c0f0023
|
[
"Unlicense"
] | null | null | null |
require 'map-rec'
REPLACED = 'REPLACED'
h1 = { foo: 'Hello', bar: 'world!' }
h2 = map_rec(h1, hash_key: false) do
REPLACED
end
h1[:foo] = REPLACED
h1[:bar] = REPLACED
raise unless h1 == h2
| 11.055556
| 36
| 0.628141
|
ea4448f5779b9ef75baec76867341dc280c03050
| 978
|
sh
|
Shell
|
scripts/tune_spectrogram/english_vowels/getvowels.sh
|
MaxStrange/ArtieInfant
|
1edbb171a5405d2971227f2d2d83acb523c70034
|
[
"MIT"
] | 1
|
2018-04-28T16:55:05.000Z
|
2018-04-28T16:55:05.000Z
|
scripts/tune_spectrogram/english_vowels/getvowels.sh
|
MaxStrange/ArtieInfant
|
1edbb171a5405d2971227f2d2d83acb523c70034
|
[
"MIT"
] | null | null | null |
scripts/tune_spectrogram/english_vowels/getvowels.sh
|
MaxStrange/ArtieInfant
|
1edbb171a5405d2971227f2d2d83acb523c70034
|
[
"MIT"
] | null | null | null |
wget https://upload.wikimedia.org/wikipedia/commons/9/91/Close_front_unrounded_vowel.ogg
wget https://upload.wikimedia.org/wikipedia/commons/6/6c/Close-mid_front_unrounded_vowel.ogg
wget https://upload.wikimedia.org/wikipedia/commons/7/71/Open-mid_front_unrounded_vowel.ogg
wget https://upload.wikimedia.org/wikipedia/commons/c/c9/Near-open_front_unrounded_vowel.ogg
wget https://upload.wikimedia.org/wikipedia/commons/6/65/Open_front_unrounded_vowel.ogg
wget https://upload.wikimedia.org/wikipedia/commons/d/d9/Mid-central_vowel.ogg
wget https://upload.wikimedia.org/wikipedia/commons/e/e5/Open_back_unrounded_vowel.ogg
wget https://upload.wikimedia.org/wikipedia/commons/9/92/Open-mid_back_unrounded_vowel.ogg
wget https://upload.wikimedia.org/wikipedia/commons/0/02/Open-mid_back_rounded_vowel.ogg
wget https://upload.wikimedia.org/wikipedia/commons/8/84/Close-mid_back_rounded_vowel.ogg
wget https://upload.wikimedia.org/wikipedia/commons/5/5d/Close_back_rounded_vowel.ogg
| 75.230769
| 92
| 0.845603
|
dda1a96bed2bd8d3aa08892e503f3d55bcf12631
| 2,164
|
java
|
Java
|
collection-map/src/com/hfm/collection/list/arraylist/MyArrayList.java
|
hfming/core-java
|
ef5c4e53965e3ef6857e3e7ccecd2472a2524cdc
|
[
"MIT"
] | null | null | null |
collection-map/src/com/hfm/collection/list/arraylist/MyArrayList.java
|
hfming/core-java
|
ef5c4e53965e3ef6857e3e7ccecd2472a2524cdc
|
[
"MIT"
] | null | null | null |
collection-map/src/com/hfm/collection/list/arraylist/MyArrayList.java
|
hfming/core-java
|
ef5c4e53965e3ef6857e3e7ccecd2472a2524cdc
|
[
"MIT"
] | null | null | null |
package com.hfm.collection.list.arraylist;
import java.util.AbstractList;
import java.util.Arrays;
/**
* @author hfm Email:hfming2016@163.com
* @version v 1.01
* @Description 自定义 ArrayList 集合
* @date 2020-04-29 18:31
*/
public class MyArrayList<E> extends AbstractList<E> {
public Object add;
/**
* 创建底层数组
*/
private Object[] elementDate;
/**
* 元素的个数
*/
private int size;
/**
* 默认创建长度为 0 的数组
*/
private static final Object[] DEFAULT_EMPTY_ELEMENTDATE = {};
/**
* 默认长度
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* 无参构造函数
*/
MyArrayList() {
// 默认初始长度为 0
elementDate = DEFAULT_EMPTY_ELEMENTDATE;
}
@Override
public boolean add(Object o) {
if (size == elementDate.length) {
grow();
}
elementDate[size++] = o;
++modCount;
return true;
}
@Override
public E remove(int index) {
checkIndexRange(index);
E o = get(index);
System.arraycopy(elementDate, index + 1, elementDate, index, size -1 - index);
elementDate[--size] = null;
return o;
}
/**
* 扩容方法
*/
private void grow() {
// 第一次添加元素
if (size == 0) {
elementDate = new Object[DEFAULT_CAPACITY];
}
// 默认扩容0.5倍
if (size == elementDate.length) {
int newCaptcity = elementDate.length + elementDate.length >> 1;
elementDate = Arrays.copyOf(elementDate, newCaptcity);
}
}
@Override
public E get(int i) {
// 判断 index 范围
checkIndexRange(i);
return (E) elementDate[i];
}
@Override
public E set(int index, E element) {
checkIndexRange(index);
E e = get(index);
return (E) (elementDate[index] = element);
}
/**
* 检查索引范围
*
* @param i
*/
private void checkIndexRange(int i) {
if (i < 0 || i > elementDate.length) {
throw new ArrayIndexOutOfBoundsException();
}
}
@Override
public int size() {
return this.size;
}
}
| 20.609524
| 86
| 0.536044
|
f68b5ad78f3011c62b0678b5c490e3d5ab5883cb
| 828
|
lua
|
Lua
|
source/libs/lua/table.lua
|
CrocodileJonesy/wagon-auto-graphics
|
2b33633fb9992e34edcd12a5070663e2614deb32
|
[
"MIT"
] | 2
|
2021-02-19T11:57:00.000Z
|
2021-02-19T12:35:30.000Z
|
source/libs/lua/table.lua
|
Loot-1/wagon-auto-graphics
|
4ff8b648458c03e9968eac570403cb2e2cdb5536
|
[
"MIT"
] | null | null | null |
source/libs/lua/table.lua
|
Loot-1/wagon-auto-graphics
|
4ff8b648458c03e9968eac570403cb2e2cdb5536
|
[
"MIT"
] | 1
|
2021-07-01T01:32:12.000Z
|
2021-07-01T01:32:12.000Z
|
function table.numericAddTable(t,t2, factor, initial)
if factor == nil then factor = 1 end
if initial == nil then initial = 0 end
for k,value in pairs(t2) do
if t[k] == nil then t[k] = initial end
t[k] = t[k] + factor * value
if t[k] == 0 then t[k] = nil end
end
end
function table.addTable(t,toAdd)
if toAdd then
for k,v in pairs(toAdd) do t[k] = v end
end
end
function table.appendTable(t, toAdd)
for k,v in pairs(toAdd) do table.insert(t, v) end
end
function table.set(t) -- set of list
local s = { }
for _, v in ipairs(t) do s[v] = true end
return s
end
function table.clear(t)
local count = #t
for i=0, count do t[i]=nil end
end
function table.contains(table,value)
if table == nil then return false end
for k,v in pairs(table) do
if v == value then return true end
end
return false
end
| 20.7
| 53
| 0.669082
|
2ac366b6381677c77cee6dd2d2bdd7ad5c2d6989
| 500
|
css
|
CSS
|
angularxavi/css/app.css
|
narum/jocomunicoLAB
|
dc9cf1d7066d49ea18542e255bebbd420a6e0bc8
|
[
"MIT"
] | null | null | null |
angularxavi/css/app.css
|
narum/jocomunicoLAB
|
dc9cf1d7066d49ea18542e255bebbd420a6e0bc8
|
[
"MIT"
] | null | null | null |
angularxavi/css/app.css
|
narum/jocomunicoLAB
|
dc9cf1d7066d49ea18542e255bebbd420a6e0bc8
|
[
"MIT"
] | null | null | null |
header{
background:#2c3e50;
color:#fff;
}
.main{
background: #f2f2f2;
}
.color1{
background: #34495e;
color:#fff;
}
aside{
background: #f2f2f2;
}
footer{
background: #FDFFE1;
color: #fff;
}
ul{
list-style-type: none;
}
.img-rounded {
border-radius: 6px;
border:2px solid;
}
.piclist {
display: inline;
}
.root {
display: flex;
flex-direction: column;
}
.root .container {
flex: 1;
}
html,body,.root {
min-height: 100vh;
}
| 11.904762
| 26
| 0.574
|
38571b77464093be09a8aa6f189d710aa072df90
| 731
|
cs
|
C#
|
Groover/Groover.AvaloniaUI/Utils/IsAdminConverter.cs
|
Djordje-Nikolic/Groover
|
aa5fee0b01431d6a845a46909103746543cc7d15
|
[
"MIT"
] | 1
|
2021-11-08T07:45:40.000Z
|
2021-11-08T07:45:40.000Z
|
Groover/Groover.AvaloniaUI/Utils/IsAdminConverter.cs
|
Djordje-Nikolic/Groover
|
aa5fee0b01431d6a845a46909103746543cc7d15
|
[
"MIT"
] | null | null | null |
Groover/Groover.AvaloniaUI/Utils/IsAdminConverter.cs
|
Djordje-Nikolic/Groover
|
aa5fee0b01431d6a845a46909103746543cc7d15
|
[
"MIT"
] | null | null | null |
using Avalonia.Data.Converters;
using Groover.AvaloniaUI.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Groover.AvaloniaUI.Utils
{
public class IsAdminConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((GrooverGroupRole)value == GrooverGroupRole.Admin)
return true;
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| 26.107143
| 103
| 0.685363
|
853bc63e40f2c7feebd02979bd9eccf1d24c1782
| 7,519
|
cs
|
C#
|
Toolbox/Toolbox/ToolboxControls/About/EasterEggControl.cs
|
NetOfficeFw/NetOffice-LegacyRepository
|
07a4b5d217cbda9c318b835e31f2ad43a5964f90
|
[
"MIT"
] | 99
|
2016-07-05T09:09:11.000Z
|
2022-03-13T02:21:12.000Z
|
Toolbox/Toolbox/ToolboxControls/About/EasterEggControl.cs
|
NetOfficeFw/NetOffice-LegacyRepository
|
07a4b5d217cbda9c318b835e31f2ad43a5964f90
|
[
"MIT"
] | 16
|
2016-10-15T15:03:44.000Z
|
2021-07-30T01:01:05.000Z
|
Toolbox/Toolbox/ToolboxControls/About/EasterEggControl.cs
|
NetOfficeFw/NetOffice-LegacyRepository
|
07a4b5d217cbda9c318b835e31f2ad43a5964f90
|
[
"MIT"
] | 52
|
2016-10-14T22:53:04.000Z
|
2021-10-14T11:14:26.000Z
|
using System;
using System.IO;
using System.Collections.Generic;
using System.Drawing;
using System.Media;
using System.Windows.Forms;
using ICSharpCode.SharpZipLib.Zip;
namespace NetOffice.DeveloperToolbox.ToolboxControls.About
{
/// <summary>
/// A small easter egg to make people smile :)
/// </summary>
public partial class EasterEggControl : UserControl
{
#region Fields
private SoundPlayer _playerGunshot;
private SoundPlayer _playerWait;
private int _lcid = 1033;
private Stream _waitStream;
private string _messageDefault = "Thanks for using Developer Toolbox";
private string _messageGerman = "Java Script? Dieses beschränkte kleine...";
#endregion
#region Ctor
/// <summary>
/// Creates an instance of the class
/// </summary>
public EasterEggControl()
{
InitializeComponent();
}
/// <summary>
/// Creates an instance of the class
/// </summary>
/// <param name="lcid">current user language id</param>
public EasterEggControl(int lcid)
{
InitializeComponent();
_lcid = lcid;
}
#endregion
#region Events
/// <summary>
/// Egg is done and want close
/// </summary>
internal event EventHandler Done;
private void RaiseDone()
{
if (null != Done)
Done(this, EventArgs.Empty);
}
#endregion
#region Methods
/// <summary>
/// Show the angry old men
/// </summary>
internal void ShowGernot()
{
try
{
CreatePlayers();
string txt = _lcid == 1031 ? _messageGerman : _messageDefault;
List<Control> list = new List<Control>();
int i = 0;
foreach (var item in txt.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries))
{
Label text = new Label();
text.AutoSize = true;
text.Location = new Point(i + 4, 30);
text.Font = panelMessage.Font;
text.ForeColor = panelMessage.ForeColor;
text.Text = item;
text.Visible = true;
list.Add(text);
i += TextRenderer.MeasureText(item, text.Font).Width;
}
Utils.Animation.Effects.EffectsAnimator.DoEffect(pictureBoxGernot, Utils.Animation.Effects.EffectsKind.Collapse, true, 250);
Timer timerText = new Timer();
timerText.Interval = 400;
timerText.Enabled = true;
int ctrlIndex = 0;
int delayTicks = 0;
bool playWait = false;
DateTime playWaitStart = DateTime.Now;
timerText.Tick += delegate(object sender, EventArgs e)
{
if (ctrlIndex >= list.Count)
{
delayTicks++;
if (delayTicks < 5)
return;
if (!playWait)
{
pictureBoxWait.Visible = true;
pictureBoxWait.BringToFront();
panelMessage.Visible = false;
pictureBoxGernot.Visible = false;
playWait = true;
playWaitStart = DateTime.Now;
PlayWait();
}
else
{
if (DateTime.Now.Subtract(playWaitStart).TotalSeconds >= 18.0)
{
timerText.Enabled = false;
DisposePlayers();
RaiseDone();
return;
}
}
}
else
{
PlayGunshot();
Control ctrl = list[ctrlIndex];
panelMessage.Controls.Add(ctrl);
ctrlIndex++;
}
};
}
catch
{
RaiseDone();
}
}
private void PlayWait()
{
try
{
if (null != _playerWait)
_playerWait.Play();
}
catch
{
;
}
}
private void PlayGunshot()
{
try
{
if (null != _playerGunshot)
_playerGunshot.Play();
}
catch
{
;
}
}
private void CreatePlayers()
{
try
{
DisposePlayers();
System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream s1 = a.GetManifestResourceStream("NetOffice.DeveloperToolbox.ToolboxControls.About.Gunshot.wav");
s1.Seek(0, System.IO.SeekOrigin.Begin);
_playerGunshot = new SoundPlayer(s1);
if (null == _waitStream)
{
System.IO.Stream waitZip = a.GetManifestResourceStream("NetOffice.DeveloperToolbox.ToolboxControls.About.Wait.zip");
waitZip.Seek(0, SeekOrigin.Begin);
ZipFile file = new ZipFile(waitZip);
var waitFile = file.GetInputStream(0);
_waitStream = waitFile;
}
_playerWait = new SoundPlayer(_waitStream);
}
catch
{
;
}
}
private void DisposePlayers()
{
try
{
if (null != _playerWait)
{
_playerWait.Stop();
_playerWait.Dispose();
_playerWait = null;
}
if (null != _playerGunshot)
{
_playerGunshot.Stop();
_playerGunshot.Dispose();
_playerGunshot = null;
}
}
catch
{
;
}
}
#endregion
#region Trigger
private void EasterEggControl_Resize(object sender, EventArgs e)
{
try
{
pictureBoxGernot.Location = new Point(Width / 2 - pictureBoxGernot.Width / 2, Height / 2 - pictureBoxGernot.Height / 2);
panelMessage.Location = new Point(pictureBoxGernot.Left, pictureBoxGernot.Top - panelMessage.Height);
}
catch (Exception exception)
{
Forms.ErrorForm.ShowError(this, exception,ErrorCategory.NonCritical);
}
}
#endregion
}
}
| 31.329167
| 141
| 0.424791
|
ae1ad426d35309ddaa5d7f6f882465f31e06c648
| 6,527
|
cs
|
C#
|
MainWindow.xaml.cs
|
jftuga/deidentify-gui
|
dd5962ffee4aa51123743149df60b9e548692a58
|
[
"MIT"
] | 1
|
2021-07-04T02:25:48.000Z
|
2021-07-04T02:25:48.000Z
|
MainWindow.xaml.cs
|
jftuga/deidentify-gui
|
dd5962ffee4aa51123743149df60b9e548692a58
|
[
"MIT"
] | 1
|
2021-03-29T20:09:12.000Z
|
2021-03-29T20:09:12.000Z
|
MainWindow.xaml.cs
|
jftuga/deidentify-gui
|
dd5962ffee4aa51123743149df60b9e548692a58
|
[
"MIT"
] | 1
|
2021-03-29T04:38:37.000Z
|
2021-03-29T04:38:37.000Z
|
using HtmlAgilityPack;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Path = System.IO.Path;
namespace deidentify_gui
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private string inputFile;
private string jsonFile;
private string outputFile;
private bool usingDefaultFilenames;
private string tempDir;
public MainWindow()
{
InitializeComponent();
ResetDefaults();
Auxiliary.DeleteTempFiles(this.tempDir);
}
private void ResetDefaults()
{
string temp = (Environment.GetEnvironmentVariable("TEMP").Length > 0) ? Environment.GetEnvironmentVariable("TEMP") : (Environment.GetEnvironmentVariable("TMP").Length > 0) ? Environment.GetEnvironmentVariable("TMP") : ".";
temp += Path.DirectorySeparatorChar;
this.tempDir = temp;
this.inputFile = temp + "default--input.txt";
this.outputFile = temp + "default--output.htm";
this.jsonFile = temp;
this.usingDefaultFilenames = true;
}
private void SetAllFilename()
{
string fileNameWithoutExtension = this.inputFile;
if (this.usingDefaultFilenames == false)
{
int i = this.inputFile.LastIndexOf(".");
if (i > 0)
{
fileNameWithoutExtension = this.inputFile.Substring(0, i);
}
this.jsonFile = fileNameWithoutExtension + "--tokens.json";
this.outputFile = fileNameWithoutExtension + "--deidentified" + ".htm";
}
}
private void Click_Close(object sender, RoutedEventArgs e)
{
Auxiliary.DeleteTempFiles(this.tempDir);
Close();
}
// update status begin
// https://stackoverflow.com/a/10715059/452281
public delegate void UpdateTextCallback(string message);
private void UpdateStatus(string message)
{
Label_Status.Content = message;
}
private void UpdateThread()
{
string message = "Status: Starting deidentification...";
this.Dispatcher.Invoke(
new UpdateTextCallback(this.UpdateStatus),
new object[] { message.ToString() }
);
}
// update status end
private void Click_Deidentify(object sender, RoutedEventArgs e)
{
// status is not working, can someone please help me fix this?
//Thread updaterTh = new Thread(new ThreadStart(UpdateThread));
//updaterTh.Start();
try
{
string tempFile = Path.GetTempFileName();
File.WriteAllText(tempFile, Auxiliary.StringFromRichTextBox(RichTextBox_Original));
Auxiliary.FileDeidentify(TextBox_Replacement.Text, this.outputFile, tempFile, Label_Status);
File.Delete(tempFile);
this.jsonFile = Auxiliary.SetJSONFilename(tempFile);
myBrowser.Navigate(this.outputFile);
} catch( Exception ex)
{
MessageBox.Show(ex.ToString(), "Exception #18293");
}
}
private void Click_OpenFile(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
string readText = "";
if (openFileDialog.ShowDialog() == true)
{
RichTextBox_Original.Document.Blocks.Clear();
this.inputFile = openFileDialog.FileName;
readText = File.ReadAllText(this.inputFile);
RichTextBox_Original.Document.Blocks.Add(new Paragraph(new Run(readText)));
this.usingDefaultFilenames = false;
SetAllFilename();
}
}
private void Click_About(object sender, RoutedEventArgs e)
{
ApplicationEnvironment app = PlatformServices.Default.Application;
string version = app.ApplicationVersion;
MessageBox.Show("Deidentify GUI" + "\n" + version + "\n\n" + "https://github.com/jftuga/deidentify-gui" + "\n" + "https://github.com/jftuga/deidentify", "Deidentify");
}
private void Click_Debug(object sender, RoutedEventArgs e)
{
string browserPath = Auxiliary.GetPathToDefaultBrowser();
Process.Start(browserPath, this.jsonFile);
}
private void Click_Clear(object sender, RoutedEventArgs e)
{
RichTextBox_Original.Document.Blocks.Clear();
myBrowser.Navigate(@"about:blank");
Label_Status.Content = "Status:";
ResetDefaults();
}
private void Click_Copy(object sender, RoutedEventArgs e)
{
var htmlDoc = new HtmlDocument();
htmlDoc.Load(this.outputFile);
var htmlNodes = htmlDoc.DocumentNode.SelectNodes("//body");
if(htmlNodes.Count() > 0)
{
Clipboard.SetDataObject(new DataObject(DataFormats.Text, htmlNodes[0].InnerText), true);
}
}
private void Click_Into_Original(object sender, MouseButtonEventArgs e)
{
string o = Auxiliary.StringFromRichTextBox(RichTextBox_Original);
if ( o.StartsWith("Original Text") )
{
RichTextBox_Original.Document.Blocks.Clear();
}
}
private void Click_Save(object sender, RoutedEventArgs e)
{
MessageBox.Show("The SAVE function has not been implemented yet." + "\n" + "Instead, use COPY to copy the deidentifed text to the clipboard.", "Deidentify");
}
private void Window_Closing(object sender, EventArgs e)
{
Auxiliary.DeleteTempFiles(this.tempDir);
}
}
}
| 35.091398
| 234
| 0.601808
|
21f800e856a2cf643d443855a04dd4448b637140
| 23,418
|
dart
|
Dart
|
lib/ui/screens/documents/document_create.dart
|
sknew93/flutter-crm
|
ab03fbcd1b513d8d9f118fdc86c4d2d07c91243c
|
[
"MIT"
] | 1
|
2020-12-23T10:40:31.000Z
|
2020-12-23T10:40:31.000Z
|
lib/ui/screens/documents/document_create.dart
|
sknew93/flutter-crm
|
ab03fbcd1b513d8d9f118fdc86c4d2d07c91243c
|
[
"MIT"
] | null | null | null |
lib/ui/screens/documents/document_create.dart
|
sknew93/flutter-crm
|
ab03fbcd1b513d8d9f118fdc86c4d2d07c91243c
|
[
"MIT"
] | null | null | null |
import 'package:file_picker/file_picker.dart';
import 'package:flushbar/flushbar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:bottle_crm/bloc/contact_bloc.dart';
import 'package:bottle_crm/ui/widgets/bottom_navigation_bar.dart';
import 'package:bottle_crm/utils/utils.dart';
import 'package:flutter_svg/svg.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:bottle_crm/bloc/document_bloc.dart';
import 'package:multiselect_formfield/multiselect_formfield.dart';
class CreateDocument extends StatefulWidget {
CreateDocument();
@override
State createState() => _CreateDocumentState();
}
class _CreateDocumentState extends State<CreateDocument> {
final GlobalKey<FormState> _createDocumentFormKey = GlobalKey<FormState>();
FilePickerResult result;
PlatformFile file;
Map _errors;
bool _isLoading = false;
FocusNode _focuserr;
FocusNode _titleFocusNode = new FocusNode();
FocusNode _documentFocusNode = new FocusNode();
bool accessError = false;
@override
void initState() {
super.initState();
}
@override
void dispose() {
if (_focuserr != null) {
_focuserr.dispose();
}
_titleFocusNode.dispose();
_documentFocusNode.dispose();
super.dispose();
}
focusError() {
setState(() {
FocusManager.instance.primaryFocus.unfocus();
FocusScope.of(context).requestFocus(_focuserr);
});
}
_saveForm() async {
_focuserr = null;
setState(() {
_errors = null;
});
if (!_createDocumentFormKey.currentState.validate()) {
focusError();
return;
}
_createDocumentFormKey.currentState.save();
dynamic _result;
setState(() {
_isLoading = true;
});
if (documentBLoc.currentEditDocumentId != null) {
_result = await documentBLoc.editDocument(file);
} else {
_result = await documentBLoc.createDocument(file);
}
setState(() {
_isLoading = false;
});
if (_result['error'] == false) {
setState(() {
_errors = null;
});
showToast(_result['message']);
Navigator.pushReplacementNamed(context, '/documents');
} else if (_result['error'] == true) {
setState(() {
_errors = _result['errors'];
});
if (_errors['title'] != null && _focuserr == null) {
_focuserr = _titleFocusNode;
focusError();
}
} else {
setState(() {
_errors = null;
});
showErrorMessage(context, 'Something went wrong');
}
}
void showErrorMessage(BuildContext context, String errorContent) {
Flushbar(
backgroundColor: Colors.white,
messageText: Text(errorContent,
style:
GoogleFonts.robotoSlab(textStyle: TextStyle(color: Colors.red))),
isDismissible: false,
mainButton: TextButton(
child: Text('TRY AGAIN',
style: GoogleFonts.robotoSlab(
textStyle: TextStyle(color: Theme.of(context).accentColor))),
onPressed: () {
Navigator.of(context).pop(true);
_saveForm();
},
),
duration: Duration(seconds: 10),
)..show(context);
}
Widget _buildForm() {
return Container(
child: Form(
key: _createDocumentFormKey,
child: Column(children: [
Container(
child: Column(
children: [
Container(
alignment: Alignment.centerLeft,
margin: EdgeInsets.only(bottom: 5.0),
child: RichText(
text: TextSpan(
text: 'Title',
style: GoogleFonts.robotoSlab(
textStyle: TextStyle(
color:
Theme.of(context).secondaryHeaderColor,
fontWeight: FontWeight.w500,
fontSize: screenWidth / 25)),
children: <TextSpan>[
TextSpan(
text: '* ',
style: GoogleFonts.robotoSlab(
textStyle: TextStyle(color: Colors.red))),
TextSpan(
text: ': ', style: GoogleFonts.robotoSlab())
],
),
)),
Container(
margin: EdgeInsets.only(bottom: 10.0),
child: TextFormField(
focusNode: _titleFocusNode,
initialValue: documentBLoc.currentEditDocument['title'],
decoration: InputDecoration(
contentPadding: EdgeInsets.all(12.0),
enabledBorder: boxBorder(),
focusedErrorBorder: boxBorder(),
focusedBorder: boxBorder(),
errorBorder: boxBorder(),
fillColor: Colors.white,
filled: true,
hintText: 'Enter Title',
errorStyle: GoogleFonts.robotoSlab(),
hintStyle: GoogleFonts.robotoSlab(
textStyle: TextStyle(fontSize: 14.0))),
keyboardType: TextInputType.text,
validator: (value) {
if (value.isEmpty) {
if (_focuserr == null) {
_focuserr = _titleFocusNode;
}
return 'This field is required.';
}
return null;
},
onSaved: (value) {
documentBLoc.currentEditDocument['title'] = value;
},
),
),
_errors != null && _errors['title'] != null
? Container(
alignment: Alignment.centerLeft,
child: Text(
_errors['title'][0],
style: GoogleFonts.robotoSlab(
textStyle: TextStyle(
color: Colors.red[700], fontSize: 12.0)),
),
)
: Container(),
Divider(color: Colors.grey)
],
),
),
Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
alignment: Alignment.centerLeft,
margin: EdgeInsets.only(bottom: 5.0),
child: RichText(
text: TextSpan(
text: 'Upload Document',
style: GoogleFonts.robotoSlab(
textStyle: TextStyle(
color:
Theme.of(context).secondaryHeaderColor,
fontWeight: FontWeight.w500,
fontSize: screenWidth / 25)),
children: <TextSpan>[
TextSpan(
text: '* ',
style: GoogleFonts.robotoSlab(
textStyle: TextStyle(color: Colors.red))),
TextSpan(
text: ': ', style: GoogleFonts.robotoSlab())
],
),
)),
GestureDetector(
onTap: () async {
FocusScope.of(context).unfocus();
result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: [
'pdf',
'doc',
'docx',
'csv',
'txt',
'xlsx',
'ppt',
'pptx',
'gdoc'
]);
setState(() {
file = result.files.first;
});
},
child: Container(
color: bottomNavBarTextColor,
padding: EdgeInsets.symmetric(
vertical: 10.0, horizontal: 20.0),
child: Text(
"Choose File",
style: GoogleFonts.robotoSlab(
textStyle: TextStyle(color: Colors.white)),
),
),
),
file != null
? Container(
margin: EdgeInsets.fromLTRB(5, 0, 0, 0),
child: Text(
file.name,
style: GoogleFonts.robotoSlab(),
),
)
: Container(
margin: EdgeInsets.fromLTRB(5, 0, 0, 0),
child: Text(
(documentBLoc.currentEditDocumentId == null)
? "No file chosen."
: (documentBLoc
.currentEditDocument['document_file']
.split('/')
.last),
style: GoogleFonts.robotoSlab(),
),
),
Divider(color: Colors.grey),
Container(
child: Column(
children: [
Container(
alignment: Alignment.centerLeft,
margin: EdgeInsets.only(bottom: 5.0),
child: Text(
'Teams :',
style: GoogleFonts.robotoSlab(
textStyle: TextStyle(
color: Theme.of(context)
.secondaryHeaderColor,
fontWeight: FontWeight.w500,
fontSize: screenWidth / 25)),
),
),
Container(
margin: EdgeInsets.only(bottom: 5.0),
child: MultiSelectFormField(
border: boxBorder(),
fillColor: Colors.white,
autovalidate: false,
dataSource: contactBloc.teamsObjForDropdown,
textField: 'name',
valueField: 'id',
okButtonLabel: 'OK',
chipLabelStyle: GoogleFonts.robotoSlab(
textStyle: TextStyle(color: Colors.black)),
dialogTextStyle: GoogleFonts.robotoSlab(),
cancelButtonLabel: 'CANCEL',
hintWidget: Text("Please choose one or more",
style: GoogleFonts.robotoSlab(
textStyle:
TextStyle(color: Colors.grey))),
title: Text(
"Teams",
style: GoogleFonts.robotoSlab(),
),
initialValue:
documentBLoc.currentEditDocument['teams'],
onSaved: (value) {
if (value == null) return;
documentBLoc.currentEditDocument['teams'] =
value;
},
),
),
Divider(color: Colors.grey),
Container(
child: Column(
children: [
Container(
alignment: Alignment.centerLeft,
margin: EdgeInsets.only(bottom: 5.0),
child: Text(
'Share To :',
style: GoogleFonts.robotoSlab(
textStyle: TextStyle(
color: Theme.of(context)
.secondaryHeaderColor,
fontWeight: FontWeight.w500,
fontSize: screenWidth / 25)),
),
),
Container(
margin: EdgeInsets.only(bottom: 5.0),
child: MultiSelectFormField(
border: boxBorder(),
fillColor: Colors.white,
autovalidate: false,
dataSource:
documentBLoc.usersObjforMultiselect,
textField: 'name',
valueField: 'id',
okButtonLabel: 'OK',
chipLabelStyle: GoogleFonts.robotoSlab(
textStyle:
TextStyle(color: Colors.black)),
dialogTextStyle: GoogleFonts.robotoSlab(),
cancelButtonLabel: 'CANCEL',
hintWidget: Text(
"Please choose one or more",
style: GoogleFonts.robotoSlab(
textStyle:
TextStyle(color: Colors.grey))),
title: Text(
"Share To",
style: GoogleFonts.robotoSlab(),
),
initialValue: documentBLoc
.currentEditDocument['shared_to'],
onSaved: (value) {
if (value == null) return;
documentBLoc.currentEditDocument[
'shared_to'] = value;
},
),
),
Divider(color: Colors.grey),
],
),
),
(documentBLoc.currentEditDocumentId != null)
? Container(
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Container(
alignment: Alignment.centerLeft,
margin: EdgeInsets.only(bottom: 5.0),
child: Text(
'Status :',
style: GoogleFonts.robotoSlab(
textStyle: TextStyle(
color: Theme.of(context)
.secondaryHeaderColor,
fontWeight: FontWeight.w500,
fontSize: screenWidth / 25)),
),
),
Container(
height: 48.0,
margin: EdgeInsets.only(bottom: 5.0),
child: DropdownButtonFormField(
decoration: InputDecoration(
border: boxBorder(),
contentPadding:
EdgeInsets.all(12.0)),
style: GoogleFonts.robotoSlab(
textStyle: TextStyle(
color: Colors.black)),
hint: Text('Select Status'),
value: documentBLoc
.currentEditDocument['status'],
onChanged: (value) {
documentBLoc.currentEditDocument[
'status'] = value;
},
items: ['active', 'inactive']
.map((item) {
return DropdownMenuItem(
child: new Text(item),
value: item,
);
}).toList(),
),
),
Divider(color: Colors.grey)
],
),
)
: Container(),
],
),
),
// Save Form
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
GestureDetector(
onTap: () {
FocusScope.of(context).unfocus();
_saveForm();
},
child: Container(
alignment: Alignment.center,
height: screenHeight * 0.06,
width: screenWidth * 0.5,
decoration: BoxDecoration(
color: submitButtonColor,
borderRadius:
BorderRadius.all(Radius.circular(3.0)),
),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceAround,
children: [
Text(
documentBLoc.currentEditDocumentId == null
? 'Create Document'
: 'Edit Document',
style: GoogleFonts.robotoSlab(
textStyle: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w500,
fontSize: screenWidth / 24)),
),
SvgPicture.asset(
'assets/images/arrow_forward.svg')
],
),
),
),
GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: Container(
child: Text(
"Cancel",
style: GoogleFonts.robotoSlab(
textStyle: TextStyle(
decoration: TextDecoration.underline,
color: bottomNavBarTextColor,
fontSize: screenWidth / 24)),
),
),
)
],
),
)
],
),
),
])));
}
@override
Widget build(BuildContext context) {
Widget loadingIndicator = _isLoading
? new Container(
color: Colors.transparent,
width: 300.0,
height: 300.0,
child: new Padding(
padding: const EdgeInsets.all(5.0),
child: new Center(child: new CircularProgressIndicator())),
)
: new Container();
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text(
'Create Document',
style: GoogleFonts.robotoSlab(),
),
),
body: Stack(
fit: StackFit.expand,
children: [
SingleChildScrollView(
padding: EdgeInsets.all(10.0),
child: Container(
color: Colors.white,
child: Container(
padding: EdgeInsets.all(10.0),
child: _buildForm(),
),
),
),
new Align(
child: loadingIndicator,
alignment: FractionalOffset.center,
),
],
),
bottomNavigationBar: BottomNavigationBarWidget());
}
}
| 43.608939
| 80
| 0.350457
|
40b7cdfcfb79bc3c3c9d9b64e972abe15b540e7b
| 6,996
|
rb
|
Ruby
|
spec/requests/inter_team_trade_groups_spec.rb
|
djstozza/fpl_app_api
|
0efb35bda9657d9acfe5d7b8738b751c41d6e74e
|
[
"MIT"
] | 1
|
2021-02-18T14:08:16.000Z
|
2021-02-18T14:08:16.000Z
|
spec/requests/inter_team_trade_groups_spec.rb
|
djstozza/fpl_app_api
|
0efb35bda9657d9acfe5d7b8738b751c41d6e74e
|
[
"MIT"
] | null | null | null |
spec/requests/inter_team_trade_groups_spec.rb
|
djstozza/fpl_app_api
|
0efb35bda9657d9acfe5d7b8738b751c41d6e74e
|
[
"MIT"
] | null | null | null |
require 'rails_helper'
RSpec.describe "InterTeamTradeGroups", type: :request do
describe "create" do
it "is valid" do
user = FactoryBot.create(:user)
auth_headers = user.create_new_auth_token
round = FactoryBot.create(:round, is_current: true, deadline_time: 1.day.from_now)
league = FactoryBot.create(:league)
out_fpl_team = FactoryBot.create(:fpl_team, league: league, user: user)
out_fpl_team_list = FactoryBot.create(:fpl_team_list, fpl_team: out_fpl_team, round: round)
out_list_position = FactoryBot.create(:list_position, fpl_team_list: out_fpl_team_list)
out_fpl_team.players << out_list_position.player
in_fpl_team = FactoryBot.create(:fpl_team, league: league)
in_fpl_team_list = FactoryBot.create(:fpl_team_list, fpl_team: in_fpl_team)
in_list_position = FactoryBot.create(:list_position, fpl_team_list: in_fpl_team_list)
in_fpl_team.players << in_list_position.player
post api_v1_inter_team_trade_groups_path(
fpl_team_id: out_fpl_team.id,
fpl_team_list_id: out_fpl_team_list.id,
out_list_position_id: out_list_position.id,
in_list_position_id: in_list_position.id,
), headers: auth_headers
expect(response).to have_http_status(200)
expected = FplTeamLists::Hash.run(
fpl_team_list: out_fpl_team_list,
user: user,
show_trade_groups: true,
user_owns_fpl_team: true,
).result
expected[:success] =
"Successfully created a pending trade - Fpl Team: #{in_fpl_team.name}, " \
"Out: #{out_list_position.player.decorate.name} In: #{in_list_position.player.decorate.name}."
expect(response.body).to eq(expected.to_json)
end
it "responds with 422 if invalid" do
user = FactoryBot.create(:user)
auth_headers = user.create_new_auth_token
round = FactoryBot.create(:round, is_current: false)
league = FactoryBot.create(:league)
out_fpl_team = FactoryBot.create(:fpl_team, league: league, user: user)
out_fpl_team_list = FactoryBot.create(:fpl_team_list, fpl_team: out_fpl_team, round: round)
out_list_position = FactoryBot.create(:list_position, fpl_team_list: out_fpl_team_list)
out_fpl_team.players << out_list_position.player
in_fpl_team = FactoryBot.create(:fpl_team, league: league)
in_fpl_team_list = FactoryBot.create(:fpl_team_list, fpl_team: in_fpl_team)
in_list_position = FactoryBot.create(:list_position, fpl_team_list: in_fpl_team_list)
in_fpl_team.players << in_list_position.player
params = {
fpl_team_id: out_fpl_team.id,
fpl_team_list_id: out_fpl_team_list.id,
out_list_position_id: out_list_position.id,
in_list_position_id: in_list_position.id,
}
post api_v1_inter_team_trade_groups_path(params), headers: auth_headers
outcome = InterTeamTradeGroups::Create.run(params.merge(user: user))
expected = outcome.fpl_team_list_hash.merge(error: outcome.errors)
expect(response).to have_http_status(422)
expect(response.body).to eq(expected.to_json)
end
end
describe "update" do
it "is valid" do
user = FactoryBot.create(:user)
auth_headers = user.create_new_auth_token
round = FactoryBot.create(:round, is_current: true, deadline_time: 1.day.from_now)
league = FactoryBot.create(:league)
out_fpl_team = FactoryBot.create(:fpl_team, league: league, user: user)
out_fpl_team_list = FactoryBot.create(:fpl_team_list, fpl_team: out_fpl_team, round: round)
out_list_position = FactoryBot.create(:list_position, fpl_team_list: out_fpl_team_list)
in_fpl_team = FactoryBot.create(:fpl_team, league: league)
in_fpl_team_list = FactoryBot.create(:fpl_team_list, fpl_team: in_fpl_team)
in_list_position = FactoryBot.create(:list_position, fpl_team_list: in_fpl_team_list)
out_fpl_team.players << out_list_position.player
in_fpl_team.players << in_list_position.player
inter_team_trade_group = FactoryBot.create(
:inter_team_trade_group,
out_fpl_team_list: out_fpl_team_list,
in_fpl_team_list: in_fpl_team_list,
league: league,
round: round,
)
FactoryBot.create(
:inter_team_trade,
inter_team_trade_group: inter_team_trade_group,
out_player: out_list_position.player,
in_player: in_list_position.player,
)
put api_v1_inter_team_trade_group_path(
fpl_team_list_id: out_fpl_team_list.id,
inter_team_trade_group_id: inter_team_trade_group.id,
trade_action: 'submit',
), headers: auth_headers
expect(response).to have_http_status(200)
expected = FplTeamLists::Hash.run(
fpl_team_list: out_fpl_team_list,
user: user,
show_trade_groups: true,
user_owns_fpl_team: true,
).result
expected[:success] = 'This trade proposal has successfully submitted'
expect(response.body).to eq(expected.to_json)
end
it "is valid" do
user = FactoryBot.create(:user)
auth_headers = user.create_new_auth_token
round = FactoryBot.create(:round, is_current: false)
league = FactoryBot.create(:league)
out_fpl_team = FactoryBot.create(:fpl_team, league: league, user: user)
out_fpl_team_list = FactoryBot.create(:fpl_team_list, fpl_team: out_fpl_team, round: round)
out_list_position = FactoryBot.create(:list_position, fpl_team_list: out_fpl_team_list)
in_fpl_team = FactoryBot.create(:fpl_team, league: league)
in_fpl_team_list = FactoryBot.create(:fpl_team_list, fpl_team: in_fpl_team)
in_list_position = FactoryBot.create(:list_position, fpl_team_list: in_fpl_team_list)
out_fpl_team.players << out_list_position.player
in_fpl_team.players << in_list_position.player
inter_team_trade_group = FactoryBot.create(
:inter_team_trade_group,
out_fpl_team_list: out_fpl_team_list,
in_fpl_team_list: in_fpl_team_list,
league: league,
round: round,
)
FactoryBot.create(
:inter_team_trade,
inter_team_trade_group: inter_team_trade_group,
out_player: out_list_position.player,
in_player: in_list_position.player,
)
params = {
fpl_team_list_id: out_fpl_team_list.id,
inter_team_trade_group_id: inter_team_trade_group.id,
trade_action: 'submit',
}
put api_v1_inter_team_trade_group_path(params), headers: auth_headers
expect(response).to have_http_status(422)
outcome = InterTeamTradeGroups::Submit.run(params.merge(user: user))
expected = FplTeamLists::Hash.run(
fpl_team_list: out_fpl_team_list,
user: user,
show_trade_groups: true,
user_owns_fpl_team: true,
).result
expected[:error] = outcome.errors
expect(response.body).to eq(expected.to_json)
end
end
end
| 35.876923
| 104
| 0.710692
|
e77c7c2ef5b778e7815f345ffee4999d8d788d67
| 3,456
|
php
|
PHP
|
PHP Projects/SugarCRM/cache/modules/Tasks/language/en_us.lang.php
|
YouCodeSchool/php-interview-questions
|
bf21d77f9c3bac8ccfdf99bf741fdb4d2900d0a9
|
[
"MIT"
] | 90
|
2020-04-16T20:24:23.000Z
|
2022-03-29T07:08:01.000Z
|
PHP Projects/SugarCRM/cache/modules/Tasks/language/en_us.lang.php
|
YouCodeSchool/php-interview-questions
|
bf21d77f9c3bac8ccfdf99bf741fdb4d2900d0a9
|
[
"MIT"
] | 1
|
2022-02-17T04:10:48.000Z
|
2022-02-17T04:10:48.000Z
|
SugarCRM/cache/modules/Tasks/language/en_us.lang.php
|
modulardata/php-interview-questions
|
a62dc53026fd3151b6410e8dbd212c1ceefab41d
|
[
"MIT"
] | 36
|
2020-03-19T20:05:23.000Z
|
2022-03-24T08:35:55.000Z
|
<?php
// created: 2012-12-06 17:25:15
$mod_strings = array (
'LBL_ID' => 'ID',
'LBL_DATE_ENTERED' => 'Date Created',
'LBL_DATE_MODIFIED' => 'Date Modified',
'LBL_MODIFIED' => 'Modified By',
'LBL_MODIFIED_ID' => 'Modified By Id',
'LBL_MODIFIED_NAME' => 'Modified By Name',
'LBL_CREATED' => 'Created By',
'LBL_CREATED_ID' => 'Created By Id',
'LBL_DESCRIPTION' => 'Description:',
'LBL_DELETED' => 'Deleted',
'LBL_NAME' => 'Name:',
'LBL_CREATED_USER' => 'Created by User',
'LBL_MODIFIED_USER' => 'Modified by User',
'LBL_LIST_NAME' => 'Name',
'LBL_EDIT_BUTTON' => 'Edit',
'LBL_REMOVE' => 'Remove',
'LBL_ASSIGNED_TO_ID' => 'Assigned User Id',
'LBL_ASSIGNED_TO_NAME' => 'Assigned to:',
'LBL_MODULE_NAME' => 'Tasks',
'LBL_TASK' => 'Tasks: ',
'LBL_MODULE_TITLE' => ' Tasks: Home',
'LBL_SEARCH_FORM_TITLE' => ' Task Search',
'LBL_LIST_FORM_TITLE' => ' Task List',
'LBL_NEW_FORM_TITLE' => ' Create Task',
'LBL_NEW_FORM_SUBJECT' => 'Subject:',
'LBL_NEW_FORM_DUE_DATE' => 'Due Date:',
'LBL_NEW_FORM_DUE_TIME' => 'Due Time:',
'LBL_NEW_TIME_FORMAT' => '(24:00)',
'LBL_LIST_CLOSE' => 'Close',
'LBL_LIST_SUBJECT' => 'Subject',
'LBL_LIST_CONTACT' => 'Contact',
'LBL_LIST_PRIORITY' => 'Priority',
'LBL_LIST_RELATED_TO' => 'Related to',
'LBL_LIST_DUE_DATE' => 'Due Date',
'LBL_LIST_DUE_TIME' => 'Due Time',
'LBL_SUBJECT' => 'Subject:',
'LBL_STATUS' => 'Status:',
'LBL_DUE_DATE' => 'Due Date:',
'LBL_DUE_TIME' => 'Due Time:',
'LBL_PRIORITY' => 'Priority:',
'LBL_COLON' => ':',
'LBL_DUE_DATE_AND_TIME' => 'Due Date & Time:',
'LBL_START_DATE_AND_TIME' => 'Start Date & Time:',
'LBL_START_DATE' => 'Start Date:',
'LBL_LIST_START_DATE' => 'Start Date',
'LBL_START_TIME' => 'Start Time:',
'LBL_LIST_START_TIME' => 'Start Time',
'DATE_FORMAT' => '(yyyy-mm-dd)',
'LBL_NONE' => 'None',
'LBL_CONTACT' => 'Contact:',
'LBL_EMAIL_ADDRESS' => 'Email Address:',
'LBL_PHONE' => 'Phone:',
'LBL_EMAIL' => 'Email Address:',
'LBL_DESCRIPTION_INFORMATION' => 'Description Information',
'LBL_CONTACT_NAME' => 'Contact Name ',
'LBL_LIST_COMPLETE' => 'Complete:',
'LBL_LIST_STATUS' => 'Status',
'LBL_DATE_DUE_FLAG' => 'No Due Date',
'LBL_DATE_START_FLAG' => 'No Start Date',
'ERR_DELETE_RECORD' => 'You must specify a record number to delete the contact.',
'ERR_INVALID_HOUR' => 'Please enter an hour between 0 and 24',
'LBL_DEFAULT_PRIORITY' => 'Medium',
'LBL_LIST_MY_TASKS' => 'My Open Tasks',
'LNK_NEW_TASK' => 'Create Task',
'LNK_TASK_LIST' => 'View Tasks',
'LNK_IMPORT_TASKS' => 'Import Tasks',
'LBL_CONTACT_FIRST_NAME' => 'Contact First Name',
'LBL_CONTACT_LAST_NAME' => 'Contact Last Name',
'LBL_LIST_ASSIGNED_TO_NAME' => 'Assigned User',
'LBL_LIST_DATE_MODIFIED' => 'Date Modified',
'LBL_CONTACT_ID' => 'Contact ID:',
'LBL_PARENT_ID' => 'Parent ID:',
'LBL_CONTACT_PHONE' => 'Contact Phone:',
'LBL_PARENT_NAME' => 'Parent Type:',
'LBL_ACTIVITIES_REPORTS' => 'Activities Report',
'LBL_TASK_INFORMATION' => 'Overview',
'LBL_EDITLAYOUT' => 'Edit Layout',
'LBL_HISTORY_SUBPANEL_TITLE' => 'Notes',
'LBL_DATE_DUE' => 'Date Due',
'LBL_EXPORT_ASSIGNED_USER_NAME' => 'Assigned User Name',
'LBL_EXPORT_ASSIGNED_USER_ID' => 'Assigned User ID',
'LBL_EXPORT_MODIFIED_USER_ID' => 'Modified By ID',
'LBL_EXPORT_CREATED_BY' => 'Created By ID',
'LBL_EXPORT_PARENT_TYPE' => 'Related To Module',
'LBL_EXPORT_PARENT_ID' => 'Related To ID',
);
| 38.831461
| 83
| 0.659144
|
299f6ba258549f872d303c57c6db3de6619918be
| 1,177
|
dart
|
Dart
|
test/domain/usecases/get_account_balance_usecase_test.dart
|
RemeJuan/investec_open_api_dart
|
9d8a551aebcc575d9ad9eaf871513617daa2cec2
|
[
"MIT"
] | null | null | null |
test/domain/usecases/get_account_balance_usecase_test.dart
|
RemeJuan/investec_open_api_dart
|
9d8a551aebcc575d9ad9eaf871513617daa2cec2
|
[
"MIT"
] | 1
|
2021-03-14T04:56:43.000Z
|
2021-03-14T04:56:43.000Z
|
test/domain/usecases/get_account_balance_usecase_test.dart
|
RemeJuan/investec_open_api_dart
|
9d8a551aebcc575d9ad9eaf871513617daa2cec2
|
[
"MIT"
] | null | null | null |
import 'package:investec_open_api/domain/repositories/account_balance_repository.dart';
import 'package:investec_open_api/domain/usecases/get_account_balance_usecase.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:test/test.dart';
import '../../fixtures/account_balance/account_balance_fixture.dart';
import 'get_account_balance_usecase_test.mocks.dart';
@GenerateMocks([AccountBalanceRepository])
void main() {
late GetAccountBalanceUseCase useCase;
late MockAccountBalanceRepository mockRepository;
setUp(() {
mockRepository = MockAccountBalanceRepository();
useCase = GetAccountBalanceUseCase(mockRepository);
});
test('should get account details from repository', () async {
const mockAccountId = 'mock-account-id';
//arrange
when(mockRepository.getBalance(mockAccountId)).thenAnswer(
(_) async => accountBalanceFixture,
);
//act
final result = await useCase(GetAccountBalanceParams(mockAccountId));
//assert
expect(result, accountBalanceFixture);
verify(mockRepository.getBalance(mockAccountId));
verifyNoMoreInteractions(mockRepository);
});
}
| 34.617647
| 87
| 0.772302
|
f6fcb257d73f69cd6ade3a92c53d79789f15ae32
| 738
|
dart
|
Dart
|
lib/property_grid.dart
|
coderespawn/dart-property-grid
|
c6bd0da5b32e5b23331248b9edc8781c00ffb1b0
|
[
"BSD-3-Clause"
] | 5
|
2015-06-01T18:22:20.000Z
|
2020-04-28T03:22:27.000Z
|
lib/property_grid.dart
|
coderespawn/dart-property-grid
|
c6bd0da5b32e5b23331248b9edc8781c00ffb1b0
|
[
"BSD-3-Clause"
] | null | null | null |
lib/property_grid.dart
|
coderespawn/dart-property-grid
|
c6bd0da5b32e5b23331248b9edc8781c00ffb1b0
|
[
"BSD-3-Clause"
] | 4
|
2015-06-18T10:45:46.000Z
|
2021-02-10T13:43:57.000Z
|
library property_grid;
import 'dart:html';
import 'dart:async';
import 'package:gradient_picker/gradient_picker.dart';
import 'package:color_picker/color_picker.dart';
part 'property_grid_lib.dart';
part 'property_grid_model.dart';
part 'property_item.dart';
part 'property_item_controller.dart';
part 'property_item_view.dart';
part 'property_item_editor.dart';
part 'editors/editor_color.dart';
part 'editors/editor_gradient.dart';
part 'editors/editor_slider.dart';
part 'editors/editor_spinner.dart';
part 'editors/editor_textbox.dart';
part 'editors/editor_browse.dart';
part 'utils/property_grid_utils.dart';
part 'views/view_color.dart';
part 'views/view_gradient.dart';
part 'views/view_label.dart';
part 'widgets/slider.dart';
| 29.52
| 54
| 0.802168
|
cd8c2b90c8ef59ecabb039ce9c388e370483c74c
| 490
|
cs
|
C#
|
src/DataProtection/DataProtection/src/Repositories/IDefaultKeyStorageDirectory.cs
|
MCCshreyas/aspnetcore
|
132c2315ea435d1c20e00fa6cc80a0dfc548ff4c
|
[
"MIT"
] | 8,570
|
2018-10-09T21:50:10.000Z
|
2020-01-07T21:08:56.000Z
|
src/DataProtection/DataProtection/src/Repositories/IDefaultKeyStorageDirectory.cs
|
MCCshreyas/aspnetcore
|
132c2315ea435d1c20e00fa6cc80a0dfc548ff4c
|
[
"MIT"
] | 13,668
|
2018-10-10T00:13:51.000Z
|
2020-01-07T21:01:12.000Z
|
src/DataProtection/DataProtection/src/Repositories/IDefaultKeyStorageDirectory.cs
|
stefannikolei/AspNetCore
|
b55573c8a5195836bfcc77730b80c460588b70b4
|
[
"MIT"
] | 2,679
|
2018-10-10T03:53:59.000Z
|
2020-01-07T14:57:11.000Z
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.IO;
namespace Microsoft.AspNetCore.DataProtection.Repositories;
/// <summary>
/// This interface enables overridding the default storage location of keys on disk
/// </summary>
internal interface IDefaultKeyStorageDirectories
{
DirectoryInfo? GetKeyStorageDirectory();
DirectoryInfo? GetKeyStorageDirectoryForAzureWebSites();
}
| 28.823529
| 83
| 0.787755
|
258af9b43e223cd250d8e80c36e61d733b5135cc
| 2,070
|
js
|
JavaScript
|
commands/Music/queue.js
|
1z3ngero/codename_yey
|
35666206d8b8eb650b325397f63666f327b4326f
|
[
"MIT"
] | 25
|
2020-07-25T07:57:58.000Z
|
2021-08-24T18:43:45.000Z
|
commands/Music/queue.js
|
GDRadio/codename_yey
|
35666206d8b8eb650b325397f63666f327b4326f
|
[
"MIT"
] | 4
|
2020-11-01T15:30:31.000Z
|
2021-05-03T10:54:48.000Z
|
commands/Music/queue.js
|
GDRadio/codename_yey
|
35666206d8b8eb650b325397f63666f327b4326f
|
[
"MIT"
] | 4
|
2020-05-27T04:12:19.000Z
|
2020-12-06T21:46:07.000Z
|
const ReactionHandler = require("../../core/ReactionHandler");
const parseTime = require("../../utils/parseTime");
module.exports = {
name: "queue",
group: "music",
description: "queueDescription",
aliases: [ "q" ],
async run(client, msg, args, prefix) {
const player = client.lavalinkManager.players.get(msg.guild.id);
if (!player) {
return msg.reply(msg.t("notPlaying"));
}
const embed = {
title: msg.t("trackQueue"),
color: await msg.author.embColor(),
};
const fields = [];
let index = 0;
for (const track of player.queue) {
fields.push({
name: `${++index}: ${track.title}`,
value: msg.t("durationRequestedBy", parseTime(Math.floor(track.duration / 1000)), track.requester.tag),
});
}
if (!fields.length) {
return msg.reply(msg.t("queueIsEmpty"));
}
if (fields.length > 10) {
const pages = [];
while (fields.length) {
const arr = []
for (const field of fields.splice(0, 10)) {
arr.push(field);
}
pages.push(arr);
}
let pageNumber = 0;
embed.fields = pages[pageNumber];
embed.footer = { text: msg.t("queueFooter", pageNumber + 1, pages.length) };
const message = await msg.reply({ embed });
message.addReaction("◀️");
message.addReaction("▶️");
const reactionHandler = new ReactionHandler(message, u => u == msg.author.id, 300000);
reactionHandler.on("reaction", (msg, emoji) => {
switch (emoji.name) {
case "◀️":
if (pageNumber === 0) return;
pageNumber--;
break;
case "▶️":
if (pageNumber === (pages.length - 1)) return;
pageNumber++;
break;
default: return;
}
embed.fields = pages[pageNumber];
embed.footer = { text: msg.t("queueFooter", pageNumber + 1, pages.length) };
message.edit({ embed });
});
} else {
embed.fields = fields;
await msg.reply({ embed });
}
}
}
| 27.236842
| 111
| 0.543961
|
dba42870cfd1f2d172fa74d896a7c52435e3843e
| 284
|
php
|
PHP
|
roomresponsive1/application/views/admin/admin_footer.php
|
rajat-malhotra/Where-to-Live
|
36378049aeb10e47c812920283dc68cfb216947a
|
[
"Apache-2.0"
] | null | null | null |
roomresponsive1/application/views/admin/admin_footer.php
|
rajat-malhotra/Where-to-Live
|
36378049aeb10e47c812920283dc68cfb216947a
|
[
"Apache-2.0"
] | null | null | null |
roomresponsive1/application/views/admin/admin_footer.php
|
rajat-malhotra/Where-to-Live
|
36378049aeb10e47c812920283dc68cfb216947a
|
[
"Apache-2.0"
] | null | null | null |
<!DOCTYPE html>
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.js">
</script>
<script src="<?= base_url('assets/js/bootstrap.min.js'); ?>"></script>
</body>
</html>
| 35.5
| 76
| 0.68662
|
5decf23567abe79738db2ccd0ab8f389a42e1458
| 1,600
|
hpp
|
C++
|
algorithms/kruskal.hpp
|
EMACC99/graph_visualizer
|
79291c2365c139d846b67698c2b983d22b670f6c
|
[
"MIT"
] | null | null | null |
algorithms/kruskal.hpp
|
EMACC99/graph_visualizer
|
79291c2365c139d846b67698c2b983d22b670f6c
|
[
"MIT"
] | 1
|
2021-03-16T20:13:58.000Z
|
2021-03-17T01:04:08.000Z
|
algorithms/kruskal.hpp
|
EMACC99/graph_visualizer
|
79291c2365c139d846b67698c2b983d22b670f6c
|
[
"MIT"
] | null | null | null |
#pragma once
#include <vector>
#include <algorithm>
#include "../includes/node.hpp"
#include "../includes/edge.hpp"
#include "../includes/globals.hpp"
// int raiz(const int &u, const std::vector<int> &padres){
// if (padres[u] != -1)
// return raiz(padres[u], padres);
// return u;
// }
/**
* @brief check the root of two nodes and meke them the sema as they are in the same conex component (disjoint sets)
*
* @param u
* @param padres
* @return int
*/
int raiz(const int &u, std::vector<int> & padres){
int p = padres[u];
if (p == -1)
return u;
else{
int r = raiz(p,padres);
padres[u] = r;
return r;
}
}
/**
* @brief join the roots of two given nodes
*
* @param u
* @param v
* @param padres
*/
void juntar(const int &u, const int &v, std::vector<int> &padres){
padres[raiz(u, padres)] = raiz(v, padres);
}
/**
* @brief executes de mst kruskal
*
* @return std::vector<edge>
*/
std::vector<edge> kusrkal(){
std::vector<edge> arbol;
std::vector<edge> kruskal_aristas = aristas;
std::sort(kruskal_aristas.begin(), kruskal_aristas.end(), compare()); //las ordenamos por peso
std::vector<int> padres (vertices.size());
for (auto &elem : padres)
elem = -1;
int u,v;
for (int i = 0; i < kruskal_aristas.size(); ++i){
u = kruskal_aristas[i].nodes[0];
v = kruskal_aristas[i].nodes[1];
if (raiz(u,padres) != raiz(v, padres)){
arbol.push_back(kruskal_aristas[i]);
juntar(u,v,padres);
}
}
return arbol;
}
| 24.242424
| 116
| 0.575
|
dbf1ddb78104912d817267f5b933ffe4889c7c28
| 4,919
|
php
|
PHP
|
web/Obrero/033/033_03_Posada.php
|
dww-circle/sw-d8
|
928881308e9f175d681cd0050deacbb22ecd5bb7
|
[
"MIT"
] | null | null | null |
web/Obrero/033/033_03_Posada.php
|
dww-circle/sw-d8
|
928881308e9f175d681cd0050deacbb22ecd5bb7
|
[
"MIT"
] | 2
|
2021-05-08T22:38:12.000Z
|
2022-02-10T17:50:38.000Z
|
web/Obrero/033/033_03_Posada.php
|
ISO-tech/sw-d8
|
928881308e9f175d681cd0050deacbb22ecd5bb7
|
[
"MIT"
] | null | null | null |
<html>
<head>
<title>
Un perdón de facto para un terrorista
</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>
</head>
<body bgcolor="#FFFFCC" text="000000" link="990000" vlink="660000" alink="003366" leftmargin="0" topmargin="0">
<table width="744" cellspacing="0" cellpadding="0" border="0">
<tr><td width="474"><a name="Top"></a><?php include "../../legacy-includes/TopLogo.htmlf" ?></td>
<td width="270"><?php include "../../legacy-includes/TopAd.htmlf" ?>
</td></tr></table>
<table width="744" cellspacing="0" cellpadding="0" border="0">
<tr><td width="18" bgcolor="FFCC66"></td>
<td width="108" bgcolor="FFCC66" valign=top><?php include "../../legacy-includes/LeftButtons.htmlf" ?></td>
<td width="18"></td>
<td width="480" valign="top">
<?php include "../../legacy-includes/BodyInsert.htmlf" ?>
<font face="Times New Roman, Times, serif" size="5"><b>El caso Posada Carriles: Un perdón <i>de facto</i> para un terrorista</b></font><p>
<font face="Times New Roman, Times, serif" size="2"><b>Por Nicole Colson</b></font><font face="Arial, Helvetica, sans-serif" size="2"> | junio-julio de 2007 | página 3</font><p>
<font face="Times New Roman, Times, serif" size="3">CUÁNDO UN terrorista no es terrorista? Cuándo él es un aliado y un operativo del gobierno de EE.UU. En mayo, una juez en EE.UU. desechó los cargos de violacion a la ley de inmigración contra el exiliado cubano derechista Luis Posada Carriles, notorio por su papel en la explosión de un avión comercial cubano en octubre de 1976, donde murieron 73 personas.<p>
Posada Carriles está confeso también de otro atentado de bomba en un hotel en la Habana en los años noventa, y es conocido por haber estado en la nómina de la CIA durante la mayoría de los 1960 hasta los principios de los 1970.<p>
En 1998, se jactó a la <i>New York Times</i> que él pagó a un mercenario salvadoreño por colocar una bomba en el Hotel Copacabana de La Habana. La explosión mató a un turista italiano.<p>
Documentos de la CIA, recientemente desclasificados, indentifican a Posada y Orlando Bosch como los cerebros detrás del complot, citando una reunión entre los dos en Venezuela que ocurrió apenas antes del bombardeo. Posada se escapó de una prisión venezolana en 1985, sin embargo, antes de que su juicio civil se completara.<p>
En el 2005, después de ser perdonado en Panamá por un complot para asesinar a Fidel Castro --como un favor a la administración Bush-- Posada Carriles entró a EEUU a hurtadillas. Luego, fue arrestado y se le acusó de violaciones de la ley migratoria.<p>
Los tribunales estadounidenes rechazaron los pedidos de estradición tanto por Cuba como por Venezuela, sosteniendo que Posada sería torturado si se le mandaran a cualquier país, una grosera aserción viniendo del administrador de las prisiones de Guantánamo, Bagram y Abu Ghraib.<p>
El juicio a Posada Carriles estaba a punto de comenzar en mayo cuando la jueza Kathleen Cardone desechó los cargos y liberó a Posadas, opinando que en su prosecución el gobierno había utilizado "fraude y engaño" para construir su caso.<p>
Por ejemplo, que Posada, quien habla inglés, no contón con la traducción apropiada durante su entrevista inicial después de su arresto, era inapropiada y causó un "malentendido". Ni los tribunales ni la administración Bush han tomado el mismo cautela con los derechos de los más de 221,000 indocumentados que fueron deportados por Immigration and Customs Enforcement (ICE, por sus siglas en inglés) el año pasado.<p>
El verdadero crimen aquí es que un terrorista como Posada Carriles le sea permitido caminar en libertad --mientras que los indocumentados viven bajo el temor constante de ser deportados y separados de sus familias.<p>
Así como lo pusiera Albor Ruiz, columnista de New York Daily News: "Mientras miles de inmigrantes pobres, decentes, y trabajadores son encarcelados en condiciones terribles, Luis Posada Carriles, un hombre peligroso que tiene un largo protuario criminal y con una orden de deportación pendiente, fue liberado . . . A medida que cientos de familias inmigrantes son destruidas despiadamente por las redadas y deportaciones, per a este hombre deshonesto lo mandaron a su hogar, su esposa y sus niños."<p>
<i>Traducido por Lance Selfa</i><p>
<?php include "../../legacy-includes/BottomNavLinksObrero.htmlf" ?>
<td width="12"></td>
<td width="108" valign="top">
<?php include "../../legacy-includes/RightAdObrero.htmlf" ?>
</td>
</tr>
</table>
</body>
</html>
| 87.839286
| 522
| 0.754015
|
3843c1e46f11a39b477826e44b7d84c6f212635d
| 19,519
|
php
|
PHP
|
resources/views/admin/tour/create.blade.php
|
pritom-dip/taxitour
|
dd00d93b919b7751bff961816545467b048033da
|
[
"MIT"
] | null | null | null |
resources/views/admin/tour/create.blade.php
|
pritom-dip/taxitour
|
dd00d93b919b7751bff961816545467b048033da
|
[
"MIT"
] | null | null | null |
resources/views/admin/tour/create.blade.php
|
pritom-dip/taxitour
|
dd00d93b919b7751bff961816545467b048033da
|
[
"MIT"
] | null | null | null |
@extends('admin.layouts.layout')
@section('title', 'Create Taxi/Tour')
@section('content')
<section class="content">
<!-- SELECT2 EXAMPLE -->
<div class="box box-success">
<div class="box-header with-border">
<div class="box-header pull-left">
<span class="box-title">Create Taxi/Tour</span>
</div>
<div class="box-tools pull-right">
<a href="{{route('tour.index')}}" class="btn btn-xs btn-success pull-left text-white" title="Add New"><i class="fa fa-arrow-left"></i> <span class="text-capitalize">back</span></a>
</div>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="row">
<form class="form-row" method="POST" action="{{route('tour.store')}}" enctype="multipart/form-data">
@csrf
<div class="col-md-6">
<div class="form-group">
<label>Type<span class="control-label"></span></label>
<select id="tourType" id="tour_type" required name="tour[tour_type]" class="form-control">
<option value="">Please Select...</option>
<option value="taxi">Taxi</option>
<option value="tour">Tour</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Name<span class="control-label"></span></label>
<input type="text" name="tour[name]" placeholder="Name" class="form-control" required />
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Short Description</label>
<input type="text" name="tour[short_desc]" placeholder="Short Description" class="form-control" />
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Price Type</label>
<select name="tour[type_id]" class="form-control">
<option value="">Please Select</option>
@foreach ($types as $type)
<option value="{{$type->id}}">{{$type->name}}</option>
@endforeach
</select>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Description</label>
<textarea id="ck-editor" class="form-control" name="tour[description]"></textarea>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Destinations</label>
<select name="tour[destination_id]" class="form-control">
<option value="">Please Select</option>
@foreach ($destinations as $data)
<option value="{{$data->id}}">{{$data->name}}</option>
@endforeach
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Locations</label>
<select name="tour[location_id]" class="form-control">
<option value="">Please Select</option>
@foreach ($locations as $data)
<option value="{{$data->id}}">{{$data->name}}</option>
@endforeach
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Categories</label>
<select name="tour[category_id]" class="form-control">
<option value="">Please Select</option>
@foreach ($categories as $data)
<option value="{{$data->id}}">{{$data->name}}</option>
@endforeach
</select>
</div>
</div>
<div class="col-md-4 tourNaming">
<div class="form-group">
<label>Activities</label>
<select name="tour[activity_id]" class="form-control">
<option value="">Please Select</option>
@foreach ($activities as $data)
<option value="{{$data->id}}">{{$data->name}}</option>
@endforeach
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Durations</label>
<select name="tour[duration_id]" class="form-control">
<option value="">Please Select</option>
@foreach ($durations as $data)
<option value="{{$data->id}}">{{$data->name}}</option>
@endforeach
</select>
</div>
</div>
<div class="col-md-4 tourNaming">
<div class="form-group">
<label>Services</label>
<select name="tour[service_id]" class="form-control">
<option value="">Please Select</option>
@foreach ($services as $data)
<option value="{{$data->id}}">{{$data->name}}</option>
@endforeach
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Destination A<span class="control-label"></span></label>
<input type="text" name="tour[destination_a]" placeholder="Destination A" class="form-control" required />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Destination B<span class="control-label"></span></label>
<input type="text" name="tour[destination_b]" placeholder="Destination B" class="form-control" required />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Minimum Capacity<span class="control-label"></span></label>
<input type="text" name="tour[min_capacity]" placeholder="Minimum capacity" required class="form-control" />
</div>
</div>
<div class="col-md-4 tourNaming">
<div class="form-group">
<label>Max Capacity<span class="control-label"></span></label>
<input type="text" name="tour[max_capacity]" placeholder="Maximum capacity" class="form-control" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Location</label>
<input type="text" name="tour[location]" placeholder="Location" class="form-control" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Price<span class="control-label"></span></label>
<input type="text" name="tour[price]" placeholder="Price" class="form-control" required />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Rating</label>
<input type="text" name="tour[rating]" placeholder="Rating" class="form-control" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Duration</label>
<input type="text" name="tour[duration]" placeholder="Duration" class="form-control" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Tour Start Date</label>
<input type="text" name="tour[start_date]" placeholder="Pick Up Date" class="datepicker form-control" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Tour End Date</label>
<input type="text" name="tour[end_date]" placeholder="End Date" class="datepicker form-control" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Departure Time</label>
<input type="text" name="tour[departure_time]" placeholder="Departure Time" class="form-control" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Num Of Persons</label>
<input type="text" name="tour[num_of_persons]" placeholder="Num Of Persons" class="form-control" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Featured Image<span class="control-label"></span></label>
<input type="file" name="tour[featured_img]" class="form-control" required />
</div>
</div>
<div class="clearfix"></div>
{{-- Rents --}}
<div class="repeater pl-3">
<div data-repeater-list="rent_section">
<div data-repeater-item>
<div class="inner-repeater">
<div class="rent-wrapper" data-repeater-list="rent_section">
<div data-repeater-item>
<div class="row mt-3">
<div class="col-md-3">
<div class="form-group">
<label for="inputRole">Rent Name</label>
<input type="text" name="rent" placeholder="Rent" class="form-control form-control-sm" id="inputRole" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="inputRole">Person</label>
<input type="text" name="person" placeholder="Person" class="form-control form-control-sm" id="inputRole" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="inputRole">Price Type</label>
<select name="type_id" class="form-control">
<option value="">Please Select</option>
@foreach ($types as $type)
<option value="{{$type->id}}">{{$type->name}}</option>
@endforeach
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label for="inputRole">Price</label>
<input type="number" name="price" placeholder="Price" class="form-control form-control-sm" id="inputRole" />
</div>
</div>
<div class="col-md-1 pt-5 pl-0" style="padding-top: 26px;">
<div data-repeater-delete class="btn btn-sm btn-success btn-danger">Delete</div>
</div>
</div>
</div>
</div>
<button data-repeater-create type="button" style="margin-top:26px;" class="btn btn-success btn-sm float-right my-3">Add More</button>
</div>
</div>
</div>
</div>
{{-- Facilities --}}
<div class="repeater pl-3">
<div data-repeater-list="facilities_section">
<div data-repeater-item>
<div class="inner-repeater">
<div style="width: 40%; float:left" data-repeater-list="facilities_section">
<div data-repeater-item>
<div class="row mt-3">
<div class="col-md-11">
<div class="form-group">
<label for="inputRole">Facilities Name</label>
<input type="text" name="facility" placeholder="Facility Name" class="form-control form-control-sm" id="inputRole" />
</div>
</div>
<div class="col-md-1 pt-5 pl-0" style="padding-top: 26px;">
<div data-repeater-delete class="btn btn-sm btn-success btn-danger">Delete</div>
</div>
</div>
</div>
</div>
<button style="float: left;margin-left:56px; margin-top:26px;" data-repeater-create type="button" class="btn btn-success btn-sm float-right my-3">Add More</button>
</div>
</div>
</div>
</div>
<div class="clearfix"></div>
{{-- Conditions --}}
<div class="repeater pl-3">
<div data-repeater-list="conditions_section">
<div data-repeater-item>
<div class="inner-repeater">
<div style="width: 40%; float:left" data-repeater-list="conditions_section">
<div data-repeater-item>
<div class="row mt-3">
<div class="col-md-11">
<div class="form-group">
<label for="inputRole">Conditions Name</label>
<input type="text" name="condition" placeholder="Condition name" class="form-control form-control-sm" id="inputRole" />
</div>
</div>
<div class="col-md-1 pt-5 pl-0" style="padding-top: 26px;">
<div data-repeater-delete class="btn btn-sm btn-success btn-danger">Delete</div>
</div>
</div>
</div>
</div>
<button style="float: left;margin-left:56px; margin-top:26px;" data-repeater-create type="button" style="margin-top:26px;" class="btn btn-success btn-sm float-right my-3">Add More</button>
</div>
</div>
</div>
</div>
<div class="clearfix"></div>
<div class="col-md-12">
<div class="pull-right">
<button class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
<!-- /.row -->
</div>
<!-- /.box-body -->
</div>
</section>
@endsection
@push('page-scripts')
<script defer src="{{asset('admin_assets/assets/js/jquery.repeater.min.js')}}"></script>
<script defer src="{{asset('admin_assets/assets/js/bootstrap-datepicker.min.js')}}"></script>
<script defer src="{{asset('admin_assets/assets/js/custom.js')}}"></script>
@endpush
| 52.897019
| 224
| 0.356986
|
a42bff919716bc60ffcf058e9c55b60cc4446bbf
| 30,485
|
php
|
PHP
|
application/helpers/users_application/form_flds_helper.php
|
gxe1157/njpob2018
|
57843423f42b51737d5f6b836c648233da13eca7
|
[
"MIT"
] | null | null | null |
application/helpers/users_application/form_flds_helper.php
|
gxe1157/njpob2018
|
57843423f42b51737d5f6b836c648233da13eca7
|
[
"MIT"
] | null | null | null |
application/helpers/users_application/form_flds_helper.php
|
gxe1157/njpob2018
|
57843423f42b51737d5f6b836c648233da13eca7
|
[
"MIT"
] | null | null | null |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/* users_application */
if ( ! function_exists('get_tables_names'))
{
function get_table_data()
{
$form_tables = array('user_address', 'user_mail_to', 'user_main',
'user_info', 'user_employment_le',
'user_children', 'user_employment_prv_sector');
$user_address = array('address1', 'address2', 'city', 'state', 'zip', 'county');
$user_mail_to = array('mail_add1', 'mail_add2','mail_city', 'mail_state', 'mail_zip');
$user_main = array('email','first_name','last_name','middle_name','phone','mail_to','cell_phone');
$user_info = array('registered_voter', 'legislative_dist', 'gender', 'dob',
'driver_lic', 'height', 'weight','social_sec', 'hair_color',
'eye_color', 'marital_status', 'spouse_fname', 'spouse_lname',
'spouse_dob', 'spouse_gender', 'spouse_email');
$user_employment_le = array('le_agency', 'le_dept', 'le_add1', 'le_add2', 'le_city',
'le_state', 'le_zip', 'le_rank', 'le_email', 'le_phone',
'le_dt_hired', 'le_dt_retired', 'le_yos');
$user_employment_prv_sector = array('prv_sector','prv_sector_employer', 'prv_sector_dept',
'prv_sector_add1', 'prv_sector_add2', 'prv_sector_city',
'prv_sector_state', 'prv_sector_zip', 'prv_sector_position',
'prv_sector_email', 'prv_sector_phone', 'prv_sector_dt_hired');
$user_children = array('child_fname', 'child_lname', 'child_dob', 'child_gender');
return array( $form_tables, $user_main, $user_address,
$user_mail_to, $user_info, $user_employment_le,
$user_employment_prv_sector, $user_children );
}
}
if ( ! function_exists('get_fields'))
{
function get_fields( $result_set = array() )
{
$results = array();
$display_value = false;
if( count($result_set) > 0 ){
$results = $result_set[0];
$display_value = true;
}
// $ci =& get_instance();
// $ci->load->module('lib');
$Select_option = array(
array(''=>'Please Select...','Yes'=>'Yes','No'=>'No'),
array(''=>'Please Select...','Male'=>'Male', 'Female'=>'Female', 'Other'=>'Other'),
array(''=>'Please Select...','Single'=>'Single', 'Married'=>'Married', 'Divorced'=>'Divorced','Widowed'=>'Widowed'),
);
$fld_group1 = array(
array(
'field' => 'fullname',
'label' => 'Fullname',
'rules' => '',
'icon' => 'user',
'placeholder'=>'John A. Smith ',
'input_value' => $display_value ? $results->first_name." ".$results->last_name : '',
'input_type' => 'text', // text, password or drop_down_sel
'input_options' => '0',
'fld_group' =>'1'
),
// array(
// 'field' => 'first_name',
// 'label' => 'First Name',
// 'rules' =>'required|min_length[3]|max_length[40]',
// 'icon' => 'user',
// 'placeholder'=>'',
// 'input_type' => 'text', // text, password or drop_down_sel
// 'input_options' => '0',
// 'fld_group' =>'1'
// ),
// array(
// 'field' => 'last_name',
// 'label' => 'Last Name',
// 'rules' =>'required|min_length[3]|max_length[40]',
// 'icon' => 'user',
// 'placeholder'=>'',
// 'input_type' => 'text', // text, password or drop_down_sel
// 'input_options' => '0',
// 'fld_group' =>'1'
// ),
array(
'field' => 'email',
'label' => 'Email',
'rules' => '',
'icon' => 'envelope',
'placeholder'=>'email@email.com',
'input_value' => $display_value ? $results->email : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' =>'1'
),
array(
'field' => 'phone',
'label' => 'Phone',
'rules' =>'',
'icon' => 'earphone',
'placeholder'=>'(201) 999-9999',
'input_value' => $display_value ? $results->phone : '',
'input_type' =>'text',
'input_options'=>'0',
'fld_group' =>'1'
),
array(
'field' => 'cell_phone',
'label' => 'Cell Phone',
'rules' =>'',
'icon' => 'phone',
'placeholder'=>'(201) 999-9999',
'input_value' => $display_value ? $results->cell_phone : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' =>'1'
),
array(
'field' => 'address1',
'label' => 'Address1',
'rules' => 'required|min_length[3]|max_length[100]',
'icon' => 'envelope',
'placeholder'=>'',
'input_value' => $display_value ? $results->address1 : '',
'input_type' =>'text',
'input_options'=>'0',
'fld_group' =>'1'
),
array(
'field' => 'address2',
'label' => 'Address2',
'rules' => 'max_length[100]',
'icon' => 'envelope',
'placeholder'=>'',
'input_value' => $display_value ? $results->address2 : '',
'input_type' =>'text',
'input_options'=>'0',
'fld_group' =>'1'
),
array(
'field' => 'city',
'label' => 'City',
'rules' => 'required|min_length[3]|max_length[100]',
'icon' => 'envelope',
'placeholder'=>'',
'input_value' => $display_value ? $results->city : '',
'input_type' =>'text',
'input_options'=>'0',
'fld_group' =>'1'
),
array(
'field' => 'state',
'label' => 'State',
'rules' => 'required',
'icon' => 'envelope',
'placeholder'=>'Example: NJ, Ct, CA ...',
'input_value' => $display_value ? $results->state : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' =>'1'
),
array(
'field' => 'zip',
'label' => 'Zip',
'rules' => 'required|is_natural|exact_length[5]',
'icon' => 'envelope',
'placeholder'=>'',
'input_value' => $display_value ? $results->zip : '',
'input_type' =>'text',
'input_options'=>'0',
'fld_group' =>'1'
),
array(
'field' => 'county',
'label' => 'County',
'rules' => 'required|alpha|max_length[100]',
'icon' => 'user',
'placeholder'=>'',
'input_value' => $display_value ? $results->county : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' =>'2'
),
array(
'field' => 'registered_voter',
'label' => 'Voter Status',
'rules' => 'required',
'icon' => 'user',
'placeholder'=>'Are you a registered voter?',
'input_value' => $display_value ? $results->registered_voter : '',
'input_type' => 'drop_down_sel',
'input_options' => '0',
'fld_group' =>'2'
),
array(
'field' => 'legislative_dist',
'label' => 'Legist Dist',
'rules' => '',
'icon' => 'user',
'placeholder'=>'Enter your legistlative district if known...',
'input_value' => $display_value ? $results->legislative_dist : '',
'input_type' => 'text',
'input_options' => '0',
'fld_group' =>'2'
),
array(
'field' => 'mail_to',
'label' => 'Mail To',
'rules' => 'required',
'icon' => 'envelope',
'placeholder'=> 'Is mailing address same?',
'input_value' => $display_value ? $results->mail_to : '',
'input_type' => 'drop_down_sel',
'input_options' => '0',
'fld_group' =>'2'
),
array(
'field' => 'mail_add1',
'label' => 'Mail Add1',
'rules' => 'required|min_length[3]|max_length[100]',
'icon' => 'envelope',
'placeholder'=>'',
'input_value' => $display_value ? $results->mail_add1 : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' =>'2'
),
array(
'field' => 'mail_add2',
'label' => 'Mail Add2',
'rules' => 'max_length[100]',
'icon' => 'envelope',
'placeholder'=>'',
'input_value' => $display_value ? $results->mail_add2 : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' =>'2'
),
array(
'field' => 'mail_city',
'label' => 'Mail City',
'rules' => 'required|min_length[3]|max_length[100]',
'icon' => 'envelope',
'placeholder'=>'',
'input_value' => $display_value ? $results->mail_city : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' =>'2'
),
array(
'field' => 'mail_state',
'label' => 'Mail State',
'rules' => 'required',
'icon' => 'envelope',
'placeholder'=>'Example: NJ, Ct, CA ...',
'input_value' => $display_value ? $results->mail_state : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' =>'2'
),
array(
'field' => 'mail_zip',
'label' => 'Mail Zip',
'rules' => 'required|is_natural|exact_length[5]',
'icon' => 'envelope',
'placeholder'=>'',
'input_value' => $display_value ? $results->mail_zip : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' =>'2'
)
);
$fld_group2 = array(
array(
'field' => 'driver_lic',
'label' => 'Driver's License',
'rules' => 'required|alpha_numeric',
'icon' => 'user',
'placeholder'=>'',
'input_value' => $display_value ? $results->driver_lic : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' =>'3'
),
array(
'field' => 'social_sec',
'label' => 'Social Security',
'rules' => 'required|numeric|max_length[9]',
'icon' => 'user',
'placeholder'=>'',
'input_value' => $display_value ? $results->social_sec : '',
'input_type' => 'password',
'input_options' => '0',
'fld_group' =>'ss'
),
array(
'field' => 'ss_confirm',
'label' => 'Confirm Social Security',
'rules' => 'matches[social_sec]',
'icon' => 'user',
'placeholder'=>'',
'input_value' => $display_value ? $results->social_sec : '',
'input_type' =>'password',
'input_options' => '0',
'fld_group' =>'ssc'
),
array(
'field' => 'marital_status',
'label' => 'Marital Status',
'rules' => 'required',
'icon' => 'user',
'placeholder'=>'Please select ',
'input_value' => $display_value ? $results->marital_status : '',
'input_type' =>'drop_down_sel',
'input_options' => '2',
'fld_group' =>'3'
)
);
$fld_group3 = array(
array(
'field' => 'le_agency',
'label' => 'Agency',
'rules' => 'required|min_length[3]|max_length[100]',
'icon' => 'user',
'placeholder'=>'Law Enforcement Agency',
'input_value' => $display_value ? $results->le_agency : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'le_'
),
array(
'field' => 'le_dept',
'label' => 'Department',
'rules' => 'required|max_length[100]',
'icon' => 'user',
'placeholder'=>'',
'input_value' => $display_value ? $results->le_dept : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'le_'
),
array(
'field' => 'le_rank',
'label' => 'Rank / Title',
'rules' => 'required|max_length[100]',
'icon' => 'user',
'placeholder'=>'',
'input_value' => $display_value ? $results->le_rank : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'le_'
),
array(
'field' => 'le_add1',
'label' => 'Address1',
'rules' => 'required|min_length[3]|max_length[100]',
'icon' => 'envelope',
'placeholder'=>'',
'input_value' => $display_value ? $results->le_add1 : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'le_'
),
array(
'field' => 'le_add2',
'label' => 'Address2',
'rules' => '',
'icon' => 'envelope',
'placeholder'=>'',
'input_value' => $display_value ? $results->le_add2 : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'le_'
),
array(
'field' => 'le_city',
'label' => 'City',
'icon' => 'envelope',
'rules' => 'required|min_length[3]|max_length[100]',
'placeholder'=>'',
'input_value' => $display_value ? $results->le_city : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'le_'
),
array(
'field' => 'le_state',
'label' => 'State',
'rules' => 'required',
'icon' => 'envelope',
'placeholder'=>'Example: NJ, Ct, CA ...',
'input_value' => $display_value ? $results->le_state : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'le_'
),
array(
'field' => 'le_zip',
'label' => 'Zip',
'rules' => 'required|is_natural|exact_length[5]',
'icon' => 'envelope',
'placeholder'=>'',
'input_value' => $display_value ? $results->le_zip : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'le_'
),
array(
'field' => 'le_email',
'label' => 'Work Email',
'rules' => 'required|valid_email|max_length[200]',
'icon' => 'envelope',
'placeholder'=>'email@email.com',
'input_value' => $display_value ? $results->le_email : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'le_'
),
array(
'field' => 'le_phone',
'label' => 'Work Phone',
'rules' => 'required',
'icon' => 'earphone',
'placeholder'=>'(201) 999-9999',
'input_value' => $display_value ? $results->le_phone : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'le_'
),
array(
'field' => 'le_dt_hired',
'label' => 'Date Hired',
'icon' => 'user',
'placeholder'=>' MM/DD/YYYY',
'input_value' => $display_value ? format_date($results->le_dt_hired) : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'le_',
),
array(
'field' => 'le_dt_retired',
'label' => 'Date Retired',
'icon' => 'user',
'placeholder'=>' MM/DD/YYYY',
'input_value' => $display_value ? format_date($results->le_dt_retired) : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'le_',
),
array(
'field' => 'le_yos',
'label' => 'Years of Service',
'icon' => 'user',
'placeholder'=>'99',
'input_value' => $display_value ? $results->le_yos : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'le_',
),
array(
'field' => 'prv_sector',
'label' => '<span style="color: #2F93CC">Are you currently employed by the private sector?</span>',
'rules' => 'required',
'icon' => '',
'placeholder'=>'Please select ',
'input_value' => $display_value ? $results->prv_sector : '',
'input_type' =>'drop_down_sel',
'input_options' => '0',
'fld_group' =>'le_'
),
array(
'field' => 'prv_sector_employer',
'label' => 'Employer',
'rules' => 'required|min_length[3]|max_length[100]',
'icon' => 'user',
'placeholder'=>'Agency/Company Name',
'input_value' => $display_value ? $results->prv_sector_employer : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'prv_'
),
array(
'field' => 'prv_sector_dept',
'label' => 'Department',
'rules' => 'required|max_length[100]',
'icon' => 'user',
'placeholder'=>'',
'input_value' => $display_value ? $results->prv_sector_dept : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'prv_'
),
array(
'field' => 'prv_sector_position',
'label' => 'Title',
'rules' => 'required|max_length[100]',
'icon' => 'user',
'placeholder'=>'',
'input_value' => $display_value ? $results->prv_sector_position : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'prv_'
),
array(
'field' => 'prv_sector_add1',
'label' => 'Address1',
'rules' => 'required|min_length[3]|max_length[100]',
'icon' => 'envelope',
'placeholder'=>'',
'input_value' => $display_value ? $results->prv_sector_add1 : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'prv_'
),
array(
'field' => 'prv_sector_add2',
'label' => 'Address2',
'rules' => '',
'icon' => 'envelope',
'placeholder'=>'',
'input_value' => $display_value ? $results->prv_sector_add2 : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'prv_'
),
array(
'field' => 'prv_sector_city',
'label' => 'City',
'icon' => 'envelope',
'rules' => 'required|min_length[3]|max_length[100]',
'placeholder'=>'',
'input_value' => $display_value ? $results->prv_sector_city : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'prv_'
),
array(
'field' => 'prv_sector_state',
'label' => 'State',
'rules' => 'required',
'icon' => 'envelope',
'placeholder'=>'Example: NJ, Ct, CA ...',
'input_value' => $display_value ? $results->prv_sector_state : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'prv_'
),
array(
'field' => 'prv_sector_zip',
'label' => 'Zip',
'rules' => 'required|is_natural|exact_length[5]',
'icon' => 'envelope',
'placeholder'=>'',
'input_value' => $display_value ? $results->prv_sector_zip : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'prv_'
),
array(
'field' => 'prv_sector_email',
'label' => 'Work Email',
'rules' => 'required|valid_email|max_length[200]',
'icon' => 'envelope',
'placeholder'=>'email@email.com',
'input_value' => $display_value ? $results->prv_sector_email : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'prv_'
),
array(
'field' => 'prv_sector_phone',
'label' => 'Work Phone',
'rules' => 'required',
'icon' => 'earphone',
'placeholder'=>'(201) 999-9999',
'input_value' => $display_value ? $results->prv_sector_phone : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'prv_'
),
array(
'field' => 'prv_sector_dt_hired',
'label' => 'Date Hired',
'icon' => 'user',
'rules' => 'required',
'placeholder'=>' MM/DD/YYYY',
'input_value' => $display_value ? format_date($results->prv_sector_dt_hired) : '',
'input_type' =>'text',
'input_options' => '0',
'fld_group' => 'prv_'
)
);
$fld_group4 = array(
array( //0
'field' => 'dob',
'label' => 'Date of Birth',
'icon' => '',
'placeholder'=>'MM/DD/YYYY',
'input_value' => $display_value ? format_date($results->dob) : '',
'input_type' =>'text',
'input_options' => '0'
),
array( //1
'field' => 'gender',
'label' => 'Gender',
'icon' => '',
'placeholder'=>'',
'input_value' => $display_value ? $results->gender : '',
'input_type' =>'drop_down_sel',
'input_options' => '1'
),
array( //2
'field' => 'height',
'label' => 'Height',
'rules' => 'required',
'icon' => '',
'placeholder'=>'ft - in',
'input_value' => $display_value ? $results->height : '',
'input_type' =>'text',
'input_options' => '0'
),
array( //3
'field' => 'weight',
'label' => 'Weight',
'rules' => 'required',
'icon' => '',
'placeholder'=>'lbs',
'input_value' => $display_value ? $results->weight : '',
'input_type' =>'text',
'input_options' => '0'
),
array( //4
'field' => 'hair_color',
'label' => 'Hair Color',
'rules' => 'required',
'icon' => '',
'placeholder'=>'',
'input_value' => $display_value ? $results->hair_color : '',
'input_type' =>'text',
'input_options' => '0'
),
array( //5
'field' => 'eye_color',
'label' => 'Eye Color',
'rules' => 'required',
'icon' => '',
'placeholder'=>'',
'input_value' => $display_value ? $results->eye_color : '',
'input_type' =>'text',
'input_options' => '0'
),
array( //6
'field' => 'spouse_fname',
'label' => 'First Name',
'rules' => 'required',
'icon' => '',
'placeholder'=>'',
'input_value' => $display_value ? $results->spouse_fname : '',
'input_type' =>'text',
'input_options' => '0'
),
array( //7
'field' => 'spouse_lname',
'label' => 'Last Name',
'rules' => 'required',
'icon' => '',
'placeholder'=>'',
'input_value' => $display_value ? $results->spouse_lname : '',
'input_type' =>'text',
'input_options' => '0'
),
array( //8
'field' => 'spouse_dob',
'label' => 'Date of Birth',
'rules' => 'required',
'icon' => '',
'placeholder'=>'MM/DD/YYYY',
'input_value' => $display_value ? format_date($results->spouse_dob) : '',
'input_type' =>'text',
'input_options' => '0'
),
array( //9
'field' => 'spouse_gender',
'label' => 'Gender',
'rules' => 'required',
'icon' => '',
'placeholder'=>'',
'input_value' => $display_value ? $results->spouse_gender : '',
'input_type' =>'drop_down_sel',
'input_options' => '1'
),
array( //9
'field' => 'spouse_email',
'label' => 'Email',
'rules' => 'required',
'icon' => 'enveople',
'placeholder'=>'email@email.com',
'input_value' => $display_value ? $results->spouse_email : '',
'input_type' =>'text',
'input_options' => '0'
),
);
$fld_group5 = array(
array( //0
'field' => 'child_fname',
'label' => 'First Name',
'rules' => 'required',
'icon' => '',
'placeholder'=>'',
'input_value' => $display_value ? $results->child_fname : '',
'input_type' =>'text',
'input_options' => '0'
),
array( //1
'field' => 'child_lname',
'label' => 'Last Name',
'rules' => 'required',
'icon' => '',
'placeholder'=>'',
'input_value' => $display_value ? $results->child_lname : '',
'input_type' =>'text',
'input_options' => '0'
),
array( //2
'field' => 'child_dob',
'label' => 'Date of Birth',
'rules' => 'required',
'icon' => '',
'placeholder'=>'MM/DD/YYYY',
'input_value' => $display_value ? format_date($results->child_dob) : '',
'input_type' =>'text',
'input_options' => '0'
),
array( //3
'field' => 'child_gender',
'label' => 'Gender',
'rules' => 'required',
'icon' => '',
'placeholder'=>'',
'input_value' => $display_value ? $results->child_gender : '',
'input_type' =>'drop_down_sel',
'input_options' => '1'
),
);
return array( $Select_option, $fld_group1, $fld_group2, $fld_group3, $fld_group4, $fld_group5 );
}// get_fields
} // endif
| 39.335484
| 126
| 0.388093
|
6e1d44fd2bde0a26c905bd6fd35d15ee9e4b694c
| 3,445
|
ps1
|
PowerShell
|
BESFailoverStatus.v1.ps1
|
kevincallanan/PowerShellScripts
|
e2a0508dc335c200cb8cb0d923ccf44e071b2d7f
|
[
"MIT"
] | null | null | null |
BESFailoverStatus.v1.ps1
|
kevincallanan/PowerShellScripts
|
e2a0508dc335c200cb8cb0d923ccf44e071b2d7f
|
[
"MIT"
] | null | null | null |
BESFailoverStatus.v1.ps1
|
kevincallanan/PowerShellScripts
|
e2a0508dc335c200cb8cb0d923ccf44e071b2d7f
|
[
"MIT"
] | null | null | null |
# ==============================================================================================
# NAME: BESFailoverStatus.v1
# AUTHOR: Kevin Callanan
# Released Version: 1.0
# Description: This script will connect to your BES SQL Database and Provide Failover Statuses for all HA pairs
# Description: This script must run as an account with permissions to Read the SQL tables on the BES Database
# WARRENTY: None - Proceed at your own risk :-)
# ==============================================================================================
$RunTime = Get-Date
#Editable Variables
$From = "besadminonprem@contoso.com"
$To = "kevin_callanan@contoso.com"
$smtphost = "mailhub.contoso.com"
$ServerName = "sqlserver.contoso.com"
$DatabaseName = "BESMgmtOP_pdb"
$BASURL = "https://exchange-baspool.contoso.com/webconsole/login"
#SQL Query Variables
$Query = "
SELECT UPPER([ServiceName]) AS 'ServiceName'
,[MachineName],[SRPid],[AutoFailover]
,[AutoFailoverExt]
FROM [BESMgmt50].[dbo].[ServerConfig]
WHERE ServiceName NOT LIKE MachineName"
$QueryTimeout = 120
$ConnectionTimeout = 30
$SuccessLogo = "<img id='logo-png' src='https://www.testexchangeconnectivity.com/Images/Success.png' alt='Success' />"
$SuccessWarnLogo = "<img id='logo-png' src='https://www.testexchangeconnectivity.com/Images/SuccessWarn.png' alt='SuccessWarn' />"
$ErrorLogo = "<img id='logo-png' src='https://www.testexchangeconnectivity.com/Images/Error.png' alt='Error' />"
#SQL Magic
$SQLConnection = New-Object System.Data.SqlClient.SQLConnection
$ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerName,$DatabaseName,$ConnectionTimeout
$SQLConnection.ConnectionString = $ConnectionString
$SQLConnection.Open()
$QueryCMD = New-Object system.Data.SqlClient.SqlCommand($Query,$SQLConnection)
$QueryCMD.CommandTimeout = $QueryTimeout
$DataTable = New-Object system.Data.DataTable
$DataAdapter = New-Object system.Data.SqlClient.SqlDataAdapter($QueryCMD)
$DataAdapter.fill($DataTable) | Out-Null
$SQLConnection.Close()
$Results = @($DataTable)
#Build Email HTML
$EmailBody = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'><title>BES HA Automated Failover Status</title></head>"
$EmailBody += "<h2>BES HA Automated Failover Status</h2>" + "<br>"
$EmailBody += "<table><center><tr><td><b>Service Name</b></td><td><b>Active Server</b></td><td><b>SRPid</b></td><td><b>AutoFailover</b></td><td><b>AutoConn Failover</b></td></tr></center>"
ForEach ($Service in $Results) {
#Set Icon Type for AutoFailover Option
IF ($Service.AutoFailover -eq 1){$AutoFailover = $SuccessLogo}
ELSE{$AutoFailover = $ErrorLogo}
#Set Icon Type for AutoFailoverExt Option
IF ($Service.AutoFailoverExt -eq 1){$AutoFailoverExt = $SuccessLogo}
ELSE{$AutoFailoverExt = $ErrorLogo}
$EmailBody += "<tr><td>" + $Service.ServiceName + "</td><td>" + $Service.MachineName + "</td><td>" + $Service.SRPid + "</td><td><center>" + $AutoFailover + "</center></td><td><center>" + $AutoFailoverExt + "</center></td></tr>"
}
#Complete Email HTML
$EmailBody += "</table>"
$EmailBody += "<br><a href=" + $BASURL + ">Blackberry Admin Console</a><br><br>"
$EmailBody += "<br><i>Data Generated on: " + $RunTime + "</i>"
$Subject = "BES HA Automatic Failover Status: (" + $RunTime + ")"
Send-MailMessage -To $to -Subject $Subject -Body $EmailBody -SmtpServer $smtphost -From $from -BodyAsHtml
| 49.214286
| 228
| 0.679826
|
465126b0325ad3735c7cc154f771e5fe1cc048e1
| 5,917
|
php
|
PHP
|
resources/views/plans/create.blade.php
|
pnam2311/Travel
|
6b0d5e03c41ff539598e418628dbc895c3912436
|
[
"MIT"
] | null | null | null |
resources/views/plans/create.blade.php
|
pnam2311/Travel
|
6b0d5e03c41ff539598e418628dbc895c3912436
|
[
"MIT"
] | null | null | null |
resources/views/plans/create.blade.php
|
pnam2311/Travel
|
6b0d5e03c41ff539598e418628dbc895c3912436
|
[
"MIT"
] | null | null | null |
@extends('layouts.master')
@section('content')
<div class="container">
<h1>Tạo kế hoạch</h1>
<input type="hidden" id = "latlng"></input><br>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Tên kế hoạch</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="plan_name_tamp" id="plan_name_tamp">
</div>
</div>
<div class="row">
<label class="col-sm-2 col-form-label">Ảnh</label>
<div class="form-group col-sm-10" enctype="multipart/form-data">
<div class="upload-btn-wrapper">
<button class="plan-img-upload"><i class="fas fa-upload"></i></button>
<form id="image" enctype="multipart/form-data">
<input accept="image/*" name="plan_photo" title="Tải ảnh lên" type="file" onchange="previewFile()">
</form>
</div>
</div>
<input type="hidden" id="file_name" value="">
</div>
<div class="form-group row">
<div class="offset-sm-2 col-sm-4">
<img id="img" src="{{asset('images/plans/plan2.jpg')}}" width="100%">
</div>
<div class="col-sm-6">
<div id="map"></div>
</div>
</div>
<div class="form-group row">
<label class="offset-sm-2 col-sm-2 col-form-label">Thời gian bắt đầu</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="start_time" id="start_time" onchange="validateForm1()">
</div>
<label class="col-sm-2 col-form-label">Địa điểm bắt đầu</label>
<div class="col-sm-3 col-form-label">
<input type="text" class="form-control" name="startpoint" id="start">
</div>
</div>
<div class="form-group row">
<label class="offset-sm-2 col-sm-2 col-form-label">Thời gian kết thúc</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="end_time" id="end_time" onchange="validateForm1()">
</div>
<label class="col-sm-2 col-form-label">Địa điểm kết thúc</label>
<div class="col-sm-3 col-form-label">
<input type="text" class="form-control" name="endpoint" id="end">
</div>
</div>
<div class="form-group row">
<label class="offset-sm-2 col-sm-2 col-form-label">Phương tiện</label>
<div class="col-sm-8">
<select class="form-control" name="vehicle" id="mode">
<option value="x"></option><!--Sửa trường vehicle trong plan là nullable và option này sẽ sửa là null-->
<option value="DRIVING">Driving</option>
<option value="WALKING">Walking</option>
<option value="BICYCLING">Bicycling</option>
<option value="TRANSIT">Transit</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="offset-sm-2 col-sm-2 col-form-label">Hoạt động</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="action" id="action">
<p style="color:red;" id="notify"></p>
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2">
<button class="btn btn-primary" onclick="addTableRow()"> <!--Xử lý bằng action javascript-->
Thêm hoạt động
</button>
</div>
</div>
<form method="post" action="" enctype="multipart/form-data">
<input type="hidden" id = "plan_name"></input><br>
<input type="hidden" id = "image_name"></input><br>
<div class="form-group row">
<div class="offset-sm-2 col-sm-10 table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Điểm xuất phát</th>
<th>Thời gian xuất phát</th>
<th>Điểm kết thúc</th>
<th>Thời gian kết thúc</th>
<th>Phương tiện</th>
<th>Hoạt động</th>
</tr>
</thead>
<tbody id="tBody">
</tbody>
</table>
<a onClick="removeLastRoad()" class="btn btn-danger" href="javascript:void(0)">Re-one</a>
<a onClick="removeAllRoads()" class="btn btn-danger" href="javascript:void(0)">Re-all</a>
</div>
</div>
<div class="form-group row">
<div class="col-sm-2">
<button type="button" id="submit_plan" class="btn btn-primary" onclick="submitPlan()">
Thêm kế hoạch
</button>
</div>
</div>
</form>
</div>
@endsection
<script type="text/javascript">
function submitPlan() {
//TODO: fix this mess
var url = "{{route('plans.store')}}";
var formData = new FormData(document.getElementById('image'));
var data = JSON.stringify(getTableContent());
// console.log(document.getElementById('image'));
formData.append('_token', '{{csrf_token()}}');
formData.append('plan_name', $('#plan_name_tamp').val());
formData.append('user_id',$('#plan_name_tamp').val());
formData.append('picture', $('#file_name').val());
formData.append('data', data);
$.ajax({
url: url,
type: 'post',
data: formData,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
var route = '{{route('plans.show', ':id')}}';
route = route.replace(':id', data);
window.location = route;
//console.log(getTableContent()[0]);
},
error: function(data) {
console.log(data);
alert('error boiiiiiiiii');
},
});
}
</script>
| 40.251701
| 120
| 0.524252
|
b2cfe0e4cd9d3511a9492ee91c37b840c50c9867
| 154
|
rb
|
Ruby
|
db/migrate/20131009112843_add_last_used_at_to_workflows.rb
|
aniket328/CompModelMatch
|
5e39017357ba69145366b3c97352d169a8afa1bd
|
[
"BSD-3-Clause"
] | 55
|
2015-08-31T13:15:47.000Z
|
2022-02-21T15:03:34.000Z
|
db/migrate/20131009112843_add_last_used_at_to_workflows.rb
|
aniket328/CompModelMatch
|
5e39017357ba69145366b3c97352d169a8afa1bd
|
[
"BSD-3-Clause"
] | 855
|
2015-09-22T08:05:52.000Z
|
2022-03-31T16:50:31.000Z
|
db/migrate/20131009112843_add_last_used_at_to_workflows.rb
|
knoppiks/n4h-lap-seek
|
80668a1bd992a16c89065acb552288410449e3d2
|
[
"BSD-3-Clause"
] | 43
|
2015-03-07T19:23:34.000Z
|
2022-03-15T12:35:22.000Z
|
class AddLastUsedAtToWorkflows < ActiveRecord::Migration
def change
change_table :workflows do |t|
t.datetime :last_used_at
end
end
end
| 19.25
| 56
| 0.733766
|
2ed19593af3ac5d880b16094558b5eb1921591e6
| 295
|
dart
|
Dart
|
bin/main.dart
|
KristobalJunta/helper_tgtoadbot
|
92306b2ae119d937e93a806730e976173dbb73de
|
[
"MIT"
] | 6
|
2021-05-05T19:44:19.000Z
|
2021-12-02T21:34:59.000Z
|
bin/main.dart
|
KristobalJunta/helper_tgtoadbot
|
92306b2ae119d937e93a806730e976173dbb73de
|
[
"MIT"
] | 1
|
2021-07-15T16:50:26.000Z
|
2021-07-16T11:07:08.000Z
|
bin/main.dart
|
KristobalJunta/helper_tgtoadbot
|
92306b2ae119d937e93a806730e976173dbb73de
|
[
"MIT"
] | 2
|
2021-05-05T19:02:27.000Z
|
2021-06-17T10:19:33.000Z
|
import 'package:intl/date_symbol_data_local.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'commands.dart';
import 'services.dart';
void main(List<String> arguments) {
tz.initializeTimeZones();
initializeDateFormatting('ua_UK');
Services.setup();
Commands.setup();
}
| 21.071429
| 50
| 0.749153
|
7df414c3ab1db8d4edf3379e593b863676e95da4
| 8,309
|
rb
|
Ruby
|
lib/clt/cvs.rb
|
CalvertYang/clt-sdk
|
02743ca1525410a956d1189e26e21f8829a2cdfa
|
[
"MIT"
] | null | null | null |
lib/clt/cvs.rb
|
CalvertYang/clt-sdk
|
02743ca1525410a956d1189e26e21f8829a2cdfa
|
[
"MIT"
] | null | null | null |
lib/clt/cvs.rb
|
CalvertYang/clt-sdk
|
02743ca1525410a956d1189e26e21f8829a2cdfa
|
[
"MIT"
] | null | null | null |
module Clt
class Cvs
include GeneralMethods
def initialize
raise ArgumentError, 'Please setup cvs_cust_id first' if Clt.cvs_cust_id.nil?
ErrorMessage.raise_error(msg: :parameter_should_be, field: :cvs_cust_id, data: :String) unless Clt.cvs_cust_id.is_a? String
ErrorMessage.raise_error(msg: :cannot_be_empty, field: :cvs_cust_id) if Clt.cvs_cust_id.empty?
raise ArgumentError, 'Please setup cvs_cust_password first' if Clt.cvs_cust_password.nil?
ErrorMessage.raise_error(msg: :parameter_should_be, field: :cvs_cust_password, data: :String) unless Clt.cvs_cust_password.is_a? String
ErrorMessage.raise_error(msg: :cannot_be_empty, field: :cvs_cust_password) if Clt.cvs_cust_password.empty?
ErrorMessage.raise_error(msg: :parameter_should_be, field: :cvs_default_expire_day, data: :Integer) unless Clt.cvs_default_expire_day.is_a? Integer
ErrorMessage.raise_error(msg: :parameter_should_be, field: :cvs_default_expire_day, data: 'greater than 0') if Clt.cvs_default_expire_day <= 0
end
def order_create(params = {})
ErrorMessage.raise_error(msg: :parameter_should_be, field: :Parameter, data: :Hash) unless params.is_a? Hash
ErrorMessage.raise_error(msg: :missing_parameter, field: :service_url) if params[:service_url].nil?
ErrorMessage.raise_error(msg: :parameter_should_be, field: :service_url, data: :String) unless params[:service_url].is_a? String
ErrorMessage.raise_error(msg: :cannot_be_empty, field: :service_url) if params[:service_url].empty?
ErrorMessage.raise_error(msg: :missing_parameter, field: :cust_order_number) if params[:cust_order_number].nil?
ErrorMessage.raise_error(msg: :parameter_should_be, field: :cust_order_number, data: :String) unless params[:cust_order_number].is_a? String
ErrorMessage.raise_error(msg: :cannot_be_empty, field: :cust_order_number) if params[:cust_order_number].empty?
ErrorMessage.raise_error(msg: :missing_parameter, field: :order_amount) if params[:order_amount].nil?
ErrorMessage.raise_error(msg: :parameter_should_be, field: :order_amount, data: :Integer) unless params[:order_amount].is_a? Integer
if params.has_key? :expire_date
ErrorMessage.raise_error(msg: :parameter_should_be, field: :expire_date, data: :String) unless params[:expire_date].is_a? String
ErrorMessage.raise_error(msg: :cannot_be_empty, field: :expire_date) if params[:expire_date].empty?
ErrorMessage.raise_error(msg: :wrong_data_format, field: :expire_date) unless /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+\d{2}:\d{2}\z/.match(params[:expire_date])
end
if params.has_key? :payer_name
ErrorMessage.raise_error(msg: :parameter_should_be, field: :payer_name, data: :String) unless params[:payer_name].is_a? String
end
if params.has_key? :payer_postcode
ErrorMessage.raise_error(msg: :parameter_should_be, field: :payer_postcode, data: :String) unless params[:payer_postcode].is_a? String
end
if params.has_key? :payer_address
ErrorMessage.raise_error(msg: :parameter_should_be, field: :payer_address, data: :String) unless params[:payer_address].is_a? String
end
ErrorMessage.raise_error(msg: :missing_parameter, field: :payer_mobile) if params[:payer_mobile].nil?
ErrorMessage.raise_error(msg: :parameter_should_be, field: :payer_mobile, data: :String) unless params[:payer_mobile].is_a? String
ErrorMessage.raise_error(msg: :cannot_be_empty, field: :payer_mobile) if params[:payer_mobile].empty?
ErrorMessage.raise_error(msg: :missing_parameter, field: :payer_email) if params[:payer_email].nil?
ErrorMessage.raise_error(msg: :parameter_should_be, field: :payer_email, data: :String) unless params[:payer_email].is_a? String
ErrorMessage.raise_error(msg: :cannot_be_empty, field: :payer_email) if params[:payer_email].empty?
expire_date = params.has_key?(:expire_date) ? params[:expire_date] : get_cvs_default_expire_date
# build xml data
builder = Nokogiri::XML::Builder.new(encoding: 'UTF-8') do
request {
header {
cmd 'cvs_order_regiater'
cust_id Clt.cvs_cust_id
cust_password Clt.cvs_cust_password
}
order {
cust_order_number params[:cust_order_number]
order_amount params[:order_amount]
expire_date expire_date
payer_name params[:payer_name]
payer_postcode params[:payer_postcode]
payer_address params[:payer_address]
payer_mobile params[:payer_mobile]
payer_email params[:payer_email]
}
}
end
post_request(service_url: params[:service_url], data: builder.to_xml)
end
def order_query(params = {})
ErrorMessage.raise_error(msg: :parameter_should_be, field: :Parameter, data: :Hash) unless params.is_a? Hash
ErrorMessage.raise_error(msg: :missing_parameter, field: :service_url) if params[:service_url].nil?
ErrorMessage.raise_error(msg: :parameter_should_be, field: :service_url, data: :String) unless params[:service_url].is_a? String
ErrorMessage.raise_error(msg: :cannot_be_empty, field: :service_url) if params[:service_url].empty?
ErrorMessage.raise_error(msg: :missing_parameter, field: :process_code_update_time_begin) if params[:process_code_update_time_begin].nil?
ErrorMessage.raise_error(msg: :parameter_should_be, field: :process_code_update_time_begin, data: :String) unless params[:process_code_update_time_begin].is_a? String
ErrorMessage.raise_error(msg: :cannot_be_empty, field: :process_code_update_time_begin) if params[:process_code_update_time_begin].empty?
ErrorMessage.raise_error(msg: :wrong_data_format, field: :process_code_update_time_begin) unless /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+\d{2}:\d{2}\z/.match(params[:process_code_update_time_begin])
ErrorMessage.raise_error(msg: :missing_parameter, field: :process_code_update_time_end) if params[:process_code_update_time_end].nil?
ErrorMessage.raise_error(msg: :parameter_should_be, field: :process_code_update_time_end, data: :String) unless params[:process_code_update_time_end].is_a? String
ErrorMessage.raise_error(msg: :cannot_be_empty, field: :process_code_update_time_end) if params[:process_code_update_time_end].empty?
ErrorMessage.raise_error(msg: :wrong_data_format, field: :process_code_update_time_end) unless /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+\d{2}:\d{2}\z/.match(params[:process_code_update_time_end])
builder = Nokogiri::XML::Builder.new(encoding: 'UTF-8') do
request {
header {
cmd 'cvs_order_query'
cust_id Clt.cvs_cust_id
cust_password Clt.cvs_cust_password
}
query {
process_code_update_time_begin params[:process_code_update_time_begin]
process_code_update_time_end params[:process_code_update_time_end]
}
}
end
post_request(service_url: params[:service_url], data: builder.to_xml)
end
private
def get_cvs_default_expire_date
seconds_in_a_day = 60 * 60 * 24
offset = seconds_in_a_day * Clt.cvs_default_expire_day
# get and converts time to local time
current_time = Time.now.localtime('+08:00')
(current_time + offset).iso8601
end
def post_request(service_url:, data:)
api_url = URI.parse(service_url)
http = Net::HTTP.new(api_url.host, api_url.port)
http.use_ssl = true if api_url.scheme == 'https'
response = http.post(api_url.request_uri, data, { 'Content-Type' => 'text/xml' })
case response
when Net::HTTPOK
parser = Nori.new(advanced_typecasting: false)
begin
response_hash = parser.parse(response.body)['response']
rescue
response_hash = { 'status' => 'ERROR', 'msg' => 'Response parsing failed', 'response' => response.body }
end
response_hash
when Net::HTTPClientError, Net::HTTPInternalServerError
raise Net::HTTPError, response.message
else
raise Net::HTTPError, 'Unexpected HTTP response'
end
end
end
end
| 52.923567
| 204
| 0.713323
|
cc5a9d596d4afc80a12b0ee613984fb040d0ac92
| 301
|
rb
|
Ruby
|
lib/matestack_engine_boilerplate.rb
|
sebyx07/matestack_engine_boilerplate
|
9322a1c5d5a13311a847f0b7f59fc78cee0e6d72
|
[
"MIT"
] | 2
|
2021-11-25T09:44:12.000Z
|
2022-02-14T01:52:00.000Z
|
lib/matestack_engine_boilerplate.rb
|
sebyx07/matestack_engine_boilerplate
|
9322a1c5d5a13311a847f0b7f59fc78cee0e6d72
|
[
"MIT"
] | null | null | null |
lib/matestack_engine_boilerplate.rb
|
sebyx07/matestack_engine_boilerplate
|
9322a1c5d5a13311a847f0b7f59fc78cee0e6d72
|
[
"MIT"
] | 1
|
2021-11-25T16:08:29.000Z
|
2021-11-25T16:08:29.000Z
|
# frozen_string_literal: true
require "matestack_engine_boilerplate/version"
require "matestack_engine_boilerplate/engine"
require "bundler/setup"
require "matestack/ui/core"
require "matestack/ui/bootstrap"
require "importmap-rails"
module MatestackEngineBoilerplate
# Your code goes here...
end
| 23.153846
| 46
| 0.82392
|
3f8b554234e3384cf26a3165901893ee8457ec2e
| 2,129
|
php
|
PHP
|
Controller/CRUDController.php
|
softlogo/cms-bundle
|
b8d062a5fe799866ba0226591adbf9504a7c911c
|
[
"CC0-1.0"
] | null | null | null |
Controller/CRUDController.php
|
softlogo/cms-bundle
|
b8d062a5fe799866ba0226591adbf9504a7c911c
|
[
"CC0-1.0"
] | null | null | null |
Controller/CRUDController.php
|
softlogo/cms-bundle
|
b8d062a5fe799866ba0226591adbf9504a7c911c
|
[
"CC0-1.0"
] | null | null | null |
<?php // src/Softlogo/CMSBundle/Controller/CRUDController.php
namespace Softlogo\CMSBundle\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Sonata\AdminBundle\Controller\CRUDController as Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Softlogo\CMSBundle\Util\SoftlogoAuditReader as Reader;
use SimpleThings\EntityAudit\Metadata\MetadataFactory;
use SimpleThings\EntityAudit\AuditConfiguration;
class CRUDController extends Controller
{
public function restoreAction($id=6, $revision=80)
{
$revision=$_GET['revision'];
$object = $this->admin->getSubject();
$em = $this->container->get('doctrine')->getEntityManager();
$className = $em->getClassMetadata(get_class($object))->getName();
$auditedEntities[0]=$className;
$factory=new MetadataFactory($auditedEntities);
$config= new AuditConfiguration();
//$id=$object->getId();
/*
*if (!$object) {
* throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
*}
*/
$reader= new Reader($em, $config, $factory);
$reader->restore($className, $id, $revision);
$this->addFlash('sonata_flash_success',"Przywrócono wcześniejszą wersję." );
//return new RedirectResponse($this->admin->generateUrl('view'));
return new RedirectResponse($this->admin->generateObjectUrl('history_view_revision', $object, array('revision'=>$revision)) );
}
public function cloneAction()
{
$object = $this->admin->getSubject();
if (!$object) {
throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
}
$clonedObject = clone $object; // Careful, you may need to overload the __clone method of your object
// to set its id to null
$clonedObject->setName($object->getName()." (Kopia)");
$this->admin->create($clonedObject);
$this->addFlash('sonata_flash_success', 'Cloned successfully');
return new RedirectResponse($this->admin->generateUrl('list'));
}
}
| 35.483333
| 134
| 0.674965
|
3f9d9f688c44242393d9f7cfe286fbbdcbd49e2b
| 59
|
rb
|
Ruby
|
lib/rspec/nlet/version.rb
|
masakazutakewaka/rspec-nlet
|
abb3540cad6a1620a26cb097509e1a25bb302ea7
|
[
"MIT"
] | null | null | null |
lib/rspec/nlet/version.rb
|
masakazutakewaka/rspec-nlet
|
abb3540cad6a1620a26cb097509e1a25bb302ea7
|
[
"MIT"
] | null | null | null |
lib/rspec/nlet/version.rb
|
masakazutakewaka/rspec-nlet
|
abb3540cad6a1620a26cb097509e1a25bb302ea7
|
[
"MIT"
] | null | null | null |
module Rspec
module Nlet
VERSION = "0.1.0"
end
end
| 9.833333
| 21
| 0.627119
|
259b179b785cb4267dbd9b5d7c1cb5594355ab2e
| 2,025
|
cs
|
C#
|
WebTest/WebTest/Operation/GetStateBySource.cs
|
ZumWalt22/WebBrowserTest
|
0c1fad3a4c05fa7e840f0b5904f86abadc6e3436
|
[
"MIT"
] | 1
|
2019-09-07T23:02:29.000Z
|
2019-09-07T23:02:29.000Z
|
WebTest/WebTest/Operation/GetStateBySource.cs
|
ZumWalt22/WebBrowserTest
|
0c1fad3a4c05fa7e840f0b5904f86abadc6e3436
|
[
"MIT"
] | null | null | null |
WebTest/WebTest/Operation/GetStateBySource.cs
|
ZumWalt22/WebBrowserTest
|
0c1fad3a4c05fa7e840f0b5904f86abadc6e3436
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
namespace WindowsFormsApplication1
{
/// <summary>
/// HTMLソースを元に値を取得する
/// </summary>
class GetStateBySource : Operation
{
//基底クラスのコンストラクタを「: base(webBrowser)」で呼び出すためのコンストラクタ
public GetStateBySource(WebBrowserReceiver webBrowserReceiver)
: base(webBrowserReceiver,false)
{
}
/// <summary>
/// 画面のIDに対する値を取得する
///
/// </summary>
/// <param name="inValue">取得する値の正規表現</param>
/// <returns>値</returns>
protected override object doneImpl(object inValue)
{
//HTMLのテキストを取得
//文字コード変換(eucをsjisに)
Encoding enceuc = Encoding.GetEncoding("euc-jp");
Encoding encsjs = Encoding.GetEncoding("shift_jis");
byte[] beuc = new byte[webBrowserReceiver.webBrowser.DocumentStream.Length];
webBrowserReceiver.webBrowser.DocumentStream.Read(beuc, 0, (int)webBrowserReceiver.webBrowser.DocumentStream.Length);
byte[] bsjs = Encoding.Convert(enceuc, encsjs, beuc);
string htmlText = encsjs.GetString(bsjs);
//正規表現
string regexPatern = (string)inValue;
//Regexオブジェクトを作成
System.Text.RegularExpressions.Regex r = new Regex(regexPatern,RegexOptions.IgnoreCase);
//正規表現と一致する対象を1つ検索
Match m = r.Match(htmlText);
string matchStr = "";
if (m.Groups.Count > 0)
{
matchStr = m.Groups[1].Value;
//ログ出力
setLogInfoStr("Get Regex Patern", "Regex Patern", regexPatern);
}
else
{
//ログ出力
setLogWarnStr("Get Regex Patern", "Regex Patern Not Exist", regexPatern);
}
//正規表現に一致した値を返却
return matchStr;
}
}
}
| 28.125
| 129
| 0.57037
|
cf5dce9a03ded7ca7df7cfcc294f56507ccbe1eb
| 806
|
lua
|
Lua
|
lua/yode-nvim/logging.lua
|
David-Kunz/yode-nvim
|
df3ab1dae88c1473475023d59726b476e250b66d
|
[
"MIT"
] | 282
|
2022-02-11T16:50:52.000Z
|
2022-03-29T16:00:52.000Z
|
lua/yode-nvim/logging.lua
|
David-Kunz/yode-nvim
|
df3ab1dae88c1473475023d59726b476e250b66d
|
[
"MIT"
] | 8
|
2022-02-12T08:59:48.000Z
|
2022-03-23T07:57:44.000Z
|
lua/yode-nvim/logging.lua
|
David-Kunz/yode-nvim
|
df3ab1dae88c1473475023d59726b476e250b66d
|
[
"MIT"
] | 4
|
2022-02-11T21:28:22.000Z
|
2022-03-04T18:29:07.000Z
|
local PlenaryLog = require('plenary.log')
local R = require('yode-nvim.deps.lamda.dist.lamda')
local M = {}
local isDebug = require('yode-nvim.isDebug')
-- https://github.com/nvim-lua/plenary.nvim/blob/80c9e00a6d7632fdebd959a18452604b862a6ebf/lua/plenary/log.lua#L14
local base
local modes = { 'trace', 'debug', 'info', 'warn', 'error', 'fatal' }
M.setup = function(options)
local conf = vim.tbl_deep_extend('force', options, {
plugin = 'yode-nvim',
level = isDebug and isDebug or 'warn',
})
base = PlenaryLog.new(conf)
end
M.create = function(name)
local prefix = name .. ':'
return R.reduce(function(obj, mode)
return R.assoc(mode, function(...)
return base[mode]('\n', '🔹' .. prefix, ...)
end, obj)
end, base, modes)
end
return M
| 27.793103
| 113
| 0.637717
|
0df8244cb45a4c7e4d53468a719c8d655f33c8a2
| 2,157
|
css
|
CSS
|
src/css/reg.css
|
xzxbbt/chinaanta
|
dbed6810d358cb15f31648895cd3da93526ae833
|
[
"Apache-2.0"
] | 1
|
2022-01-24T03:20:43.000Z
|
2022-01-24T03:20:43.000Z
|
src/css/reg.css
|
xzxbbt/chinaanta
|
dbed6810d358cb15f31648895cd3da93526ae833
|
[
"Apache-2.0"
] | null | null | null |
src/css/reg.css
|
xzxbbt/chinaanta
|
dbed6810d358cb15f31648895cd3da93526ae833
|
[
"Apache-2.0"
] | null | null | null |
.wrapper {
width: 100%;
min-width: 1280px;
height: 600px;
}
.wrap {
width: 100%;
min-height: 100%;
height: auto;
padding: 50px 0 0 0;
background: url(../img/login-01.jpg) no-repeat;
background-size: 100% auto;
}
.reg-box {
height: 500px;
position: relative;
}
.reg {
position: absolute;
right: 0;
padding: 72px 0 0 0;
width: 500px;
height: 428px;
background-color: white;
}
.reg-title {
width: 356px;
/* height: 45px; */
margin: 0 auto;
padding: 10px 0;
}
.reg-title div {
height: 35px;
width: 50%;
float: left;
line-height: 35px;
cursor: pointer;
text-align: center;
color: #999;
background: #fbfbfb;
}
.reg-title div:first-child {
color: white;
background-color: rgb(34, 34, 34);
}
.reg-main {
width: 356px;
margin: 0 auto;
}
/* .phone-main */
.phone-main {
display: block;
}
.email-main {
display: none;
}
.reg-main p {
color: #666;
font-weight: 800;
margin: 10px 0 10px;
}
.phone-main form > input:nth-of-type(1),
.phone-main form > input:nth-of-type(2) {
width: 328px;
height: 16px;
margin: 10px 0;
padding: 13px 14px;
border: 1px #ccc solid;
}
.verification {
width: 356px;
}
.verification input {
width: 210px;
float: left;
height: 16px;
margin: 10px 0;
padding: 13px 14px;
border: 1px #ccc solid;
}
.verification span {
display: block;
float: left;
width: 111px;
height: 36px;
/*margin-top: 13px;*/
margin-left: 5px;
}
#captcha {
margin-top: 10px;
}
.clause input {
position: relative;
top: 1px;
}
.error_prompt {
display: block;
margin: 10px 0 13px;
color: red;
font-size: 12px;
}
#phoneSubmit {
width: 360px;
height: 53px;
text-align: center;
line-height: 53px;
font-size: 16px;
background-color: black;
color: white;
border: 1px #ccc solid;
cursor: pointer;
}
/* email-main */
.email-main form > input:nth-of-type(1),
.email-main form > input:nth-of-type(2) {
width: 328px;
height: 16px;
margin: 10px 0;
padding: 13px 14px;
border: 1px #ccc solid;
}
.email-main form > input[type="button"] {
width: 360px;
height: 53px;
text-align: center;
line-height: 53px;
font-size: 16px;
background-color: black;
color: white;
border: 1px #ccc solid;
cursor: pointer;
}
| 15.977778
| 48
| 0.658785
|
5917de2e81ac36a4ab9889210743b4cc503e7729
| 10,113
|
swift
|
Swift
|
Sources/Constaints/LemonadeConstraint+View.swift
|
nektarapps/LemonadeUI
|
1138179a693ba40a6fdade7aee3e1b60dbb5ebc4
|
[
"MIT"
] | 3
|
2021-09-17T11:03:43.000Z
|
2022-01-06T14:32:56.000Z
|
Sources/Constaints/LemonadeConstraint+View.swift
|
nektarapps/LemonadeUI
|
1138179a693ba40a6fdade7aee3e1b60dbb5ebc4
|
[
"MIT"
] | null | null | null |
Sources/Constaints/LemonadeConstraint+View.swift
|
nektarapps/LemonadeUI
|
1138179a693ba40a6fdade7aee3e1b60dbb5ebc4
|
[
"MIT"
] | null | null | null |
//
// LemonadeConstraint+View.swift
// LemonadeUI
//
// Created by Hasan Özgür Elmaslı on 11.08.2021.
//
import UIKit
extension UIView {
/**
Filling all views with padding. Default padding values 0.0
- parameter padding: Default values 0.0.
- returns: None
- warning: If superView is nil , function will return fatalError
*/
public func fill2SuperView( _ padding : LemonadePadding = .init()){
if superview == nil { fatalError( LemonadeConstraintError.superViewError.rawValue )}
self.top(superview!, equalTo: .top , constant: padding.top)
self.left(superview!, equalTo: .left , constant: padding.left)
self.right(superview!, equalTo: .right , constant: -padding.right)
self.bottom(superview!, equalTo: .bottom , constant: -padding.bottom)
}
public func center(to : UIView , width : CGFloat , height : CGFloat) {
self.centerX(to, equalTo: .centerX)
self.centerY(to, equalTo: .centerY)
self.width(constant: width)
self.height(constant: height)
}
public func center(to : UIView) {
self.centerX(to, equalTo: .centerX)
self.centerY(to, equalTo: .centerY)
}
/**
Width and Height equal anchor settings
- parameter to: Anchor will connect to this View
- parameter equalTo: Anchor Type
- parameter constant: Margin between to view. Default value 0.0
- parameter multiplier: Multiple to connected View height anchor
- returns: None
- warning: If superView is nil , function will return fatalError
*/
public func widthAndHeight( _ to : UIView , equalTo : LemonadeConstraintBounds , constant : CGFloat = 0.0 , multiplier : CGFloat = 1.0 , safeArea : Bool = false) {
self.height(to, equalTo: equalTo, constant: constant, multiplier: multiplier, safeArea: safeArea)
self.width(to, equalTo: equalTo, constant: constant, multiplier: multiplier, safeArea: safeArea)
}
/**
Width and Height constant value
- parameter constant: Bound value
- returns: None
- warning: If superView is nil , function will return fatalError
*/
public func widthAndHeight(constant : CGFloat) {
self.height(constant: constant)
self.width(constant: constant)
}
public func leftAndRight( _ to : UIView , constant : CGFloat = 0.0 , safeArea : Bool = false) {
self.left(to, equalTo: .left, constant: constant, safeArea: safeArea)
self.right(to, equalTo: .right, constant: -constant, safeArea: safeArea)
}
/// Ratio
}
extension UIView {
/**
Left anchor settings
- parameter to: Anchor will connect to this View
- parameter equalTo: Anchor Type
- parameter constant: Margin between to view. Default value 0.0
- returns: None
- warning: If superView is nil , function will return fatalError
*/
public func left( _ to : UIView , equalTo : LemonadeConstraint , constant : CGFloat = 0.0 , safeArea : Bool = false) {
if superview == nil { fatalError( LemonadeConstraintError.superViewError.rawValue )}
self.translatesAutoresizingMaskIntoConstraints = false
let constaint : LemonadeConstraint = .left
constaint.equalToConstraint(currentView: self, to: to, equalTo: equalTo , constant: constant , safeArea: safeArea)
}
/**
Right anchor settings
- parameter to: Anchor will connect to this View
- parameter equalTo: Anchor Type
- parameter constant: Margin between to view. Default value 0.0
- returns: None
- warning: If superView is nil , function will return fatalError
*/
public func right( _ to : UIView , equalTo : LemonadeConstraint , constant : CGFloat = 0.0 , safeArea : Bool = false) {
if superview == nil { fatalError( LemonadeConstraintError.superViewError.rawValue )}
self.translatesAutoresizingMaskIntoConstraints = false
let constaint : LemonadeConstraint = .right
constaint.equalToConstraint(currentView: self, to: to, equalTo: equalTo , constant: constant , safeArea: safeArea)
}
/**
Top anchor settings
- parameter to: Anchor will connect to this View
- parameter equalTo: Anchor Type
- parameter constant: Margin between to view. Default value 0.0
- returns: None
- warning: If superView is nil , function will return fatalError
*/
public func top( _ to : UIView , equalTo : LemonadeConstraint , constant : CGFloat = 0.0 , safeArea : Bool = false) {
if superview == nil { fatalError( LemonadeConstraintError.superViewError.rawValue )}
self.translatesAutoresizingMaskIntoConstraints = false
let constaint : LemonadeConstraint = .top
constaint.equalToConstraint(currentView: self, to: to, equalTo: equalTo , constant: constant , safeArea: safeArea)
}
/**
Bottom anchor settings
- parameter to: Anchor will connect to this View
- parameter equalTo: Anchor Type
- parameter constant: Margin between to view. Default value 0.0
- returns: None
- warning: If superView is nil , function will return fatalError
*/
public func bottom( _ to : UIView , equalTo : LemonadeConstraint , constant : CGFloat = 0.0 , safeArea : Bool = false) {
if superview == nil { fatalError( LemonadeConstraintError.superViewError.rawValue )}
self.translatesAutoresizingMaskIntoConstraints = false
let constaint : LemonadeConstraint = .bottom
constaint.equalToConstraint(currentView: self, to: to, equalTo: equalTo , constant: constant , safeArea: safeArea)
}
/**
CenterX anchor settings
- parameter to: Anchor will connect to this View
- parameter equalTo: Anchor Type
- parameter constant: Margin between to view. Default value 0.0
- returns: None
- warning: If superView is nil , function will return fatalError
*/
public func centerX( _ to : UIView , equalTo : LemonadeConstraint , constant : CGFloat = 0.0 , safeArea : Bool = false) {
if superview == nil { fatalError( LemonadeConstraintError.superViewError.rawValue )}
self.translatesAutoresizingMaskIntoConstraints = false
let constaint : LemonadeConstraint = .centerX
constaint.equalToConstraint(currentView: self, to: to, equalTo: equalTo , constant: constant , safeArea: safeArea)
}
/**
CenterY anchor settings
- parameter to: Anchor will connect to this View
- parameter equalTo: Anchor Type
- parameter constant: Margin between to view. Default value 0.0
- returns: None
- warning: If superView is nil , function will return fatalError
*/
public func centerY( _ to : UIView , equalTo : LemonadeConstraint , constant : CGFloat = 0.0 , safeArea : Bool = false) {
if superview == nil { fatalError( LemonadeConstraintError.superViewError.rawValue )}
self.translatesAutoresizingMaskIntoConstraints = false
let constaint : LemonadeConstraint = .centerY
constaint.equalToConstraint(currentView: self, to: to, equalTo: equalTo , constant: constant , safeArea: safeArea)
}
}
extension UIView {
/**
Width equal anchor settings
- parameter to: Anchor will connect to this View
- parameter equalTo: Anchor Type
- parameter constant: Margin between to view. Default value 0.0
- parameter multiplier: Multiple to connected View Width anchor
- returns: None
- warning: If superView is nil , function will return fatalError
*/
public func width( _ to : UIView , equalTo : LemonadeConstraintBounds , constant : CGFloat = 0.0 , multiplier : CGFloat = 1.0 , safeArea : Bool = false) {
if superview == nil { fatalError( LemonadeConstraintError.superViewError.rawValue )}
self.translatesAutoresizingMaskIntoConstraints = false
let constraint : LemonadeConstraintBounds = .width
constraint.equalTo(currentView: self, to: to, equalTo: equalTo, constant: constant, multiplier: multiplier , safeArea: safeArea)
}
/**
Width value
- parameter constant: Bound value
- returns: None
- warning: If superView is nil , function will return fatalError
*/
public func width(constant : CGFloat) {
// if superview == nil { fatalError( LemonadeConstraintError.superViewError.rawValue )}
self.translatesAutoresizingMaskIntoConstraints = false
let constraint : LemonadeConstraintBounds = .width
constraint.constant(currentView: self, type: .width, constant: constant)
}
/**
Height equal anchor settings
- parameter to: Anchor will connect to this View
- parameter equalTo: Anchor Type
- parameter constant: Margin between to view. Default value 0.0
- parameter multiplier: Multiple to connected View height anchor
- returns: None
- warning: If superView is nil , function will return fatalError
*/
public func height( _ to : UIView , equalTo : LemonadeConstraintBounds , constant : CGFloat = 0.0 , multiplier : CGFloat = 1.0 , safeArea : Bool = false) {
if superview == nil { fatalError( LemonadeConstraintError.superViewError.rawValue )}
self.translatesAutoresizingMaskIntoConstraints = false
let constraint : LemonadeConstraintBounds = .height
constraint.equalTo(currentView: self, to: to, equalTo: equalTo, constant: constant, multiplier: multiplier , safeArea: safeArea )
}
/**
Height value
- parameter constant: Bound value
- returns: None
- warning: If superView is nil , function will return fatalError
*/
public func height(constant : CGFloat) {
// if superview == nil { fatalError( LemonadeConstraintError.superViewError.rawValue )}
self.translatesAutoresizingMaskIntoConstraints = false
let constraint : LemonadeConstraintBounds = .height
constraint.constant(currentView: self, type: .height, constant: constant)
}
}
| 43.034043
| 167
| 0.674973
|
b606613bd034409015312aa7d81412a5bc0fd1f0
| 166
|
asm
|
Assembly
|
text/maps/cerulean_trade_house.asm
|
etdv-thevoid/pokemon-rgb-enhanced
|
5b244c1cf46aab98b9c820d1b7888814eb7fa53f
|
[
"MIT"
] | 9
|
2020-07-12T19:44:21.000Z
|
2022-03-03T23:32:40.000Z
|
text/maps/CeruleanTradeHouse.asm
|
JStar-debug2020/pokemon-rby-dx
|
c2fdd8145d96683addbd8d9075f946a68d1527a1
|
[
"MIT"
] | 7
|
2020-07-16T10:48:52.000Z
|
2021-01-28T18:32:02.000Z
|
text/maps/CeruleanTradeHouse.asm
|
JStar-debug2020/pokemon-rby-dx
|
c2fdd8145d96683addbd8d9075f946a68d1527a1
|
[
"MIT"
] | 2
|
2021-03-28T18:33:43.000Z
|
2021-05-06T13:12:09.000Z
|
_CeruleanHouse1Text1::
text "My husband likes"
line "trading #MON."
para "If you are a"
line "collector, would"
cont "you please trade"
cont "with him?"
done
| 16.6
| 24
| 0.698795
|
21123bc810556887e9b2bb10c9d3b029d0fbd815
| 2,167
|
swift
|
Swift
|
PickerVIewChallenge/PickerVIewChallenge/ViewController.swift
|
fawkes32/swiftCourse
|
f35602350353f8c657886e3896237448d7b2190c
|
[
"MIT"
] | null | null | null |
PickerVIewChallenge/PickerVIewChallenge/ViewController.swift
|
fawkes32/swiftCourse
|
f35602350353f8c657886e3896237448d7b2190c
|
[
"MIT"
] | null | null | null |
PickerVIewChallenge/PickerVIewChallenge/ViewController.swift
|
fawkes32/swiftCourse
|
f35602350353f8c657886e3896237448d7b2190c
|
[
"MIT"
] | null | null | null |
//
// ViewController.swift
// PickerVIewChallenge
//
// Created by Daniel Marquez on 6/23/15.
// Copyright (c) 2015 Tec de Monterrey. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
var sex = ["Masculino","Femenino"]
let alert = UIAlertView()
@IBOutlet weak var txtName: UITextField!
@IBOutlet weak var txtAge: UITextField!
@IBOutlet weak var pickerSex: UIPickerView!
@IBOutlet weak var lblResult: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func btnSend(sender: AnyObject) {
if !txtName.text.isEmpty && !txtAge.text.isEmpty{
if txtAge.text.toInt()! >= 18{
lblResult.text = "\(txtName.text) si puedes votar y tu sexo es \(sex[pickerSex.selectedRowInComponent(0)])"
} else{
lblResult.text = "\(txtName.text) no puedes votar y tu sexo es \(sex[pickerSex.selectedRowInComponent(0)])"
}
}else{
self.alert.title = "Error"
self.alert.message = "Tienes que insertar datos"
self.alert.addButtonWithTitle("OK")
self.alert.show()
}
}
// returns the number of 'columns' to display.
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{
return 1
}
// returns the # of rows in each component..
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
return self.sex.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return self.sex[row]
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.view.endEditing(true)
}
}
| 27.782051
| 124
| 0.62575
|
2176635c2f65aa07ab726013315a8b98fe41ae42
| 828
|
js
|
JavaScript
|
zipinfo_browser.js
|
ikreymer/zipinfo.js
|
56fadfed121263b38ee85746ede6a2b23ed9f41a
|
[
"MIT"
] | 23
|
2017-09-01T20:36:49.000Z
|
2022-03-16T22:35:24.000Z
|
zipinfo_browser.js
|
ikreymer/zipinfo.js
|
56fadfed121263b38ee85746ede6a2b23ed9f41a
|
[
"MIT"
] | 1
|
2020-05-24T04:49:32.000Z
|
2020-05-24T21:49:53.000Z
|
zipinfo_browser.js
|
ikreymer/zipinfo.js
|
56fadfed121263b38ee85746ede6a2b23ed9f41a
|
[
"MIT"
] | 6
|
2017-10-16T09:53:01.000Z
|
2021-07-17T09:18:24.000Z
|
/* globals ZipInfo, XMLHttpRequest, Uint8Array */
'use strict';
ZipInfo.getRemoteEntries = function(url, onGotEntries) {
function sendHttpRequest(params) {
var x = new XMLHttpRequest();
x.open('GET', url);
x.responseType = 'arraybuffer';
if (params.rangeHeader) {
x.setRequestHeader('Range', params.rangeHeader);
}
x.onreadystatechange = params.onHeadersReceived && function() {
if (x.readyState === 2) {
params.onHeadersReceived(x.getResponseHeader.bind(x));
}
};
x.onloadend = function() {
params.onCompleted(new Uint8Array(x.response || 0));
};
x.send();
return {
abort: function() {
x.onreadystatechange = x.onloadend = null;
x.abort();
}
};
}
ZipInfo.runGetEntriesOverHttp(sendHttpRequest, onGotEntries);
};
| 27.6
| 67
| 0.630435
|
d412967a39060b190d0b363a901545085cfc91e9
| 249
|
cpp
|
C++
|
1300_ladder/200B.cpp
|
saivarshith2000/A20J
|
2faa77eb10ce93cb1822fffba278ef6a24b86cee
|
[
"MIT"
] | null | null | null |
1300_ladder/200B.cpp
|
saivarshith2000/A20J
|
2faa77eb10ce93cb1822fffba278ef6a24b86cee
|
[
"MIT"
] | null | null | null |
1300_ladder/200B.cpp
|
saivarshith2000/A20J
|
2faa77eb10ce93cb1822fffba278ef6a24b86cee
|
[
"MIT"
] | null | null | null |
// http://codeforces.com/problemset/problem/200/B
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
int sum = 0, temp;
for(int i = 0; i < n; i++){cin >> temp; sum += temp;}
cout << 100 * (1.0 * sum)/(100*n) << endl;
}
| 20.75
| 54
| 0.570281
|
da9fa159e882a56d5cdc6272d0f19327693d73c8
| 6,240
|
tsx
|
TypeScript
|
src/components/link/index.test.tsx
|
Vinnl/solid-ui-react
|
77d0347bd87e4086867dac0f71a7ee0ceddcbde8
|
[
"MIT"
] | 71
|
2020-10-01T21:11:51.000Z
|
2022-03-21T01:12:50.000Z
|
src/components/link/index.test.tsx
|
Vinnl/solid-ui-react
|
77d0347bd87e4086867dac0f71a7ee0ceddcbde8
|
[
"MIT"
] | 300
|
2020-09-25T06:03:27.000Z
|
2022-03-31T03:08:13.000Z
|
src/components/link/index.test.tsx
|
Vinnl/solid-ui-react
|
77d0347bd87e4086867dac0f71a7ee0ceddcbde8
|
[
"MIT"
] | 11
|
2020-11-24T13:43:52.000Z
|
2022-02-15T20:32:05.000Z
|
/**
* Copyright 2020 Inrupt Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import React from "react";
import { render } from "@testing-library/react";
import * as SolidFns from "@inrupt/solid-client";
import { Link } from "./index";
import * as helpers from "../../helpers";
const mockUrl = "http://test.url";
const mockPredicate = `http://xmlns.com/foaf/0.1/homepage`;
const mockThing = SolidFns.addUrl(
SolidFns.createThing(),
mockPredicate,
mockUrl
);
describe("Link component", () => {
it("Link snapshot", () => {
const { asFragment } = render(
<Link thing={mockThing} property={mockPredicate} />
);
expect(asFragment()).toMatchSnapshot();
});
it("renders default error message if there is an error", () => {
const documentBody = render(
<Link thing={mockThing} property="https://example.com/bad-url" />
);
const { baseElement } = documentBody;
expect(baseElement).toMatchSnapshot();
});
it("renders custom error component if passed and there is an error", () => {
const documentBody = render(
<Link
thing={mockThing}
property="https://example.com/bad-url"
errorComponent={({ error }) => (
<span id="custom-error-component">{error.toString()}</span>
)}
/>
);
const { baseElement } = documentBody;
expect(baseElement).toMatchSnapshot();
});
it("matches snapshot while fetching data", () => {
jest.spyOn(helpers, "useProperty").mockReturnValueOnce({
thing: undefined,
error: undefined,
value: null,
setDataset: jest.fn(),
setThing: jest.fn(),
property: mockPredicate,
});
const documentBody = render(<Link property={mockPredicate} />);
const { baseElement } = documentBody;
expect(baseElement).toMatchSnapshot();
});
it("renders loading component if passed while fetching data", () => {
jest.spyOn(helpers, "useProperty").mockReturnValueOnce({
thing: undefined,
error: undefined,
value: null,
setDataset: jest.fn(),
setThing: jest.fn(),
property: mockPredicate,
});
const documentBody = render(
<Link
property={mockPredicate}
loadingComponent={() => (
<span id="custom-loading-component">loading...</span>
)}
/>
);
const { baseElement } = documentBody;
expect(baseElement).toMatchSnapshot();
});
it("does not render default loading message if loadingComponent is null", () => {
jest.spyOn(helpers, "useProperty").mockReturnValueOnce({
thing: undefined,
error: undefined,
value: null,
setDataset: jest.fn(),
setThing: jest.fn(),
property: mockPredicate,
});
const documentBody = render(
<Link property={mockPredicate} loadingComponent={null} />
);
const { baseElement } = documentBody;
expect(baseElement).toMatchSnapshot();
});
it("Should call getUrl and use result as href value", () => {
jest.spyOn(SolidFns, "getUrl").mockImplementationOnce(() => mockUrl);
const { getByText } = render(
<Link thing={mockThing} property={mockPredicate} />
);
expect(SolidFns.getUrl).toHaveBeenCalled();
expect(getByText(mockUrl).getAttribute("href")).toBe(mockUrl);
});
it("When passed no children, should render href as link text", () => {
const { getByText } = render(
<Link thing={mockThing} property={mockPredicate} />
);
expect(getByText(mockUrl)).toBeTruthy();
});
it("When passed children, should render as link text", () => {
const { getByText } = render(
<Link thing={mockThing} property={mockPredicate}>
<span>Test child</span>
</Link>
);
expect(getByText("Test child")).toBeTruthy();
});
it("Passes down additional props to <a>", () => {
const { getByText } = render(
<Link
thing={mockThing}
property={mockPredicate}
className="test-class"
target="_self"
rel="abcd"
/>
);
expect(getByText(mockUrl).getAttribute("target")).toBe("_self");
expect(getByText(mockUrl).getAttribute("class")).toBe("test-class");
expect(getByText(mockUrl).getAttribute("rel")).toBe("abcd");
});
it("Defaults rel to 'noopener noreferrer' if target=_blank", () => {
const { getByText } = render(
<Link
thing={mockThing}
property={mockPredicate}
className="test-class"
target="_blank"
/>
);
expect(getByText(mockUrl).getAttribute("rel")).toBe("noopener noreferrer");
});
it("Overrides rel if passed in", () => {
const { getByText } = render(
<Link
thing={mockThing}
property={mockPredicate}
className="test-class"
target="_blank"
rel="test"
/>
);
expect(getByText(mockUrl).getAttribute("rel")).toBe("test");
});
it("renders in edit mode", () => {
const mockDataset = SolidFns.setThing(
SolidFns.createSolidDataset(),
mockThing
);
const { asFragment } = render(
<Link
thing={mockThing}
property={mockPredicate}
solidDataset={mockDataset}
/>
);
expect(asFragment()).toMatchSnapshot();
});
});
| 32.5
| 86
| 0.636699
|
5d2b2bdfd2c7213ade404ed98fd222e4caba2603
| 6,303
|
cpp
|
C++
|
sources/Notebook.cpp
|
noamv2/cppEx2b
|
d7ae12b27aae22d4dea8835c0942c727de10de4b
|
[
"MIT"
] | null | null | null |
sources/Notebook.cpp
|
noamv2/cppEx2b
|
d7ae12b27aae22d4dea8835c0942c727de10de4b
|
[
"MIT"
] | null | null | null |
sources/Notebook.cpp
|
noamv2/cppEx2b
|
d7ae12b27aae22d4dea8835c0942c727de10de4b
|
[
"MIT"
] | null | null | null |
#include <string>
#include <iostream>
#include <cctype>
#include "Direction.hpp"
#include "Notebook.hpp"
using namespace ariel;
using std::string;
bool Notebook::isIn(int key){
return notebook.count(key) != 0;
}
void Notebook::write(int page, int row, int col, Direction dir, string const & str){
if(page < 0 || row < 0 || col < 0){
throw "Invalid input";
}
for(auto c: str){
if(isprint(c) == 0 || c == '~'){
throw "Invalid input";
}
}
//Create the page if needed
if(!isIn(page)){
notebook[page] = Page();
}
notebook[page].writeRange(row, col, dir,str.length(), str);
}
string Notebook::read(int page, int row, int col, Direction dir, int len){
const int ROW_END = 99;
if(page < 0 || len < 0 || row < 0 || col < 0 || col > ROW_END){
throw "Invalid input";
}
//case we are reading page that wasnt created
if(!isIn(page)){
notebook[page] = Page();
}
return notebook[page].readRange(row, col, dir, len);
}
void Notebook::erase(int page, int row, int col, Direction dir, int len){
if(page < 0 || len < 0 || row < 0 || col < 0){
throw "Invalid input";
}
//case we are erasing in page that wasnt created yet
if(!isIn(page)){
notebook[page] = Page();
}
notebook[page].eraseData(row, col, dir, len);
}
void Notebook::show(int page){
if (page < 0){
throw "Cant have negetive page values";
}
std::cout<<notebook[page].readPage();
}
void Page::newLines(int num){
for(int i = 0 ; i < num ; i ++){
vector<char> v (ROW_END,'_');
rows.push_back(v);
}
}
void Page::writeRange(int row,int col,Direction dir, int len, std::string const & data){
if(len < 0 || row < 0 || col < 0){
throw "Invalid input";
}
//check if we have enough rows
int currLen = rows.size();
if(currLen == 0){
currLen--; //in case where the page is empty
}
int linesToAdd = 0;
if(dir == Direction::Vertical){
//Add new rows if needed
linesToAdd =(len - (currLen - row));
if(linesToAdd > 0){
newLines(linesToAdd);
}
//make sure that we are writing to empty cells
for(size_t i = static_cast<size_t>(row); i < len + row; i++){
if(rows.at(i).at(static_cast<size_t>(col)) != '_'){
throw "Cant write the same spot twice";
}
}
//write the actual data
for(char c: data){
rows.at(static_cast<size_t>(row)).at(static_cast<size_t>(col)) = c;
row++;
}
}
else{
//throw an exception if we are out of the row
if(len + col > ROW_END){
throw "Out of row error";
}
//Add new rows if needed
linesToAdd =(row - currLen + 1);
if(linesToAdd > 0){
newLines(linesToAdd);
}
int rowTemp = row;
//make sure that we are writing to empty cells
for(int i = col; i < col + len;i++){
if(rows.at(static_cast<size_t>(rowTemp)).at(static_cast<size_t>(i % ROW_END)) != '_'){
throw "Cant write the same spot twice";
}
rowTemp = row + i /ROW_END;
}
//write the actual data
for(char c: data){
rows.at(static_cast<size_t>(row)).at(static_cast<size_t>(col)) = c;
++col;
if(col == ROW_END){
col = 0;
++row;
}
}
}
}
std::string Page::readPage(){
std::string s;
for(size_t i = 0 ; i < rows.size(); i++){
s += std::to_string(i) + ": ";
s += std::string(rows.at(i).data()) +"\n";
}
return s;
}
void Page::eraseData(int row,int col,Direction dir, int len){
if(len < 0 || row < 0 || col < 0){
throw "Invalid input";
}
if(len < 0){
throw "Invalid length";
}
//check if we have enough rows
int currLen = rows.size();
if(currLen == 0){
currLen--; //in case where the page is empty
}
int linesToAdd = 0;
if(dir == Direction::Vertical){
//Add new rows if needed
linesToAdd =(len - (currLen - row));
if(linesToAdd > 0){
newLines(linesToAdd);
}
//make sure that we are writing to empty cells
for(int i = row; i < len + row; i++){
rows.at(static_cast<size_t>(i)).at(static_cast<size_t>(col)) = '~';
}
}
else{
if(len + col > ROW_END){
throw "Out of row error";
}
//Add new rows if needed
linesToAdd =(row - currLen + 1);
if(linesToAdd > 0){
newLines(linesToAdd);
}
int rowTemp = row;
//make sure that we are writing to empty cells
for(int i = col; i < col + len;i++){
rows.at(static_cast<size_t>(rowTemp)).at(static_cast<size_t>(i % ROW_END)) = '~';
rowTemp = row + i /ROW_END;
}
}
}
std::string Page::readRange(int row, int col, Direction dir, int len){
if(len < 0){
throw "Invalid length";
}
//fill the result string with '_' in case we want to read more then length of the notebook
std::string res(static_cast<size_t>(len), '_');
int index = 0;
if(dir == Direction::Vertical){
for(int i = row; i < rows.size() && index < len; i++){
res.replace(static_cast<size_t>(index),1,1,rows.at(static_cast<size_t>(i)).at(static_cast<size_t>(col)));
index++;
}
}
else{
if(len + col > ROW_END){
throw "Out of row error";
}
if (row >= rows.size()){
return res;
}
while(row != rows.size() && index < len){
res.replace(static_cast<size_t>(index),1,1,rows.at(static_cast<size_t>(row)).at(static_cast<size_t>(col)));
col++;
index++;
if(col == ROW_END){//go the next row if we reached the end of the current one
col = 0;
++row;
}
}
}
return res;
}
| 23.606742
| 119
| 0.503252
|
7fc7c74dee6206b92d434557cfb67366acc3ce87
| 546
|
php
|
PHP
|
app/Http/Controllers/Admin/PromotionImageController.php
|
Daimond-Red/order-management-system
|
cdbd599f5c8b738e0398c82cc5b469076a7d46f8
|
[
"MIT"
] | null | null | null |
app/Http/Controllers/Admin/PromotionImageController.php
|
Daimond-Red/order-management-system
|
cdbd599f5c8b738e0398c82cc5b469076a7d46f8
|
[
"MIT"
] | null | null | null |
app/Http/Controllers/Admin/PromotionImageController.php
|
Daimond-Red/order-management-system
|
cdbd599f5c8b738e0398c82cc5b469076a7d46f8
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Basecode\Classes\Repositories\PromotionImageRepository as Repository;
use App\Basecode\Classes\Permissions\Permission as Permission;
class PromotionImageController extends BackendController {
public $repository, $permission;
public function __construct(
Repository $repository,
Permission $permission
) {
$this->repository = $repository;
$this->permission = $permission;
}
}
| 24.818182
| 77
| 0.741758
|
6f6d99f44486fa43f60b7b00336c0c3bb565f311
| 5,008
|
dart
|
Dart
|
lib/main.dart
|
akhil2000mittal/ConsumerFlutterApp
|
64cd45829129be43faa30de5836cb4ce1e15c1ee
|
[
"MIT"
] | 52
|
2020-10-07T20:32:58.000Z
|
2022-03-15T10:19:59.000Z
|
lib/main.dart
|
akhil2000mittal/ConsumerFlutterApp
|
64cd45829129be43faa30de5836cb4ce1e15c1ee
|
[
"MIT"
] | 5
|
2020-10-07T05:36:06.000Z
|
2021-10-03T04:23:33.000Z
|
lib/main.dart
|
akhil2000mittal/ConsumerFlutterApp
|
64cd45829129be43faa30de5836cb4ce1e15c1ee
|
[
"MIT"
] | 30
|
2020-10-07T17:39:53.000Z
|
2022-01-21T10:25:03.000Z
|
import 'package:LaCoro/core/di/app_module.dart';
import 'package:LaCoro/core/localization/app_localizations_delegate.dart';
import 'package:LaCoro/presentation/adresses/addresses_page_new.dart';
import 'package:LaCoro/presentation/adresses/my_address_page.dart';
import 'package:LaCoro/presentation/checkout/checkout_page.dart';
import 'package:LaCoro/presentation/order_detail/order_detail_page.dart';
import 'package:LaCoro/presentation/order_history/order_history_page.dart';
import 'package:LaCoro/presentation/order_status/order_status_page.dart';
import 'package:LaCoro/presentation/past_order_detail/past_order_detail_page.dart';
import 'package:LaCoro/presentation/register/pin_page.dart';
import 'package:LaCoro/presentation/register/register_page.dart';
import 'package:LaCoro/presentation/splash/splash.dart';
import 'package:LaCoro/presentation/store_details/store_details_page.dart';
import 'package:LaCoro/presentation/test/styles_test_page.dart';
import 'package:LaCoro/presentation/test/test_page.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_simple_dependency_injection/injector.dart';
import 'package:responsive_framework/responsive_framework.dart';
import 'core/appearance/app_theme.dart';
import 'core/env/envirionment_configuration.dart';
import 'presentation/adresses/select_address_map_page.dart';
import 'presentation/store_list/store_list_page.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized(); //all widgets are rendered here
await EnvironmentConfiguration.run(); // Init env configuration
await AppModule.initialise(Injector.getInjector()); // Inject modules
await Firebase.initializeApp(); // Init Firebase
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
currentFocus.focusedChild.unfocus();
}
},
child: MaterialApp(
builder: (context, widget) => ResponsiveWrapper.builder(
BouncingScrollWrapper.builder(context, widget),
maxWidth: 1200,
minWidth: 450,
defaultScale: true,
breakpoints: [
ResponsiveBreakpoint.resize(480, name: MOBILE),
ResponsiveBreakpoint.resize(800, name: TABLET),
// ResponsiveBreakpoint.resize(1000, name: DESKTOP),
// ResponsiveBreakpoint.autoScale(2460, name: '4K'),
],
),
localizationsDelegates: [
const AppLocalizationsDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [
const Locale('en', ''),
const Locale('es', ''),
],
debugShowCheckedModeBanner: false,
title: 'LaCoro',
theme: AppTheme.build(),
onGenerateRoute: (settings) {
Widget destinationRoute = SplashPage();
switch (settings.name) {
case StoreDetailsPage.STORE_DETAILS_ROUTE:
destinationRoute = StoreDetailsPage();
break;
case OrderDetailPage.ORDER_DETAIL_ROUTE:
destinationRoute = OrderDetailPage();
break;
case CheckoutPage.CHECKOUT_ORDER_ROUTE:
destinationRoute = CheckoutPage();
break;
case OrderStatusPage.ORDER_STATUS_ROUTE:
destinationRoute = OrderStatusPage();
break;
case MyAddressPage.MY_ADDRESS_ROUTE:
destinationRoute = MyAddressPage();
break;
case PastOrderDetailPage.PAST_ORDER_DETAIL_ROUTE:
destinationRoute = PastOrderDetailPage();
break;
}
return MaterialPageRoute(builder: (context) => destinationRoute, settings: settings);
},
initialRoute: '/',
routes: {
'/': (BuildContext context) => SplashPage(),
StoreListPage.STORE_LIST_ROUTE: (BuildContext context) => StoreListPage(),
SelectAddressMapPage.SELECT_ADDRESS_MAP_ROUTE: (BuildContext context) => SelectAddressMapPage(),
StylesTestPage.STYLE_TEST_PAGE_ROUTE: (BuildContext context) => StylesTestPage(),
AddressesPage.ADDRESSES_LIST_ROUTE: (BuildContext context) => AddressesPage(),
SplashPage.SPLASH_PAGE_ROUTE: (BuildContext context) => SplashPage(),
RegisterPage.REGISTER_ROUTE: (BuildContext context) => RegisterPage(),
PinPage.PIN_REGISTER_ROUTE: (BuildContext context) => PinPage(),
OrderHistoryPage.ORDER_HISTORY_ROUTE: (BuildContext context) => OrderHistoryPage(),
TestPage.TEST_PAGE_ROUTE: (BuildContext context) => TestPage()
},
),
);
}
}
| 45.117117
| 106
| 0.696086
|
25394005db9864d1cd045b54ef931dd97413019e
| 886
|
rb
|
Ruby
|
lib/spellr/file_list.rb
|
robotdana/spellr
|
775db18ce30fc343c691e1bcf8ce7a5b8c6e5d47
|
[
"MIT"
] | 34
|
2019-03-23T06:50:24.000Z
|
2022-03-23T06:33:33.000Z
|
lib/spellr/file_list.rb
|
robotdana/spellr
|
775db18ce30fc343c691e1bcf8ce7a5b8c6e5d47
|
[
"MIT"
] | 49
|
2019-09-20T07:34:10.000Z
|
2021-06-15T11:32:44.000Z
|
lib/spellr/file_list.rb
|
robotdana/spellr
|
775db18ce30fc343c691e1bcf8ce7a5b8c6e5d47
|
[
"MIT"
] | null | null | null |
# frozen_string_literal: true
require 'fast_ignore'
require_relative '../spellr'
require_relative 'file'
module Spellr
class FileList
include Enumerable
def initialize(patterns = nil)
@patterns = patterns
end
def each
return enum_for(:each) unless block_given?
fast_ignore.each do |file|
yield(Spellr::File.new(file))
end
end
def to_a
enum_for(:each).to_a
end
private
def configured_rules
return { gitignore: false } if Spellr.config.suppress_file_rules
{
ignore_rules: Spellr.config.excludes,
include_rules: Spellr.config.includes
}
end
def fast_ignore # rubocop:disable Metrics/MethodLength
FastIgnore.new(
**configured_rules,
argv_rules: @patterns,
follow_symlinks: true,
root: Spellr.pwd_s
)
end
end
end
| 18.458333
| 70
| 0.64447
|
21689f210b0f0fb8475f4555cf7a57140eb270ca
| 4,499
|
js
|
JavaScript
|
server/crawler/trailersCrawler.js
|
xinpengfei520/WeChatOfficialAccountServer
|
826868014c4413ce4c7d50b17d8c22023be8d9b8
|
[
"Apache-2.0"
] | null | null | null |
server/crawler/trailersCrawler.js
|
xinpengfei520/WeChatOfficialAccountServer
|
826868014c4413ce4c7d50b17d8c22023be8d9b8
|
[
"Apache-2.0"
] | 2
|
2020-07-16T21:06:54.000Z
|
2021-05-08T10:31:58.000Z
|
server/crawler/trailersCrawler.js
|
xinpengfei520/WeChatOfficialAccountServer
|
826868014c4413ce4c7d50b17d8c22023be8d9b8
|
[
"Apache-2.0"
] | null | null | null |
const puppeteer = require('puppeteer');
// 爬取热门电影信息
const url = 'https://movie.douban.com/coming';
module.exports = async () => {
// 1. 打开浏览器
const browser = await puppeteer.launch({
args: ['--no-sandbox'],
headless: true // 以无头浏览器的形式打开浏览器,没有界面显示,在后台运行,默认为 true
});
// 2. 创建 tab 标签页
const page = await browser.newPage();
// 3. 跳转到指定网址
await page.goto(url, {
waitUntil: 'networkidle2' // 等待网络空闲时,再跳转加载页面
});
// 4. 等待网址加载完成,开始爬取数据
// 开启延时器,延时 2 秒钟在开始爬取数据
await timeout();
// 一、爬取所有预告片详情页面网址
let result = await page.evaluate(() => {
// 对加载好的页面进行 dom 操作
// 所有爬取的数据数组
let result = [];
// 获取所有即将上映电影
const $trs = $('.coming_list tbody tr');
// $($('.coming_list tbody tr')[0]).find('td').last().html()
for (let i = 0; i < $trs.length; i++) {
const trDom = $trs[i];
// 获取想看的人数(解析出字符串中的数字)
let wantedNum = parseInt($(trDom).find('td').last().html());
// 判断 wantedNum 的大小,想看人数大于 100,电影才较好
if (wantedNum > 100) {
// 电影详情页面
let href = $(trDom).find('a').attr('href');
result.push(href);
}
}
// 将爬取的数据返回出去
return result;
});
console.log(result);
// 所有电影数据的数组
let moviesData = [];
// 二、爬取主要的电影数据
// 遍历爬取到的数据
for (let i = 0; i < result.length; i++) {
// 获取电影详情页面的网址
let url = result[i];
// 跳转到电影详情页
await page.goto(url, {
waitUntil: 'networkidle2' // 等待网络空闲时,在跳转加载页面
});
// 爬取其他数据
let itemResult = await page.evaluate(() => {
// 预告片电影的网址
const href = $('.related-pic-video').attr('href');
if (!href) {
return false;
}
// 标题
let title = $('[property="v:itemreviewed"]').html();
// 导演
let directors = $('[rel="v:directedBy"]').html();
// 海报图
let image = $('[rel="v:image"]').attr('src');
// 豆瓣 id
let doubanId = $('.a_show_login.lnk-sharing').attr('share-id');
// 演员
let casts = [];
let $star = $('[rel="v:starring"]');
let length = $star.length > 3 ? 3 : $star.length;
for (var j = 0; j < length; j++) {
casts.push($star[j].innerText);
}
// 类型
let genre = [];
const $genre = $('[property="v:genre"]');
for (let j = 0; j < $genre.length; j++) {
genre.push($genre[j].innerText);
}
// 简介
const summary = $('[property="v:summary"]').html().replace(/\s+/g, '');
// 上映日期
const releaseDate = $('[property="v:initialReleaseDate"]')[0].innerText;
// 片长
const runtime = $('[property="v:runtime"]').html();
// 评分
const rating = $('[property="v:average"]').html();
// 电影封面图片
const cover = $('.related-pic-video').css('background-image').split('"')[1].split('?')[0];
// 给单个对象添加两个属性
return {
title,
directors,
casts,
genre,
image,
summary,
releaseDate,
doubanId,
runtime,
rating,
href,
cover
}
});
console.log(itemResult);
// 只有数据是对象时,才添加到数组中
if (itemResult) {
moviesData.push(itemResult);
}
}
console.log(moviesData);
// 三、预告片电影链接
for (let i = 0; i < moviesData.length; i++) {
let item = moviesData[i];
let url = item.href;
// 跳转到电影详情页
await page.goto(url, {
waitUntil: 'networkidle2' // 等待网络空闲时,在跳转加载页面
});
// 爬取其他数据
item.link = await page.evaluate(() => {
// 电影链接
return $('video>source').attr('src');
})
}
console.log(moviesData);
// 5. 关闭浏览器
await browser.close();
// 最终会将数据全部返回出去
return moviesData;
};
// 延时 2 秒钟
function timeout() {
return new Promise(resolve => setTimeout(resolve, 2000))
}
| 27.944099
| 103
| 0.437653
|
6c814acefed965202372785096812a36e7ac821b
| 1,600
|
lua
|
Lua
|
svgmath/fonts/glyphlist.lua
|
akavel/svgmath
|
b587d0aa0dfb5942e6fcea87a4f3ce0f2e858d3f
|
[
"MIT"
] | 5
|
2018-03-14T05:58:17.000Z
|
2020-11-27T12:45:09.000Z
|
svgmath/fonts/glyphlist.lua
|
akavel/svgmath
|
b587d0aa0dfb5942e6fcea87a4f3ce0f2e858d3f
|
[
"MIT"
] | 1
|
2018-03-14T06:19:13.000Z
|
2018-03-14T13:13:25.000Z
|
svgmath/fonts/glyphlist.lua
|
akavel/svgmath
|
b587d0aa0dfb5942e6fcea87a4f3ce0f2e858d3f
|
[
"MIT"
] | 5
|
2018-03-14T07:02:47.000Z
|
2020-12-06T13:15:26.000Z
|
local math, string, table, arg = math, string, table, arg
local pairs, ipairs, require, tonumber, error = pairs, ipairs, require, tonumber, error
local _ENV = {package=package}
local PYLUA = require('PYLUA')
local os = require('os')
GlyphList = PYLUA.class(dict) {
__init__ = function(self, f)
while true do
local line = f:readline()
if #line==0 then
break
end
line = PYLUA.strip(line)
if #line==0 or PYLUA.startswith(line, '#') then
goto continue
end
local pair = PYLUA.split(line, ';')
if #pair~=2 then
goto continue
end
local glyph = PYLUA.strip(pair[1])
local codelist = PYLUA.split(pair[2])
if #codelist~=1 then
goto continue -- no support for compounds
end
local codepoint = tonumber(codelist[1], 16) or error('cannot convert '..codelist[1]..' to codepoint')
if self[glyph] then
table.insert(self[glyph], codepoint)
else
self[glyph] = {codepoint}
end
::continue::
end
end
;
lookup = function(self, glyphname)
return self[glyphname] or defaultGlyphList[glyphname]
end
;
}
local glyphListName = PYLUA.dirname(arg[0]) .. 'svgmath/fonts/default.glyphs'
defaultGlyphList = GlyphList(PYLUA.open(glyphListName, 'r'))
main = function()
if #arg>0 then
local glyphList = parseGlyphList(PYLUA.open(arg[1], 'r'))
else
glyphList = defaultGlyphList
end
for entry, value in pairs(glyphList) do
PYLUA.print(entry, ' => ', value, '\n')
end
end
if arg and arg[1]==... then
main()
end
return _ENV
| 23.529412
| 107
| 0.628125
|
33048193a88a1e1e35d3fb58f520797876b6b879
| 49
|
lua
|
Lua
|
isaac/constants.lua
|
Gabriel-Baril/lua-projects
|
ed4b2e2e05dca5392c0a6ea1817468f7d5de9f36
|
[
"Apache-2.0"
] | null | null | null |
isaac/constants.lua
|
Gabriel-Baril/lua-projects
|
ed4b2e2e05dca5392c0a6ea1817468f7d5de9f36
|
[
"Apache-2.0"
] | null | null | null |
isaac/constants.lua
|
Gabriel-Baril/lua-projects
|
ed4b2e2e05dca5392c0a6ea1817468f7d5de9f36
|
[
"Apache-2.0"
] | null | null | null |
WIN_WIDTH = 800
WIN_HEIGHT = 800
TITLE = "Isaac"
| 12.25
| 16
| 0.714286
|
6f5dbd0f1e4966860c8eccf622244fce2e0ae1e6
| 2,421
|
php
|
PHP
|
resources/views/questions/create.blade.php
|
Farzoqe/LamenessSurvey
|
95ff726d8290a2bb28272cee7aa70ddbb3e5ea19
|
[
"MIT"
] | null | null | null |
resources/views/questions/create.blade.php
|
Farzoqe/LamenessSurvey
|
95ff726d8290a2bb28272cee7aa70ddbb3e5ea19
|
[
"MIT"
] | 2
|
2021-05-11T03:05:46.000Z
|
2022-02-27T00:35:24.000Z
|
resources/views/questions/create.blade.php
|
Farzoqe/LamenessSurvey
|
95ff726d8290a2bb28272cee7aa70ddbb3e5ea19
|
[
"MIT"
] | null | null | null |
@extends('layout')
@section("content")
<div class="container-fluid">
<div class="card mb-3">
<form method="post" action="/questions">
@csrf
<input type="hidden" name="id" value="{{$item->id ?? ''}}">
<div class="card-header">
<h6 class="m-0 font-weight-bold text-primary">Add Question</h6>
</div>
<div class="card-body">
<div class="form-group">
<input type="hidden" name="survey_id" value="{{request('sid',$item->survey_id ?? null)}}"/>
<input type="text" value="{{$item->title ?? ''}}" name="title" class="form-control" placeholder="Title"/>
</div>
<div class="form-group">
<input type="text" value="{{$item->title_ur ?? ''}}" name="title_ur" class="form-control" placeholder="Title Urdu"/>
</div>
<div class="form-group">
<select class="form-control" name="type">
<option {{($item->type??null) == 'Short Answer'?'selected':''}}>Short Answer</option>
<option {{($item->type??null) == 'Multiple Choice'?'selected':''}}>Multiple Choice</option>
<option {{($item->type??null) == 'Long Answer'?'selected':''}}>Long Answer</option>
<option {{($item->type??null) == 'Ranking'?'selected':''}}>Ranking</option>
<option {{($item->type??null) == 'Picture'?'selected':''}}>Picture</option>
{{-- <option>Location</option>--}}
</select>
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Options" name="options">{{$item->options ?? ''}}</textarea>
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Options Urdu" name="options_ur">{{$item->options_ur ?? ''}}</textarea>
</div>
</div>
<div class="card-footer text-right">
<button class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
@stop
| 55.022727
| 140
| 0.44114
|
ffca2c104e543fbab98741d6f72041b26ae72a8d
| 337
|
swift
|
Swift
|
Packages/EurofurenceComponents/Sources/XCTComponentBase/Share/CapturingShareService.swift
|
Fenrikur/ef_app_ios
|
f4c52fe49cfd07046c7c55015640572b069e959c
|
[
"MIT"
] | 9
|
2016-02-02T08:27:24.000Z
|
2021-12-10T08:02:13.000Z
|
Packages/EurofurenceComponents/Sources/XCTComponentBase/Share/CapturingShareService.swift
|
Fenrikur/ef_app_ios
|
f4c52fe49cfd07046c7c55015640572b069e959c
|
[
"MIT"
] | 351
|
2016-07-04T15:58:52.000Z
|
2022-03-28T11:39:40.000Z
|
Packages/EurofurenceComponents/Sources/XCTComponentBase/Share/CapturingShareService.swift
|
Fenrikur/ef_app_ios
|
f4c52fe49cfd07046c7c55015640572b069e959c
|
[
"MIT"
] | 3
|
2016-08-02T10:12:45.000Z
|
2017-07-05T05:30:39.000Z
|
import ComponentBase
public class CapturingShareService: ShareService {
public init() {
}
public private(set) var sharedItem: Any?
public private(set) var sharedItemSender: Any?
public func share(_ item: Any, sender: Any) {
sharedItem = item
sharedItemSender = sender
}
}
| 19.823529
| 50
| 0.626113
|
0dbcb6be04f2e5d44167ec83bea21b7aeaff607b
| 6,422
|
cs
|
C#
|
BenefitsAllocationUpload/Services/BlobStorageService.cs
|
ucdavis/BenefitsAllocationUpload
|
fe122be2606e5318a5da6f7c0070355cf563a5c3
|
[
"MIT"
] | null | null | null |
BenefitsAllocationUpload/Services/BlobStorageService.cs
|
ucdavis/BenefitsAllocationUpload
|
fe122be2606e5318a5da6f7c0070355cf563a5c3
|
[
"MIT"
] | 3
|
2017-02-02T23:19:57.000Z
|
2020-06-16T18:18:28.000Z
|
BenefitsAllocationUpload/Services/BlobStorageService.cs
|
ucdavis/BenefitsAllocationUpload
|
fe122be2606e5318a5da6f7c0070355cf563a5c3
|
[
"MIT"
] | null | null | null |
using BenefitsAllocationUpload.Models;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.IO;
namespace BenefitsAllocationUpload.Services
{
public interface IBlobStorageService
{
void RenameBlob(string oldName, string newName);
byte[] GetBlob(string filename);
void PutBlob(string filepath);
Uri PutBlob(Stream stream, string filepath);
bool DeleteBlob(string filename);
bool Exists(string filename);
List<FileNames> ListBlobs();
long GetBlobLength(string filename);
}
public class BlobStoargeService : IBlobStorageService
{
//private readonly IBlobStoargeService _storageService;
private readonly CloudBlobContainer _container;
public BlobStoargeService()
{
var storageConnectionString =
string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}",
CloudConfigurationManager.GetSetting("AzureStorageAccountName"),
CloudConfigurationManager.GetSetting("AzureStorageKey"));
var storageAccount = CloudStorageAccount.Parse(storageConnectionString);
var blobClient = storageAccount.CreateCloudBlobClient();
_container = blobClient.GetContainerReference(CloudConfigurationManager.GetSetting("AzureContainerName"));
_container.CreateIfNotExists();
_container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Off });
}
public void RenameBlob(string oldName, string newName)
{
_container.Rename(oldName, newName);
}
public List<FileNames> ListBlobs()
{
var retval = new List<FileNames>();
var blobs = _container.ListBlobs(null, false);
var fileId = 0;
foreach (var item in blobs)
{
if (item != null && item is CloudBlockBlob)
{
var blob = (CloudBlockBlob)item;
retval.Add(new FileNames()
{
Length = blob.Properties.Length,
TimeStamp = blob.Properties.LastModified,
FileName = blob.Name,
FileId = fileId,
FilePath = blob.Uri.AbsoluteUri
});
//Console.WriteLine("Block blob of length {0}: {1}", blob.Properties.Length, blob.Uri);
}
else if (item != null && item is CloudPageBlob)
{
var pageBlob = (CloudPageBlob)item;
retval.Add(new FileNames()
{
Length = pageBlob.Properties.Length,
TimeStamp = pageBlob.Properties.LastModified,
FileName = pageBlob.Name,
FileId = fileId,
FilePath = pageBlob.Uri.AbsoluteUri
});
//Console.WriteLine("Page blob of length {0}: {1}", pageBlob.Properties.Length, pageBlob.Uri);
}
else if (item != null && item is CloudBlobDirectory)
{
var directory = (CloudBlobDirectory)item;
retval.Add(new FileNames()
{
FileId = fileId,
FilePath = directory.Uri.AbsoluteUri
});
//Console.WriteLine("Directory: {0}", directory.Uri);
}
fileId++;
}
return retval;
}
public byte[] GetBlob(string filename)
{
byte[] contents = null;
try
{
//Get file from blob storage and populate the contents
var blob = _container.GetBlockBlobReference(string.Format("{0}", filename));
using (var stream = new MemoryStream())
{
blob.DownloadToStream(stream);
//stream.Seek(0, SeekOrigin.Begin);
contents = stream.ToArray();
//using (var reader = new BinaryReader(stream))
//{
// stream.Position = 0;
// contents = reader.ReadBytes((int)stream.Length);
//}
}
}
catch (Exception)
{
return contents;
}
return contents;
}
public void PutBlob(string filepath)
{
var filename = Path.GetFileName(filepath);
var blob = _container.GetBlockBlobReference(string.Format("{0}", filename));
using (var fileStream = System.IO.File.OpenRead(filepath))
{
blob.UploadFromStream(fileStream);
}
}
public Uri PutBlob(Stream stream, string filepath)
{
var filename = Path.GetFileName(filepath);
var blob = _container.GetBlockBlobReference(string.Format("{0}", filename));
stream.Seek(0, SeekOrigin.Begin);
blob.UploadFromStream(stream);
return blob.Uri;
}
public bool Exists(string filename)
{
return _container.GetBlockBlobReference(string.Format("{0}", filename)).Exists();
}
public bool DeleteBlob(string filename)
{
var blob = _container.GetBlockBlobReference(string.Format("{0}", filename));
return blob.DeleteIfExists(DeleteSnapshotsOption.IncludeSnapshots);
}
public long GetBlobLength(string filename)
{
var blob = _container.GetBlobReferenceFromServer(filename);
return blob.Properties.Length;
}
}
public static class BlobContainerExtensions
{
public static void Rename(this CloudBlobContainer container, string oldName, string newName)
{
var source = container.GetBlobReferenceFromServer(oldName);
var target = container.GetBlockBlobReference(newName);
target.StartCopyFromBlob(source.Uri);
source.Delete();
}
}
}
| 34.526882
| 121
| 0.546559
|
51853edb7de63a7f9bbe47e1d3d0cf80a367d24e
| 1,913
|
dart
|
Dart
|
example/lib/editor/note_title.dart
|
MattWei/flutter-note
|
e2f732713c53cc16f071b847d5d10902bb1c0ad6
|
[
"Apache-2.0"
] | null | null | null |
example/lib/editor/note_title.dart
|
MattWei/flutter-note
|
e2f732713c53cc16f071b847d5d10902bb1c0ad6
|
[
"Apache-2.0"
] | null | null | null |
example/lib/editor/note_title.dart
|
MattWei/flutter-note
|
e2f732713c53cc16f071b847d5d10902bb1c0ad6
|
[
"Apache-2.0"
] | null | null | null |
import 'package:flutter/material.dart';
import 'editor_mode.dart';
class NoteTitleRoute extends StatefulWidget {
NoteTitleRoute(
{@required this.noteChangedNotifier,
@required this.editorSwitchedNotifier,
@required this.titleController,
Key key})
: super(key: key);
final NoteChangedNotifier noteChangedNotifier;
final EditorSwitchedNotifier editorSwitchedNotifier;
final TextEditingController titleController;
@override
_NoteTitleRouteState createState() => _NoteTitleRouteState();
}
class _NoteTitleRouteState extends State<NoteTitleRoute> {
@override
initState() {
super.initState();
widget.noteChangedNotifier.addListener(_handleNoteChanged);
widget.editorSwitchedNotifier.addListener(_handleEditModeChanged);
}
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 20),
child: Column(
children: <Widget>[
_showTitle(context),
],
),
);
}
bool _isReadOnly() {
return widget.noteChangedNotifier.value == null ||
widget.editorSwitchedNotifier.value == EditorMode.view;
}
Widget _showTitle(BuildContext context) {
return new TextField(
controller: widget.titleController,
style: TextStyle(fontFamily: 'NotoSerif'),
readOnly: _isReadOnly(),
);
}
void _setTitleText() {
final titleController = widget.titleController;
final title = widget.noteChangedNotifier.value.name;
print('note title:$title');
titleController.value = titleController.value.copyWith(
text: title,
selection:
TextSelection(baseOffset: title.length, extentOffset: title.length),
composing: TextRange.empty,
);
}
void _handleNoteChanged() {
_setTitleText();
setState(() {});
}
void _handleEditModeChanged() {
setState(() {
});
}
}
| 23.9125
| 78
| 0.690016
|
52618d3545c413999fe3ba2901275874c36cdc55
| 165
|
rb
|
Ruby
|
src/ex1268.rb
|
wkoszek/book-programming-ruby
|
6a087e0c455e602a4811d22afdb2a77a6d8a2e83
|
[
"BSD-2-Clause"
] | 7
|
2015-09-02T13:15:46.000Z
|
2019-08-25T04:44:55.000Z
|
src/ex1268.rb
|
wkoszek/book-programming-ruby
|
6a087e0c455e602a4811d22afdb2a77a6d8a2e83
|
[
"BSD-2-Clause"
] | 8
|
2020-07-17T02:34:54.000Z
|
2022-02-26T11:00:59.000Z
|
Notes/Ruby/sample_code/ex1268.rb
|
thib123/TPJ
|
e790fbefb04d53b4c31c4159692108d4dac4acb0
|
[
"MIT"
] | 4
|
2015-09-02T07:14:18.000Z
|
2020-05-27T00:52:38.000Z
|
# Sample code from Programing Ruby, page 589
"string\r\n".chop
"string\n\r".chop
"string\n".chop
"string".chop
"x".chop.chop
| 23.571429
| 44
| 0.539394
|
f1c28491ad0c98295beec50ee8ddb0d7688c82d6
| 297
|
rb
|
Ruby
|
spec/xrbp/websocket/command_spec.rb
|
sweetdream0729/XRBP
|
3d87662750fcc51ddc16b789474deb513a7a546c
|
[
"MIT"
] | 13
|
2019-03-27T21:14:47.000Z
|
2022-03-15T05:33:07.000Z
|
spec/xrbp/websocket/command_spec.rb
|
sweetdream0729/XRBP
|
3d87662750fcc51ddc16b789474deb513a7a546c
|
[
"MIT"
] | 1
|
2019-04-06T23:21:37.000Z
|
2019-04-06T23:21:37.000Z
|
spec/xrbp/websocket/command_spec.rb
|
sweetdream0729/XRBP
|
3d87662750fcc51ddc16b789474deb513a7a546c
|
[
"MIT"
] | 1
|
2019-04-04T19:01:51.000Z
|
2019-04-04T19:01:51.000Z
|
describe XRBP::WebSocket::Command do
subject { described_class.new(command: 'test') }
it 'returns command being requested' do
expect(subject.requesting).to eq 'test'
end
it 'returns bool indicating if we are request command' do
expect(subject).to be_requesting('test')
end
end
| 24.75
| 59
| 0.727273
|
ddb7264eaebb2beb0e0f29b15629259fbe5319c5
| 29,678
|
lua
|
Lua
|
dist/@Resources/game/init.lua
|
BanCrash/Lauhdutin
|
0bcc0b199d8908fd375510c42a60895fe877df2a
|
[
"MIT"
] | 86
|
2015-04-29T16:40:03.000Z
|
2022-02-06T07:24:22.000Z
|
dist/@Resources/game/init.lua
|
Kapiainen/Lauhdutin
|
71d7c8bbc94001396df262d4f73d6a138106beeb
|
[
"MIT"
] | 123
|
2015-06-22T02:58:11.000Z
|
2022-03-17T20:29:18.000Z
|
dist/@Resources/game/init.lua
|
Kapiainen/Lauhdutin
|
71d7c8bbc94001396df262d4f73d6a138106beeb
|
[
"MIT"
] | 17
|
2015-09-13T18:47:55.000Z
|
2022-03-16T07:18:09.000Z
|
RUN_TESTS = false
if RUN_TESTS then
print('Running tests')
end
local utility = nil
LOCALIZATION = nil
STATE = {
PATHS = {
GAMES = 'games.json',
BANGS = 'cache\\bangs.txt',
NOTES = 'cache\\notes.txt'
},
SCROLLBAR = {
START = nil,
MAX_HEIGHT = nil,
HEIGHT = nil,
STEP = nil
},
GAME = nil,
ALL_GAMES = nil,
GAMES_VERSION = nil,
ALL_TAGS = nil,
ALL_PLATFORMS = nil,
HIGHLIGHTED_SLOT_INDEX = 0,
CENTERED = false
}
local COMPONENTS = {
STATUS = nil,
SETTINGS = nil,
SLOTS = nil
}
local Property
do
local _class_0
local _base_0 = { }
_base_0.__index = _base_0
_class_0 = setmetatable({
__init = function(self, args)
self.title = args.title
self.value = args.value
self.action = args.action
self.update = args.update
end,
__base = _base_0,
__name = "Property"
}, {
__index = _base_0,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
Property = _class_0
end
local Slot
do
local _class_0
local _base_0 = {
populate = function(self, property)
self.property = property
return self:update()
end,
update = function(self)
if self.property ~= nil then
if self.property.update ~= nil then
self.property.value = self.property:update()
end
SKIN:Bang(('[!SetOption "Slot%dTitle" "Text" "%s"]'):format(self.index, utility.replaceUnsupportedChars(self.property.title)))
local value = utility.replaceUnsupportedChars(self.property.value)
SKIN:Bang(('[!SetOption "Slot%dValue" "Text" "%s"]'):format(self.index, value))
if value:len() > self.maxValueStringLength then
SKIN:Bang(('[!SetOption "Slot%dValue" "ToolTipText" "%s"]'):format(self.index, value))
SKIN:Bang(('[!SetOption "Slot%dValue" "ToolTipHidden" "0"]'):format(self.index))
else
SKIN:Bang(('[!SetOption "Slot%dValue" "ToolTipHidden" "1"]'):format(self.index))
end
return
end
SKIN:Bang(('[!SetOption "Slot%dTitle" "Text" " "]'):format(self.index))
SKIN:Bang(('[!SetOption "Slot%dValue" "Text" " "]'):format(self.index))
return SKIN:Bang(('[!SetOption "Slot%dValue" "ToolTipHidden" "1"]'):format(self.index))
end,
hasAction = function(self)
return self.property ~= nil and self.property.action ~= nil
end,
action = function(self)
if self.property == nil or self.property.action == nil then
return
end
return self.property:action(self.index)
end
}
_base_0.__index = _base_0
_class_0 = setmetatable({
__init = function(self, index, maxValueStringLength)
self.index = index
self.maxValueStringLength = maxValueStringLength
end,
__base = _base_0,
__name = "Slot"
}, {
__index = _base_0,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
Slot = _class_0
end
local Game = nil
log = function(...)
if STATE.LOGGING == true then
return print(...)
end
end
local additionalEnums
additionalEnums = function()
ENUMS.TAG_STATES = {
DISABLED = 1,
ENABLED = 2,
ENABLED_PLATFORM = 3,
MAX = 4
}
end
local getGamesAndTags
getGamesAndTags = function()
local games = io.readJSON(STATE.PATHS.GAMES)
STATE.GAMES_VERSION = games.version
do
local _accum_0 = { }
local _len_0 = 1
local _list_0 = games.games
for _index_0 = 1, #_list_0 do
local args = _list_0[_index_0]
_accum_0[_len_0] = Game(args)
_len_0 = _len_0 + 1
end
STATE.ALL_GAMES = _accum_0
end
if STATE.ALL_TAGS == nil then
STATE.ALL_TAGS = { }
local _list_0 = STATE.ALL_GAMES
for _index_0 = 1, #_list_0 do
local game = _list_0[_index_0]
local _list_1 = game:getTags()
for _index_1 = 1, #_list_1 do
local tag = _list_1[_index_1]
STATE.ALL_TAGS[tag] = ENUMS.TAG_STATES.DISABLED
end
local _list_2 = game:getPlatformTags()
for _index_1 = 1, #_list_2 do
local tag = _list_2[_index_1]
STATE.ALL_TAGS[tag] = ENUMS.TAG_STATES.DISABLED
end
end
end
end
Initialize = function()
SKIN:Bang('[!Hide]')
STATE.PATHS.RESOURCES = SKIN:GetVariable('@')
dofile(('%s%s'):format(STATE.PATHS.RESOURCES, 'lib\\rainmeter_helpers.lua'))
COMPONENTS.STATUS = require('shared.status')()
local success, err = pcall(function()
log('Initializing Game config')
require('shared.enums')
additionalEnums()
utility = require('shared.utility')
utility.createJSONHelpers()
COMPONENTS.SETTINGS = require('shared.settings')()
STATE.LOGGING = COMPONENTS.SETTINGS:getLogging()
LOCALIZATION = require('shared.localization')(COMPONENTS.SETTINGS)
Game = require('main.game')
do
local _accum_0 = { }
local _len_0 = 1
local _list_0 = require('main.platforms')
for _index_0 = 1, #_list_0 do
local Platform = _list_0[_index_0]
_accum_0[_len_0] = Platform(COMPONENTS.SETTINGS)
_len_0 = _len_0 + 1
end
STATE.ALL_PLATFORMS = _accum_0
end
getGamesAndTags()
STATE.NUM_SLOTS = 4
STATE.SCROLL_INDEX = 1
local valueMeter = SKIN:GetMeter('Slot1Value')
local maxValueStringLength = math.round(valueMeter:GetW() / valueMeter:GetOption('FontSize'))
do
local _accum_0 = { }
local _len_0 = 1
for i = 1, STATE.NUM_SLOTS do
_accum_0[_len_0] = Slot(i, maxValueStringLength)
_len_0 = _len_0 + 1
end
COMPONENTS.SLOTS = _accum_0
end
local scrollbar = SKIN:GetMeter('Scrollbar')
STATE.SCROLLBAR.START = scrollbar:GetY()
STATE.SCROLLBAR.MAX_HEIGHT = scrollbar:GetH()
STATE.SUPPORTED_BANNER_EXTENSIONS = table.concat(require('main.platforms.platform')(COMPONENTS.SETTINGS):getBannerExtensions(), '|'):gsub('%.', '')
SKIN:Bang(('[!SetOption "SaveButton" "Text" "%s"]'):format(LOCALIZATION:get('button_label_save', 'Save')))
SKIN:Bang(('[!SetOption "CancelButton" "Text" "%s"]'):format(LOCALIZATION:get('button_label_cancel', 'Cancel')))
SKIN:Bang('[!CommandMeasure "Script" "HandshakeGame()" "#ROOTCONFIG#"]')
return COMPONENTS.STATUS:hide()
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
Update = function() end
local updateTitle
updateTitle = function(game, maxStringLength)
local title = utility.replaceUnsupportedChars(game:getTitle())
SKIN:Bang(('[!SetOption "PageTitle" "Text" "%s"]'):format(title))
if title:len() > maxStringLength then
SKIN:Bang(('[!SetOption "PageTitle" "ToolTipText" "%s"]'):format(title))
return SKIN:Bang('[!SetOption "PageTitle" "ToolTipHidden" "0"]')
else
return SKIN:Bang('[!SetOption "PageTitle" "ToolTipHidden" "1"]')
end
end
local updateBanner
updateBanner = function(game)
local path = game:getBanner()
if not (path) then
SKIN:Bang('[!SetOption "Banner" "ImageName" "#@#game\\gfx\\blank.png"]')
SKIN:Bang(('[!SetOption "BannerMissing" "Text" "%s"]'):format(LOCALIZATION:get('game_no_banner', 'No banner')))
local expectedBanner = game:getExpectedBanner()
if expectedBanner then
local tooltip
local _exp_0 = game:getPlatformID()
if ENUMS.PLATFORM_IDS.SHORTCUTS == _exp_0 then
local platformOverride = game:getPlatformOverride()
if platformOverride ~= nil then
tooltip = ('\\@Resources\\Shortcuts\\%s\\%s.%s'):format(platformOverride, expectedBanner, STATE.SUPPORTED_BANNER_EXTENSIONS)
else
tooltip = ('\\@Resources\\Shortcuts\\%s.%s'):format(expectedBanner, STATE.SUPPORTED_BANNER_EXTENSIONS)
end
elseif ENUMS.PLATFORM_IDS.STEAM == _exp_0 then
if game:getPlatformOverride() then
tooltip = ('\\@Resources\\cache\\steam_shortcuts\\%s.%s'):format(expectedBanner, STATE.SUPPORTED_BANNER_EXTENSIONS)
else
tooltip = ('\\@Resources\\cache\\steam\\%s.%s'):format(expectedBanner, STATE.SUPPORTED_BANNER_EXTENSIONS)
end
elseif ENUMS.PLATFORM_IDS.BATTLENET == _exp_0 then
tooltip = ('\\@Resources\\cache\\battlenet\\%s.%s'):format(expectedBanner, STATE.SUPPORTED_BANNER_EXTENSIONS)
elseif ENUMS.PLATFORM_IDS.GOG_GALAXY == _exp_0 then
tooltip = ('\\@Resources\\cache\\gog_galaxy\\%s.%s'):format(expectedBanner, STATE.SUPPORTED_BANNER_EXTENSIONS)
end
SKIN:Bang(('[!SetOption "BannerMissing" "ToolTipText" "%s"]'):format(tooltip))
SKIN:Bang('[!SetOption "BannerMissing" "ToolTipHidden" "0"]')
return
end
end
SKIN:Bang(('[!SetOption "Banner" "ImageName" "#@#%s"]'):format(path))
SKIN:Bang('[!SetOption "BannerMissing" "Text" ""]')
return SKIN:Bang('[!SetOption "BannerMissing" "ToolTipHidden" "1"]')
end
local updateScrollbar
updateScrollbar = function()
STATE.MAX_SCROLL_INDEX = #STATE.PROPERTIES - STATE.NUM_SLOTS + 1
STATE.SCROLLBAR.HEIGHT = math.round(STATE.SCROLLBAR.MAX_HEIGHT / (#STATE.PROPERTIES - STATE.NUM_SLOTS + 1))
STATE.SCROLLBAR.STEP = (STATE.SCROLLBAR.MAX_HEIGHT - STATE.SCROLLBAR.HEIGHT) / (#STATE.PROPERTIES - STATE.NUM_SLOTS)
SKIN:Bang(('[!SetOption "Scrollbar" "H" "%d"]'):format(STATE.SCROLLBAR.HEIGHT))
local y = STATE.SCROLLBAR.START + (STATE.SCROLL_INDEX - 1) * STATE.SCROLLBAR.STEP
return SKIN:Bang(('[!SetOption "Scrollbar" "Y" "%d"]'):format(math.round(y)))
end
local updateSlots
updateSlots = function()
for i, slot in ipairs(COMPONENTS.SLOTS) do
slot:populate(STATE.PROPERTIES[i + STATE.SCROLL_INDEX - 1])
if i == STATE.HIGHLIGHTED_SLOT_INDEX then
if slot:hasAction() then
MouseOver(i)
else
MouseLeave(i)
end
end
end
end
local sortPropertiesByTitle
sortPropertiesByTitle = function(a, b)
if a.title:lower() < b.title:lower() then
return true
end
return false
end
local createTagProperty
createTagProperty = function(tag, state)
local f
f = function()
local _exp_0 = STATE.GAME_TAGS[tag]
if ENUMS.TAG_STATES.DISABLED == _exp_0 then
return LOCALIZATION:get('button_label_disabled', 'Disabled')
elseif ENUMS.TAG_STATES.ENABLED == _exp_0 then
return LOCALIZATION:get('button_label_enabled', 'Enabled')
elseif ENUMS.TAG_STATES.ENABLED_PLATFORM == _exp_0 then
return LOCALIZATION:get('button_label_enabled', 'Enabled') .. '*'
end
end
if state == ENUMS.TAG_STATES.ENABLED_PLATFORM then
return Property({
title = tag,
value = f(),
update = f
})
else
return Property({
title = tag,
value = f(),
action = function(self, index)
local _exp_0 = STATE.GAME_TAGS[tag]
if ENUMS.TAG_STATES.DISABLED == _exp_0 then
STATE.GAME_TAGS[tag] = ENUMS.TAG_STATES.ENABLED
elseif ENUMS.TAG_STATES.ENABLED == _exp_0 then
STATE.GAME_TAGS[tag] = ENUMS.TAG_STATES.DISABLED
else
STATE.GAME_TAGS[tag] = STATE.GAME_TAGS[tag]
end
end,
update = f
})
end
end
local createTagProperties
createTagProperties = function()
local properties = { }
for tag, state in pairs(STATE.GAME_TAGS) do
table.insert(properties, createTagProperty(tag, state))
end
table.sort(properties, sortPropertiesByTitle)
table.insert(properties, 1, Property({
title = LOCALIZATION:get('game_tag_create', 'Create a new tag'),
value = '',
action = function(self, index)
return StartCreatingTag(index)
end
}))
return properties
end
local createProperties
createProperties = function(game, platform)
local properties = { }
local platformOverride = game:getPlatformOverride()
local platformName
if platformOverride ~= nil then
platformName = platformOverride .. '*'
else
platformName = platform:getName()
end
table.insert(properties, Property({
title = LOCALIZATION:get('game_platform', 'Platform'),
value = platformName
}))
table.insert(properties, Property({
title = LOCALIZATION:get('button_label_hours_played', 'Hours played'),
value = ('%.0f'):format(game:getHoursPlayed())
}))
local f
f = function(self)
local lastPlayed = game:getLastPlayed()
if lastPlayed > 315532800 then
local date = os.date('*t', lastPlayed)
return ('%04.f-%02.f-%02.f %02.f:%02.f:%02.f'):format(date.year, date.month, date.day, date.hour, date.min, date.sec)
end
return LOCALIZATION:get('game_last_played_never', 'Never')
end
table.insert(properties, Property({
title = LOCALIZATION:get('game_last_played', 'Last played'),
value = f()
}))
f = function(self)
if game:isInstalled() then
return LOCALIZATION:get('button_label_yes', 'Yes')
end
return LOCALIZATION:get('button_label_no', 'No')
end
table.insert(properties, Property({
title = LOCALIZATION:get('game_installed', 'Installed'),
value = f()
}))
f = function(self)
if game:isVisible() then
return LOCALIZATION:get('button_label_yes', 'Yes')
end
return LOCALIZATION:get('button_label_no', 'No')
end
table.insert(properties, Property({
title = LOCALIZATION:get('game_visible', 'Visible'),
value = f(),
action = function(self, index)
return STATE.GAME:toggleVisibility()
end,
update = f
}))
local action = nil
local path = game:getPath():match('"(.-)"')
if path ~= nil and io.fileExists(path, false) then
local head, tail = io.splitPath(path)
if head ~= nil then
action = function(self, index)
return SKIN:Bang(('["%s"]'):format(head))
end
end
end
table.insert(properties, Property({
title = LOCALIZATION:get('game_path', 'Path'),
value = ('""%s""'):format(game:getPath()),
action = action
}))
action = nil
path = nil
f = function(self)
local processOverride = game:getProcessOverride()
if processOverride ~= nil and processOverride ~= '' then
return processOverride .. '*'
end
local process = game:getProcess(true)
if process ~= nil and process ~= '' then
return process
end
return LOCALIZATION:get('game_process_none', 'None')
end
table.insert(properties, Property({
title = LOCALIZATION:get('game_process', 'Process'),
value = f(),
action = function(self, index)
return StartEditingProcessOverride(index)
end,
update = f
}))
f = function(self)
local notes = game:getNotes()
if notes ~= nil and notes:len() > 0 then
local lines = notes:splitIntoLines()
local line = lines[1]
if #lines > 1 then
line = line .. '...'
end
return line
end
return LOCALIZATION:get('game_notes_none', 'None')
end
table.insert(properties, Property({
title = LOCALIZATION:get('game_notes', 'Notes'),
value = f(),
action = function(self, index)
return StartEditingNotes()
end,
update = f
}))
f = function(self)
local tags = { }
local _list_0 = game:getTags()
for _index_0 = 1, #_list_0 do
local tag = _list_0[_index_0]
tags[tag] = false
end
local _list_1 = game:getPlatformTags()
for _index_0 = 1, #_list_1 do
local tag = _list_1[_index_0]
tags[tag] = true
end
if tags then
do
local _accum_0 = { }
local _len_0 = 1
for tag, fromPlatform in pairs(tags) do
_accum_0[_len_0] = {
tag = tag,
fromPlatform = fromPlatform
}
_len_0 = _len_0 + 1
end
tags = _accum_0
end
table.sort(tags, function(a, b)
return a.tag < b.tag
end)
local str = ''
for _index_0 = 1, #tags do
local entry = tags[_index_0]
if entry.fromPlatform then
str = str .. (' | %s*'):format(entry.tag)
else
str = str .. (' | %s'):format(entry.tag)
end
end
str = str:sub(4)
if str ~= '' then
return str
end
end
return LOCALIZATION:get('game_tags_none', 'None')
end
table.insert(properties, Property({
title = LOCALIZATION:get('game_tags', 'Tags'),
value = f(),
action = function(self, index)
do
local _tbl_0 = { }
for tag, state in pairs(STATE.ALL_TAGS) do
_tbl_0[tag] = state
end
STATE.GAME_TAGS = _tbl_0
end
local _list_0 = game:getTags()
for _index_0 = 1, #_list_0 do
local tag = _list_0[_index_0]
STATE.GAME_TAGS[tag] = ENUMS.TAG_STATES.ENABLED
end
local _list_1 = game:getPlatformTags()
for _index_0 = 1, #_list_1 do
local tag = _list_1[_index_0]
STATE.GAME_TAGS[tag] = ENUMS.TAG_STATES.ENABLED_PLATFORM
end
SKIN:Bang(('[!SetOption "SaveButton" "Text" "%s"]'):format(LOCALIZATION:get('button_label_accept', 'Accept')))
STATE.TAG_PROPERTIES = createTagProperties()
STATE.PROPERTIES = STATE.TAG_PROPERTIES
STATE.PREVIOUS_SCROLL_INDEX = STATE.SCROLL_INDEX
STATE.SCROLL_INDEX = 1
updateScrollbar()
return updateSlots()
end,
update = f
}))
f = function(self)
if game:getIgnoresOtherBangs() then
return LOCALIZATION:get('button_label_yes', 'Yes')
end
return LOCALIZATION:get('button_label_no', 'No')
end
table.insert(properties, Property({
title = LOCALIZATION:get('game_ignores_other_bangs', 'Ignores other bangs'),
value = f(),
action = function(self, index)
return STATE.GAME:toggleIgnoresOtherBangs()
end,
update = f
}))
f = function(self)
local bangs = game:getStartingBangs()
if bangs and #bangs > 0 then
bangs = table.concat(bangs, ' | ')
if bangs ~= '' then
return (bangs:gsub('\"', '\'\''))
end
end
return LOCALIZATION:get('button_label_bangs_none', 'None')
end
table.insert(properties, Property({
title = LOCALIZATION:get('button_label_starting_bangs', 'Starting bangs'),
value = f(),
action = function(self, index)
return StartEditingStartingBangs()
end,
update = f
}))
f = function(self)
local bangs = game:getStoppingBangs()
if bangs and #bangs > 0 then
bangs = table.concat(bangs, ' | ')
if bangs ~= '' then
return (bangs:gsub('\"', '\'\''))
end
end
return LOCALIZATION:get('button_label_bangs_none', 'None')
end
table.insert(properties, Property({
title = LOCALIZATION:get('button_label_stopping_bangs', 'Stopping bangs'),
value = f(),
action = function(self, index)
return StartEditingStoppingBangs()
end,
update = f
}))
return properties
end
Handshake = function(gameID)
local success, err = pcall(function()
log('Accepting Game handshake', gameID)
getGamesAndTags()
local game = STATE.ALL_GAMES[gameID]
if game == nil or game.gameID ~= gameID then
game = nil
local _list_0 = STATE.ALL_GAMES
for _index_0 = 1, #_list_0 do
local candidate = _list_0[_index_0]
if candidate:getGameID() == gameID then
game = candidate
break
end
end
end
assert(game ~= nil, ('Could not find a game with the gameID: %d'):format(gameID))
STATE.GAME = game
local valueMeter = SKIN:GetMeter('PageTitle')
local maxStringLength = math.round(valueMeter:GetW() / valueMeter:GetOption('FontSize'))
updateTitle(game, maxStringLength)
updateBanner(game)
local platform = nil
local _list_0 = STATE.ALL_PLATFORMS
for _index_0 = 1, #_list_0 do
local p = _list_0[_index_0]
if p:getPlatformID() == game:getPlatformID() then
platform = p
break
end
end
assert(platform ~= nil, 'Could not find the game\'s platform.')
STATE.DEFAULT_PROPERTIES = createProperties(game, platform)
STATE.PROPERTIES = STATE.DEFAULT_PROPERTIES
updateScrollbar()
updateSlots()
if STATE.CENTERED == false then
STATE.CENTERED = true
if COMPONENTS.SETTINGS:getCenterOnMonitor() then
local meter = SKIN:GetMeter('WindowShadow')
local skinWidth = meter:GetW()
local skinHeight = meter:GetH()
local mainConfig = utility.getConfig(SKIN:GetVariable('ROOTCONFIG'))
local monitorIndex = nil
if mainConfig ~= nil then
monitorIndex = utility.getConfigMonitor(mainConfig) or 1
else
monitorIndex = 1
end
local x, y = utility.centerOnMonitor(skinWidth, skinHeight, monitorIndex)
SKIN:Bang(('[!Move "%d" "%d"]'):format(x, y))
end
end
return SKIN:Bang('[!Show]')
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
Scroll = function(direction)
if not (COMPONENTS.SLOTS ~= nil) then
return
end
local index = STATE.SCROLL_INDEX + direction
if index < 1 then
return
elseif index > STATE.MAX_SCROLL_INDEX then
return
end
STATE.SCROLL_INDEX = index
updateScrollbar()
return updateSlots()
end
MouseOver = function(index)
if not (COMPONENTS.SLOTS ~= nil) then
return
end
STATE.HIGHLIGHTED_SLOT_INDEX = index
if not (COMPONENTS.SLOTS[index] ~= nil and COMPONENTS.SLOTS[index]:hasAction()) then
return
end
return SKIN:Bang(('[!SetOption "Slot%dButton" "SolidColor" "#ButtonHighlightedColor#"]'):format(index))
end
MouseLeave = function(index)
if not (COMPONENTS.SLOTS ~= nil) then
return
end
if index == 0 then
STATE.HIGHLIGHTED_SLOT_INDEX = 0
for i = index, STATE.NUM_SLOTS do
SKIN:Bang(('[!SetOption "Slot%dButton" "SolidColor" "#ButtonBaseColor#"]'):format(i))
end
else
return SKIN:Bang(('[!SetOption "Slot%dButton" "SolidColor" "#ButtonBaseColor#"]'):format(index))
end
end
MouseLeftPress = function(index)
if not (COMPONENTS.SLOTS ~= nil and COMPONENTS.SLOTS[index] ~= nil and COMPONENTS.SLOTS[index]:hasAction()) then
return
end
return SKIN:Bang(('[!SetOption "Slot%dButton" "SolidColor" "#ButtonPressedColor#"]'):format(index))
end
ButtonAction = function(index)
if not (COMPONENTS.SLOTS ~= nil and COMPONENTS.SLOTS[index] ~= nil and COMPONENTS.SLOTS[index]:hasAction()) then
return
end
SKIN:Bang(('[!SetOption "Slot%dButton" "SolidColor" "#ButtonHighlightedColor#"]'):format(index))
COMPONENTS.SLOTS[index]:action()
return updateSlots()
end
local showDefaultProperties
showDefaultProperties = function()
SKIN:Bang(('[!SetOption "SaveButton" "Text" "%s"]'):format(LOCALIZATION:get('button_label_save', 'Save')))
SKIN:Bang(('[!SetOption "CancelButton" "Text" "%s"]'):format(LOCALIZATION:get('button_label_cancel', 'Cancel')))
STATE.PROPERTIES = STATE.DEFAULT_PROPERTIES
STATE.SCROLL_INDEX = STATE.PREVIOUS_SCROLL_INDEX
STATE.PREVIOUS_SCROLL_INDEX = 1
updateScrollbar()
return updateSlots()
end
Save = function()
local success, err = pcall(function()
local _exp_0 = STATE.PROPERTIES
if STATE.DEFAULT_PROPERTIES == _exp_0 then
io.writeJSON(STATE.PATHS.GAMES, {
version = STATE.GAMES_VERSION,
games = STATE.ALL_GAMES
})
local gameID = STATE.GAME:getGameID()
return SKIN:Bang(('[!CommandMeasure "Script" "UpdateGame(%d)" "#ROOTCONFIG#"][!DeactivateConfig]'):format(gameID))
elseif STATE.TAG_PROPERTIES == _exp_0 then
STATE.GAME:setTags((function()
local _accum_0 = { }
local _len_0 = 1
for tag, state in pairs(STATE.GAME_TAGS) do
if state == ENUMS.TAG_STATES.ENABLED then
_accum_0[_len_0] = tag
_len_0 = _len_0 + 1
end
end
return _accum_0
end)())
return showDefaultProperties()
end
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
Cancel = function()
local success, err = pcall(function()
local _exp_0 = STATE.PROPERTIES
if STATE.DEFAULT_PROPERTIES == _exp_0 then
return SKIN:Bang('[!CommandMeasure "Script" "UpdateGame()" "#ROOTCONFIG#"][!DeactivateConfig]')
elseif STATE.TAG_PROPERTIES == _exp_0 then
return showDefaultProperties()
end
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
OpenBanner = function()
local success, err = pcall(function()
local path = SKIN:GetMeter('Banner'):GetOption('ImageName')
if path ~= nil and path ~= '' and path:match('@Resources\\game\\gfx\\') == nil then
return SKIN:Bang(('"%s"'):format(path))
else
local game = STATE.GAME
local _exp_0 = game:getPlatformID()
if ENUMS.PLATFORM_IDS.SHORTCUTS == _exp_0 then
local platformOverride = game:getPlatformOverride()
if platformOverride ~= nil then
path = ('Shortcuts\\%s\\'):format(platformOverride)
else
path = 'Shortcuts\\'
end
elseif ENUMS.PLATFORM_IDS.STEAM == _exp_0 then
if game:getPlatformOverride() then
path = 'cache\\steam_shortcuts\\'
else
path = 'cache\\steam\\'
end
elseif ENUMS.PLATFORM_IDS.BATTLENET == _exp_0 then
path = 'cache\\battlenet\\'
elseif ENUMS.PLATFORM_IDS.GOG_GALAXY == _exp_0 then
path = 'cache\\gog_galaxy\\'
end
return SKIN:Bang(('"#@#%s"'):format(path))
end
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
StartEditingProcessOverride = function(index)
local success, err = pcall(function()
local meter = SKIN:GetMeter(('Slot%dValue'):format(index))
SKIN:Bang(('[!SetOption "Input" "X" "%d"]'):format(meter:GetX() - 1))
SKIN:Bang(('[!SetOption "Input" "Y" "%d"]'):format(meter:GetY() - 1))
SKIN:Bang(('[!SetOption "Input" "W" "%d"]'):format(meter:GetW()))
SKIN:Bang(('[!SetOption "Input" "H" "%d"]'):format(20))
return SKIN:Bang('[!CommandMeasure "Input" "ExecuteBatch 1"]')
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
OnEditedProcessOverride = function(process)
local success, err = pcall(function()
STATE.GAME:setProcessOverride(process:sub(1, -2))
return updateSlots()
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
StartCreatingTag = function(index)
local success, err = pcall(function()
local meter = SKIN:GetMeter(('Slot%dValue'):format(index))
SKIN:Bang(('[!SetOption "Input" "X" "%d"]'):format(meter:GetX() - 1))
SKIN:Bang(('[!SetOption "Input" "Y" "%d"]'):format(meter:GetY() - 1))
SKIN:Bang(('[!SetOption "Input" "W" "%d"]'):format(meter:GetW()))
SKIN:Bang(('[!SetOption "Input" "H" "%d"]'):format(20))
return SKIN:Bang('[!CommandMeasure "Input" "ExecuteBatch 2"]')
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
OnCreatedTag = function(tag)
local success, err = pcall(function()
tag = tag:sub(1, -2)
if STATE.ALL_TAGS[tag] ~= nil then
return
end
STATE.ALL_TAGS[tag] = ENUMS.TAG_STATES.DISABLED
STATE.GAME_TAGS[tag] = ENUMS.TAG_STATES.ENABLED
local createProperty = table.remove(STATE.TAG_PROPERTIES, 1)
table.insert(STATE.TAG_PROPERTIES, createTagProperty(tag, STATE.GAME_TAGS[tag]))
table.sort(STATE.TAG_PROPERTIES, sortPropertiesByTitle)
table.insert(STATE.TAG_PROPERTIES, 1, createProperty)
updateScrollbar()
return updateSlots()
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
StartEditingStartingBangs = function()
local success, err = pcall(function()
local bangs = STATE.GAME:getStartingBangs()
io.writeFile(STATE.PATHS.BANGS, table.concat(bangs, '\n'))
return utility.runCommand(('""%s""'):format(io.joinPaths(STATE.PATHS.RESOURCES, STATE.PATHS.BANGS)), '', 'OnEditedStartingBangs')
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
OnEditedStartingBangs = function()
local success, err = pcall(function()
local bangs = io.readFile(STATE.PATHS.BANGS)
STATE.GAME:setStartingBangs(bangs:splitIntoLines())
return updateSlots()
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
StartEditingStoppingBangs = function()
local success, err = pcall(function()
local bangs = STATE.GAME:getStoppingBangs()
io.writeFile(STATE.PATHS.BANGS, table.concat(bangs, '\n'))
return utility.runCommand(('""%s""'):format(io.joinPaths(STATE.PATHS.RESOURCES, STATE.PATHS.BANGS)), '', 'OnEditedStoppingBangs')
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
OnEditedStoppingBangs = function()
local success, err = pcall(function()
local bangs = io.readFile(STATE.PATHS.BANGS)
STATE.GAME:setStoppingBangs(bangs:splitIntoLines())
return updateSlots()
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
ToggleIgnoresOtherBangs = function()
local success, err = pcall(function()
STATE.GAME:toggleIgnoresOtherBangs()
return updateSlots()
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
StartEditingNotes = function()
local success, err = pcall(function()
local notes = STATE.GAME:getNotes()
if notes == nil then
notes = ''
end
io.writeFile(STATE.PATHS.NOTES, notes)
return utility.runCommand(('""%s""'):format(io.joinPaths(STATE.PATHS.RESOURCES, STATE.PATHS.NOTES)), '', 'OnEditedNotes')
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
OnEditedNotes = function()
local success, err = pcall(function()
local notes = io.readFile(STATE.PATHS.NOTES)
STATE.GAME:setNotes(notes)
return updateSlots()
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
| 32.79337
| 151
| 0.654593
|
d56c8a75e240c040a5d34d865a0cb9c9e8a15182
| 719
|
lua
|
Lua
|
ZombieEscape/gamemode/sv_humans.lua
|
samuelmaddock/zombie-escape
|
c89196e1076b9e46cd2864060e733cf754244a93
|
[
"MIT"
] | 14
|
2015-08-13T07:16:38.000Z
|
2022-01-10T17:49:39.000Z
|
ZombieEscape/gamemode/sv_humans.lua
|
samuelmaddock/zombie-escape
|
c89196e1076b9e46cd2864060e733cf754244a93
|
[
"MIT"
] | 3
|
2016-08-12T21:21:36.000Z
|
2018-08-27T00:04:12.000Z
|
ZombieEscape/gamemode/sv_humans.lua
|
samuelmaddock/zombie-escape
|
c89196e1076b9e46cd2864060e733cf754244a93
|
[
"MIT"
] | 5
|
2017-03-25T04:33:38.000Z
|
2020-04-22T18:08:42.000Z
|
CVars.HumanSpeed = CreateConVar( "ze_human_speed", 250, {FCVAR_REPLICATED}, "Speed at which the humans move in units/sec." )
CVars.Ammo = CreateConVar( "ze_ammo", 800, {FCVAR_REPLICATED}, "Amount of ammo to give humans." )
CVars.Buyzone = CreateConVar( "ze_buyzone", 1, {FCVAR_REPLICATED}, "Whether or not players may purchase weapons only in a buyzone." )
-- GM.AmmoTypes = {"smg1","pistol","357","ar2","buckshot","sniperround"}
GM.AmmoTypes = {"ammo_50AE","ammo_762mm","ammo_556mm","ammo_556mm_box","ammo_338mag","ammo_9mm","ammo_buckshot","ammo_45acp","ammo_357sig","ammo_57mm"}
GM.ValidHumans = {"male14","male18","male12","male17","male13","male10","male16","male15","male11",
"female10","female11","female12"}
| 89.875
| 151
| 0.724618
|
fa0d99ae5c5f24a96a0bd0f127c0cedd118144ff
| 1,214
|
cpp
|
C++
|
Problem201-250/p222_2.cpp
|
dingqunfei/LeetCode
|
c74a21ea56ee7b35308d2f387ef24ab29b031e24
|
[
"Apache-2.0"
] | null | null | null |
Problem201-250/p222_2.cpp
|
dingqunfei/LeetCode
|
c74a21ea56ee7b35308d2f387ef24ab29b031e24
|
[
"Apache-2.0"
] | null | null | null |
Problem201-250/p222_2.cpp
|
dingqunfei/LeetCode
|
c74a21ea56ee7b35308d2f387ef24ab29b031e24
|
[
"Apache-2.0"
] | null | null | null |
/**
* @file p222_2.cpp
* @brief
* @author dingqunfei (dqflying@gmail.com)
* @version 1.0
* @date 2021-04-11
*
* @copyright Copyright (c) 2021 DQFLYING
*
* @par :
*
*
* Date : 2021-04-11
* Version : 1.0
* Author : dqflying
* Lisence :
* Description :
*
*
*
*
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root)
{
return 0;
}
int lh = 0, rh = 0;
TreeNode *left = root;
TreeNode *right = root;
while(left)
{
++lh;
left = left->left;
}
while(right)
{
++rh;
right = right->right;
}
if(rh == lh)
{
return pow(2, rh)-1;
}
return 1+countNodes(root->left)+countNodes(root->right);
}
};
| 19.580645
| 93
| 0.474465
|
454f6ee28e05b65b3f86f868ef4389ac7b6c801b
| 10,645
|
py
|
Python
|
ppapi/native_client/tools/browser_tester/browsertester/server.py
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668
|
2015-01-01T01:57:10.000Z
|
2022-03-31T23:33:32.000Z
|
ppapi/native_client/tools/browser_tester/browsertester/server.py
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113
|
2015-05-04T09:58:14.000Z
|
2022-01-31T19:35:03.000Z
|
ppapi/native_client/tools/browser_tester/browsertester/server.py
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941
|
2015-01-02T11:32:21.000Z
|
2022-03-31T16:35:46.000Z
|
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import BaseHTTPServer
import cgi
import mimetypes
import os
import os.path
import posixpath
import SimpleHTTPServer
import SocketServer
import threading
import time
import urllib
import urlparse
class RequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def NormalizePath(self, path):
path = path.split('?', 1)[0]
path = path.split('#', 1)[0]
path = posixpath.normpath(urllib.unquote(path))
words = path.split('/')
bad = set((os.curdir, os.pardir, ''))
words = [word for word in words if word not in bad]
# The path of the request should always use POSIX-style path separators, so
# that the filename input of --map_file can be a POSIX-style path and still
# match correctly in translate_path().
return '/'.join(words)
def translate_path(self, path):
path = self.NormalizePath(path)
if path in self.server.file_mapping:
return self.server.file_mapping[path]
for extra_dir in self.server.serving_dirs:
# TODO(halyavin): set allowed paths in another parameter?
full_path = os.path.join(extra_dir, os.path.basename(path))
if os.path.isfile(full_path):
return full_path
# Try the complete relative path, not just a basename. This allows the
# user to serve everything recursively under extra_dir, not just one
# level deep.
#
# One use case for this is the Native Client SDK examples. The examples
# expect to be able to access files as relative paths from the root of
# the example directory.
# Sometimes two subdirectories contain files with the same name, so
# including all subdirectories in self.server.serving_dirs will not do
# the correct thing; (i.e. the wrong file will be chosen, even though the
# correct path was given).
full_path = os.path.join(extra_dir, path)
if os.path.isfile(full_path):
return full_path
if not path.endswith('favicon.ico') and not self.server.allow_404:
self.server.listener.ServerError('Cannot find file \'%s\'' % path)
return path
def guess_type(self, path):
# We store the extension -> MIME type mapping in the server instead of the
# request handler so we that can add additional mapping entries via the
# command line.
_, ext = posixpath.splitext(path)
if ext in self.server.extensions_mapping:
return self.server.extensions_mapping[ext]
ext = ext.lower()
if ext in self.server.extensions_mapping:
return self.server.extensions_mapping[ext]
else:
return self.server.extensions_mapping['']
def SendRPCResponse(self, response):
self.send_response(200)
self.send_header("Content-type", "text/plain")
self.send_header("Content-length", str(len(response)))
self.end_headers()
self.wfile.write(response)
# shut down the connection
self.wfile.flush()
self.connection.shutdown(1)
def HandleRPC(self, name, query):
kargs = {}
for k, v in query.items():
assert len(v) == 1, k
kargs[k] = v[0]
l = self.server.listener
try:
response = getattr(l, name)(**kargs)
except Exception as e:
self.SendRPCResponse('%r' % (e,))
raise
else:
self.SendRPCResponse(response)
# For Last-Modified-based caching, the timestamp needs to be old enough
# for the browser cache to be used (at least 60 seconds).
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
# Often we clobber and regenerate files for testing, so this is needed
# to actually use the browser cache.
def send_header(self, keyword, value):
if keyword == 'Last-Modified':
last_mod_format = '%a, %d %b %Y %H:%M:%S GMT'
old_value_as_t = time.strptime(value, last_mod_format)
old_value_in_secs = time.mktime(old_value_as_t)
new_value_in_secs = old_value_in_secs - 360
value = time.strftime(last_mod_format,
time.localtime(new_value_in_secs))
SimpleHTTPServer.SimpleHTTPRequestHandler.send_header(self,
keyword,
value)
def do_POST(self):
# Backwards compatible - treat result as tuple without named fields.
_, _, path, _, query, _ = urlparse.urlparse(self.path)
self.server.listener.Log('POST %s (%s)' % (self.path, path))
if path == '/echo':
self.send_response(200)
self.end_headers()
data = self.rfile.read(int(self.headers.getheader('content-length')))
self.wfile.write(data)
elif self.server.output_dir is not None:
# Try to write the file to disk.
path = self.NormalizePath(path)
output_path = os.path.join(self.server.output_dir, path)
try:
outfile = open(output_path, 'w')
except IOError:
error_message = 'File not found: %r' % output_path
self.server.listener.ServerError(error_message)
self.send_error(404, error_message)
return
try:
data = self.rfile.read(int(self.headers.getheader('content-length')))
outfile.write(data)
except IOError as e:
outfile.close()
try:
os.remove(output_path)
except OSError:
# Oh, well.
pass
error_message = 'Can\'t write file: %r\n' % output_path
error_message += 'Exception:\n%s' % str(e)
self.server.listener.ServerError(error_message)
self.send_error(500, error_message)
return
outfile.close()
# Send a success response.
self.send_response(200)
self.end_headers()
else:
error_message = 'File not found: %r' % path
self.server.listener.ServerError(error_message)
self.send_error(404, error_message)
self.server.ResetTimeout()
def do_GET(self):
# Backwards compatible - treat result as tuple without named fields.
_, _, path, _, query, _ = urlparse.urlparse(self.path)
tester = '/TESTER/'
if path.startswith(tester):
# If the path starts with '/TESTER/', the GET is an RPC call.
name = path[len(tester):]
# Supporting Python 2.5 prevents us from using urlparse.parse_qs
query = cgi.parse_qs(query, True)
self.server.rpc_lock.acquire()
try:
self.HandleRPC(name, query)
finally:
self.server.rpc_lock.release()
# Don't reset the timeout. This is not "part of the test", rather it's
# used to tell us if the renderer process is still alive.
if name == 'JavaScriptIsAlive':
self.server.JavaScriptIsAlive()
return
elif path in self.server.redirect_mapping:
dest = self.server.redirect_mapping[path]
self.send_response(301, 'Moved')
self.send_header('Location', dest)
self.end_headers()
self.wfile.write(self.error_message_format %
{'code': 301,
'message': 'Moved',
'explain': 'Object moved permanently'})
self.server.listener.Log('REDIRECT %s (%s -> %s)' %
(self.path, path, dest))
else:
self.server.listener.Log('GET %s (%s)' % (self.path, path))
# A normal GET request for transferring files, etc.
f = self.send_head()
if f:
self.copyfile(f, self.wfile)
f.close()
self.server.ResetTimeout()
def copyfile(self, source, outputfile):
# Bandwidth values <= 0.0 are considered infinite
if self.server.bandwidth <= 0.0:
return SimpleHTTPServer.SimpleHTTPRequestHandler.copyfile(
self, source, outputfile)
self.server.listener.Log('Simulating %f mbps server BW' %
self.server.bandwidth)
chunk_size = 1500 # What size to use?
bits_per_sec = self.server.bandwidth * 1000000
start_time = time.time()
data_sent = 0
while True:
chunk = source.read(chunk_size)
if len(chunk) == 0:
break
cur_elapsed = time.time() - start_time
target_elapsed = (data_sent + len(chunk)) * 8 / bits_per_sec
if (cur_elapsed < target_elapsed):
time.sleep(target_elapsed - cur_elapsed)
outputfile.write(chunk)
data_sent += len(chunk)
self.server.listener.Log('Streamed %d bytes in %f s' %
(data_sent, time.time() - start_time))
# Disable the built-in logging
def log_message(self, format, *args):
pass
# The ThreadingMixIn allows the server to handle multiple requests
# concurently (or at least as concurently as Python allows). This is desirable
# because server sockets only allow a limited "backlog" of pending connections
# and in the worst case the browser could make multiple connections and exceed
# this backlog - causing the server to drop requests. Using ThreadingMixIn
# helps reduce the chance this will happen.
# There were apparently some problems using this Mixin with Python 2.5, but we
# are no longer using anything older than 2.6.
class Server(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
def Configure(
self, file_mapping, redirect_mapping, extensions_mapping, allow_404,
bandwidth, listener, serving_dirs=[], output_dir=None):
self.file_mapping = file_mapping
self.redirect_mapping = redirect_mapping
self.extensions_mapping.update(extensions_mapping)
self.allow_404 = allow_404
self.bandwidth = bandwidth
self.listener = listener
self.rpc_lock = threading.Lock()
self.serving_dirs = serving_dirs
self.output_dir = output_dir
def TestingBegun(self, timeout):
self.test_in_progress = True
# self.timeout does not affect Python 2.5.
self.timeout = timeout
self.ResetTimeout()
self.JavaScriptIsAlive()
# Have we seen any requests from the browser?
self.received_request = False
def ResetTimeout(self):
self.last_activity = time.time()
self.received_request = True
def JavaScriptIsAlive(self):
self.last_js_activity = time.time()
def TimeSinceJSHeartbeat(self):
return time.time() - self.last_js_activity
def TestingEnded(self):
self.test_in_progress = False
def TimedOut(self, total_time):
return (total_time >= 0.0 and
(time.time() - self.last_activity) >= total_time)
def Create(host, port):
server = Server((host, port), RequestHandler)
server.extensions_mapping = mimetypes.types_map.copy()
server.extensions_mapping.update({
'': 'application/octet-stream' # Default
})
return server
| 35.721477
| 79
| 0.66341
|
37f5e26b04698fdd3ea5a21161ba5345a8e71bd1
| 4,842
|
swift
|
Swift
|
Cosmostation/Cell/SifMyPoolCell.swift
|
shieldwallets/cosmostation-ios
|
48d01c4bd15091709abf226c5fa2f4e07e98baaa
|
[
"MIT"
] | 97
|
2019-06-28T12:31:40.000Z
|
2022-03-29T05:38:32.000Z
|
Cosmostation/Cell/SifMyPoolCell.swift
|
TrendingTechnology/cosmostation-ios
|
1f5bbdf2ffa9b1738462d66bd924985d0b0b755c
|
[
"MIT"
] | 84
|
2019-09-17T10:01:29.000Z
|
2021-10-21T07:55:10.000Z
|
Cosmostation/Cell/SifMyPoolCell.swift
|
TrendingTechnology/cosmostation-ios
|
1f5bbdf2ffa9b1738462d66bd924985d0b0b755c
|
[
"MIT"
] | 44
|
2019-07-18T04:26:49.000Z
|
2022-03-14T06:40:36.000Z
|
//
// SifMyPoolCell.swift
// Cosmostation
//
// Created by 정용주 on 2021/10/19.
// Copyright © 2021 wannabit. All rights reserved.
//
import UIKit
class SifMyPoolCell: UITableViewCell {
@IBOutlet weak var poolCardView: CardView!
@IBOutlet weak var poolPairTokenImg: UIImageView!
@IBOutlet weak var poolPairLabel: UILabel!
@IBOutlet weak var totalLiquidityValueLabel: UILabel!
@IBOutlet weak var liquidity1AmountLabel: UILabel!
@IBOutlet weak var liquidity1DenomLabel: UILabel!
@IBOutlet weak var liquidity2AmountLabel: UILabel!
@IBOutlet weak var liquidity2DenomLabel: UILabel!
@IBOutlet weak var myShareValueLabel: UILabel!
@IBOutlet weak var myDepositCoin0AmountLabel: UILabel!
@IBOutlet weak var myDepositCoin0DenomLabel: UILabel!
@IBOutlet weak var myDepositCoin1AmountLabel: UILabel!
@IBOutlet weak var myDepositCoin1DenomLabel: UILabel!
@IBOutlet weak var availableCoin0AmountLabel: UILabel!
@IBOutlet weak var availableCoin0DenomLabel: UILabel!
@IBOutlet weak var availableCoin1AmountLabel: UILabel!
@IBOutlet weak var availableCoin1DenomLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.selectionStyle = .none
liquidity1AmountLabel.font = UIFontMetrics(forTextStyle: .footnote).scaledFont(for: Font_13_footnote)
liquidity2AmountLabel.font = UIFontMetrics(forTextStyle: .footnote).scaledFont(for: Font_13_footnote)
myDepositCoin0AmountLabel.font = UIFontMetrics(forTextStyle: .footnote).scaledFont(for: Font_13_footnote)
myDepositCoin1AmountLabel.font = UIFontMetrics(forTextStyle: .footnote).scaledFont(for: Font_13_footnote)
availableCoin0AmountLabel.font = UIFontMetrics(forTextStyle: .footnote).scaledFont(for: Font_13_footnote)
availableCoin1AmountLabel.font = UIFontMetrics(forTextStyle: .footnote).scaledFont(for: Font_13_footnote)
}
func onBindSifPoolView(_ pool: Sifnode_Clp_V1_Pool, _ myLp: Sifnode_Clp_V1_LiquidityProviderRes?) {
poolCardView.backgroundColor = TRANS_BG_COLOR_SIF
poolPairLabel.textColor = COLOR_SIF
let nf = WUtils.getNumberFormatter(2)
let rowanDecimal = WUtils.getSifCoinDecimal(SIF_MAIN_DENOM)
let rowanAmount = NSDecimalNumber.init(string: pool.nativeAssetBalance)
let externalDecimal = WUtils.getSifCoinDecimal(pool.externalAsset.symbol)
let externalAmount = NSDecimalNumber.init(string: pool.externalAssetBalance)
let exteranlDenom = pool.externalAsset.symbol
let poolValue = WUtils.getSifPoolValue(pool)
let poolValueFormatted = "$ " + nf.string(from: poolValue)!
WUtils.DpSifCoinImg(poolPairTokenImg, exteranlDenom)
poolPairLabel.text = "ROWAN : " + WUtils.getSifCoinName(exteranlDenom).uppercased()
totalLiquidityValueLabel.attributedText = WUtils.getDpAttributedString(poolValueFormatted, 2, totalLiquidityValueLabel.font)
WUtils.DpSifCoinName(liquidity1DenomLabel, SIF_MAIN_DENOM)
WUtils.DpSifCoinName(liquidity2DenomLabel, exteranlDenom)
liquidity1AmountLabel.attributedText = WUtils.displayAmount2(rowanAmount.stringValue, liquidity1AmountLabel.font, rowanDecimal, 6)
liquidity2AmountLabel.attributedText = WUtils.displayAmount2(externalAmount.stringValue, liquidity2AmountLabel.font, externalDecimal, 6)
//dp my lp info
if (myLp != nil) {
let myShareValue = WUtils.getSifMyShareValue(pool, myLp!)
let myShareValueFormatted = "$ " + nf.string(from: myShareValue)!
myShareValueLabel.attributedText = WUtils.getDpAttributedString(myShareValueFormatted, 2, myShareValueLabel.font)
WUtils.DpSifCoinName(myDepositCoin0DenomLabel, SIF_MAIN_DENOM)
WUtils.DpSifCoinName(myDepositCoin1DenomLabel, exteranlDenom)
myDepositCoin0AmountLabel.attributedText = WUtils.displayAmount2(myLp!.nativeAssetBalance, myDepositCoin0AmountLabel.font, rowanDecimal, 6)
myDepositCoin1AmountLabel.attributedText = WUtils.displayAmount2(myLp?.externalAssetBalance, myDepositCoin1AmountLabel.font, externalDecimal, 6)
}
//dp available
let availableRowan = BaseData.instance.getAvailable_gRPC(SIF_MAIN_DENOM)
let availableExternal = BaseData.instance.getAvailable_gRPC(exteranlDenom)
WUtils.DpSifCoinName(availableCoin0DenomLabel, SIF_MAIN_DENOM)
WUtils.DpSifCoinName(availableCoin1DenomLabel, exteranlDenom)
availableCoin0AmountLabel.attributedText = WUtils.displayAmount2(availableRowan, availableCoin0AmountLabel.font, rowanDecimal, 6)
availableCoin1AmountLabel.attributedText = WUtils.displayAmount2(availableExternal, availableCoin1AmountLabel.font, externalDecimal, 6)
}
}
| 55.655172
| 156
| 0.755886
|
2e9499661c71fbbda6b46403de365e323aba32b7
| 406
|
swift
|
Swift
|
Protein/Coding Support/Extensions/Foundation/Data.swift
|
06Games/Saily
|
8ea0840e17d9e415a5e15eebda6ebe84747a9ae4
|
[
"MIT"
] | 1
|
2021-03-08T03:53:19.000Z
|
2021-03-08T03:53:19.000Z
|
Protein/Coding Support/Extensions/Foundation/Data.swift
|
mrh5201314/Saily
|
dbed89900b886f436008a3a2502d9a738c2cc78a
|
[
"MIT"
] | null | null | null |
Protein/Coding Support/Extensions/Foundation/Data.swift
|
mrh5201314/Saily
|
dbed89900b886f436008a3a2502d9a738c2cc78a
|
[
"MIT"
] | 1
|
2021-03-08T03:53:32.000Z
|
2021-03-08T03:53:32.000Z
|
//
// Data.swift
// Protein
//
// Created by Lakr Aream on 2020/7/19.
// Copyright © 2020 Lakr Aream. All rights reserved.
//
import Foundation
extension Data {
init<T>(from value: T) {
var value = value
self.init(buffer: UnsafeBufferPointer(start: &value, count: 1))
}
func to<T>(type: T.Type) -> T {
return self.withUnsafeBytes { $0.load(as: T.self) }
}
}
| 18.454545
| 71
| 0.596059
|
beb1e400879223dd37f669100599ec1495d046a8
| 941
|
ts
|
TypeScript
|
src/globals.ts
|
designerbjk/nft-armory
|
4bd788630512680a3bcf8e487b8fce6eb89c1e18
|
[
"MIT"
] | 124
|
2021-11-07T23:05:31.000Z
|
2022-03-30T14:00:28.000Z
|
src/globals.ts
|
designerbjk/nft-armory
|
4bd788630512680a3bcf8e487b8fce6eb89c1e18
|
[
"MIT"
] | 17
|
2021-11-14T20:56:37.000Z
|
2022-03-28T17:48:28.000Z
|
src/globals.ts
|
designerbjk/nft-armory
|
4bd788630512680a3bcf8e487b8fce6eb89c1e18
|
[
"MIT"
] | 61
|
2021-11-15T19:28:50.000Z
|
2022-03-31T08:43:36.000Z
|
import events from 'events';
export const EE = new events.EventEmitter.EventEmitter();
// --------------------------------------- errors
export const ERR_NO_NFTS = new Error('No NFTs Found:( Are you on the right network?');
// --------------------------------------- defaults
export const DEFAULTS = {
CLUSTER: 'mainnet',
OWNER: 'AEahaRpDFzg74t7NtWoruabo2fPJQjKFM9kQJNjH7obK',
CREATOR: 'BDYYJ1VzPDXwJoARMZNnN4MX4cZNjVvc5DfFaKzgrruz',
AUTHORITY: 'Edy3xedybSQYAE6eboza5YEcoJan91nfSd3jUppHz7u1',
MINT: 'A3wpue1mWdnfiU7VVLQeMAuVR4LcVrEsTtxysX1hPKLZ',
URI: 'https://gateway.pinata.cloud/ipfs/Qmawjub6LNBQUZ9KnVLMobf3bUiKwjusKpb52p86k5SAZG',
MAX_SUPPLY: null,
MASTER_MINT: 'A3wpue1mWdnfiU7VVLQeMAuVR4LcVrEsTtxysX1hPKLZ',
UPDATE_AUTHORITY: null,
NFT_MINT: 'A3wpue1mWdnfiU7VVLQeMAuVR4LcVrEsTtxysX1hPKLZ',
METADATA: null,
PRIMARY_SALE: null,
METADATA_PROGRAM_ID: 'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s',
};
| 30.354839
| 90
| 0.730074
|
8dc7bff4e078f9584bf56adc42da11ed594af23d
| 869
|
js
|
JavaScript
|
src/db/seeders/locationSeeds.js
|
Japhethca/population-manager
|
24bb2a307146304e3fcb48e6e1fede438cb67ecf
|
[
"MIT"
] | null | null | null |
src/db/seeders/locationSeeds.js
|
Japhethca/population-manager
|
24bb2a307146304e3fcb48e6e1fede438cb67ecf
|
[
"MIT"
] | null | null | null |
src/db/seeders/locationSeeds.js
|
Japhethca/population-manager
|
24bb2a307146304e3fcb48e6e1fede438cb67ecf
|
[
"MIT"
] | null | null | null |
export default {
up: queryInterface => queryInterface.bulkInsert('Location', [
{
name: 'Abuja',
maleResidents: 500,
femaleResidents: 800,
totalResidents: 1300,
createdAt: new Date(),
updatedAt: new Date(),
},
{
name: 'Lagos',
maleResidents: 200,
femaleResidents: 400,
totalResidents: 600,
createdAt: new Date(),
updatedAt: new Date(),
},
{
name: 'Kaduna',
maleResidents: 700,
femaleResidents: 300,
totalResidents: 1000,
createdAt: new Date(),
updatedAt: new Date(),
},
{
name: 'California',
maleResidents: 1200,
femaleResidents: 3000,
totalResidents: 4200,
createdAt: new Date(),
updatedAt: new Date(),
},
]),
down: queryInterface => queryInterface.bulkDelete('Location', null, {}),
};
| 22.282051
| 74
| 0.56847
|
daeac8f2096e9f820bf5bdbbd8d4989012e0f0b7
| 1,448
|
rb
|
Ruby
|
app/controllers/users_controller.rb
|
toomanyjoes/everlywellproject_api
|
d3442b917e8d3d82ac793e9af936af313c2e8316
|
[
"MIT"
] | null | null | null |
app/controllers/users_controller.rb
|
toomanyjoes/everlywellproject_api
|
d3442b917e8d3d82ac793e9af936af313c2e8316
|
[
"MIT"
] | null | null | null |
app/controllers/users_controller.rb
|
toomanyjoes/everlywellproject_api
|
d3442b917e8d3d82ac793e9af936af313c2e8316
|
[
"MIT"
] | null | null | null |
class UsersController < ApplicationController
rescue_from ApiExceptions::BaseException,
:with => :render_error_response
HEADING = 'heading'
# GET /users
def index
users = User.order(:last_name)
render json: users
end
# GET /users/:id
def show
render json: User.find(params[:id])
end
# POST /users
def create
user = User.new(user_params)
if user.valid?
tinylink = Tinylink.shorten(params['data']['attributes'][:website])
user.website = tinylink
user.save
output = Scraper.scrape_url(user.website)
if output.any?
write_user_data(user.id, output)
end
render json: user, status: :created
else
render json: user, adapter: :json_api,
serializer: ActiveModel::Serializer::ErrorSerializer,
status: :unprocessable_entity
end
end
private
def user_params
params.require(:data).require(:attributes).
permit(:first_name, :last_name, :website) ||
ActionController::Parameters.new
end
def write_user_data(user_id, data)
data.each do |header|
datum = Userdatum.new({user_id: user_id, data_type: HEADING, data: header})
if datum.valid?
datum.save
else
raise ApiExceptions::ScraperError::HeadingError
end
end
end
def render_error_response(error)
render json: error, each_serializer: ApiExceptionSerializer, status: 400
end
end
| 24.542373
| 81
| 0.65884
|