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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dda5cd2ddadfc914da123de33de513bb645e2324 | 169 | php | PHP | application/helpers/allowed_helper.php | fyulistian/politeknik-learning | 6ba258b54680071bb613d5ee4cb4a3f8b60c8593 | [
"MIT"
] | null | null | null | application/helpers/allowed_helper.php | fyulistian/politeknik-learning | 6ba258b54680071bb613d5ee4cb4a3f8b60c8593 | [
"MIT"
] | null | null | null | application/helpers/allowed_helper.php | fyulistian/politeknik-learning | 6ba258b54680071bb613d5ee4cb4a3f8b60c8593 | [
"MIT"
] | null | null | null | <?php
function allowed($param)
{
$CI =& get_instance();
if ($CI->session->userdata('level') != $param) {
redirect(base_url(),'refresh');
}
} | 21.125 | 52 | 0.526627 |
26108252b3a89e05b0e1edf934c2f839d17a1121 | 506 | java | Java | src/main/java/com/api/demo/Controller/ApiController.java | aquajack22/CapstoneProject3 | c8edc0241b2fcde9e0bfbcb0334a0b14239b8048 | [
"MIT"
] | null | null | null | src/main/java/com/api/demo/Controller/ApiController.java | aquajack22/CapstoneProject3 | c8edc0241b2fcde9e0bfbcb0334a0b14239b8048 | [
"MIT"
] | null | null | null | src/main/java/com/api/demo/Controller/ApiController.java | aquajack22/CapstoneProject3 | c8edc0241b2fcde9e0bfbcb0334a0b14239b8048 | [
"MIT"
] | null | null | null | package com.api.demo.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/Assess")
@CrossOrigin
public class ApiController {
@GetMapping("/api/info")
public String getWarehouse(){
return "############# The API call is a success #############";
}
} | 33.733333 | 71 | 0.743083 |
26a11b12d32e89d070b1dd019defce4d7f819d7f | 8,375 | java | Java | app/src/main/java/com/appacitive/khelkund/activities/pick5/Pick5ListActivity.java | randhika/khelkund | c8d1b22e19c0c4cc950100d6efc299ca26844a03 | [
"Apache-2.0"
] | 2 | 2021-04-03T17:23:30.000Z | 2021-04-09T02:14:36.000Z | app/src/main/java/com/appacitive/khelkund/activities/pick5/Pick5ListActivity.java | randhika/khelkund | c8d1b22e19c0c4cc950100d6efc299ca26844a03 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/appacitive/khelkund/activities/pick5/Pick5ListActivity.java | randhika/khelkund | c8d1b22e19c0c4cc950100d6efc299ca26844a03 | [
"Apache-2.0"
] | 7 | 2018-11-06T05:44:42.000Z | 2020-11-14T21:13:36.000Z | package com.appacitive.khelkund.activities.pick5;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.appacitive.khelkund.R;
import com.appacitive.khelkund.activities.misc.LoginActivity;
import com.appacitive.khelkund.adapters.Pick5Adapter;
import com.appacitive.khelkund.infra.BusProvider;
import com.appacitive.khelkund.infra.SharedPreferencesManager;
import com.appacitive.khelkund.infra.SnackBarManager;
import com.appacitive.khelkund.infra.StorageManager;
import com.appacitive.khelkund.infra.services.FetchAllPick5MatchesIntentService;
import com.appacitive.khelkund.model.Match;
import com.appacitive.khelkund.model.events.MatchSelectedEvent;
import com.squareup.otto.Subscribe;
import butterknife.ButterKnife;
import butterknife.InjectView;
import jp.wasabeef.recyclerview.animators.adapters.ScaleInAnimationAdapter;
public class Pick5ListActivity extends ActionBarActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
private List<Match> openMatches;
private List<Match> completedMatches;
private List<Match> upcomingMatches;
private List<Match> mMatches;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pick5_list);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
String mUserId = SharedPreferencesManager.ReadUserId();
if (mUserId == null) {
Intent loginIntent = new Intent(this, LoginActivity.class);
startActivity(loginIntent);
finish();
return;
}
fetchMatches();
}
private void fetchMatches() {
mMatches = new ArrayList<Match>();
openMatches = new ArrayList<Match>();
completedMatches = new ArrayList<Match>();
upcomingMatches = new ArrayList<Match>();
StorageManager storageManager = new StorageManager();
mMatches = storageManager.GetAllMatches();
if (mMatches.size() == 0) {
SnackBarManager.showMessage("Match data could not be made available at the moment. Please try again later", this);
Intent mPick5ServiceIntent = new Intent(this, FetchAllPick5MatchesIntentService.class);
startService(mPick5ServiceIntent);
return;
}
for (Match match : mMatches) {
if (match.getMatchStatus() == 2) {
completedMatches.add(match);
continue;
}
// int diffInDays = (int) ((match.getStartDate().getTime() - (new Date()).getTime()) / (1000 * 60 * 60 * 24));
if(match.isOpen() == true || match.getMatchStatus() == 1)
openMatches.add(match);
else upcomingMatches.add(match);
// if (diffInDays > 2)
// {
// upcomingMatches.add(match);
// }
// else openMatches.add(match);
}
}
@Subscribe
public void onMatchSelected(MatchSelectedEvent event) {
Intent intent = new Intent(this, Pick5MatchActivity.class);
intent.putExtra("match_id", event.MatchId);
startActivity(intent);
}
@Override
protected void onResume() {
super.onResume();
BusProvider.getInstance().register(this);
}
@Override
protected void onPause() {
super.onPause();
BusProvider.getInstance().unregister(this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
overridePendingTransition(R.anim.slide_in_left_fast, R.anim.slide_out_right_fast);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.slide_in_left_fast, R.anim.slide_out_right_fast);
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
{
return Pick5ListFragment.newInstance(openMatches);
}
case 1:
{
return Pick5ListFragment.newInstance(upcomingMatches);
}
default :
{
return Pick5ListFragment.newInstance(completedMatches);
}
}
}
@Override
public int getCount() {
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "OPEN";
case 1:
return "UPCOMING";
case 2:
return "COMPLETED";
}
return null;
}
}
public static class Pick5ListFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
@InjectView(R.id.rv_pick5)
public RecyclerView mRecyclerView;
public RecyclerView.Adapter mAdapter;
public RecyclerView.LayoutManager mLayoutManager;
private List<Match> matches;
public static Pick5ListFragment newInstance(List<Match> matches) {
Pick5ListFragment fragment = new Pick5ListFragment();
fragment.matches = matches;
return fragment;
}
public Pick5ListFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pick5_list, container, false);
ButterKnife.inject(this, rootView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
Pick5Adapter scheduleAdapter = new Pick5Adapter(matches);
mAdapter = new ScaleInAnimationAdapter(scheduleAdapter);
mRecyclerView.setAdapter(mAdapter);
return rootView;
}
}
}
| 32.587549 | 126 | 0.642149 |
abd4b9d5117e2ceb486d5e362ccc241beab85dc4 | 263 | go | Go | persister/bolt_interface.go | marknguyen85/server-api | aaa7c2b0fc3148307367ac321c22157c2a464f85 | [
"MIT"
] | null | null | null | persister/bolt_interface.go | marknguyen85/server-api | aaa7c2b0fc3148307367ac321c22157c2a464f85 | [
"MIT"
] | null | null | null | persister/bolt_interface.go | marknguyen85/server-api | aaa7c2b0fc3148307367ac321c22157c2a464f85 | [
"MIT"
] | null | null | null | package persister
import "github.com/marknguyen85/server-api/tomochain"
type BoltInterface interface {
StoreGeneralInfo(map[string]*tomochain.TokenGeneralInfo) error
GetGeneralInfo(map[string]tomochain.Token) (map[string]*tomochain.TokenGeneralInfo, error)
}
| 29.222222 | 91 | 0.828897 |
4042a9007a46eba46168c6133b48626596ed1a99 | 1,033 | py | Python | conference/tools/voteengine-0.99/ve.py | zevaverbach/epcon | 8352c030ee0d4197f559cdb58a54ee45c7a4471a | [
"BSD-2-Clause"
] | 40 | 2015-03-03T22:14:58.000Z | 2022-02-15T22:27:48.000Z | conference/tools/voteengine-0.99/ve.py | zevaverbach/epcon | 8352c030ee0d4197f559cdb58a54ee45c7a4471a | [
"BSD-2-Clause"
] | 699 | 2015-01-21T10:13:29.000Z | 2022-02-08T09:26:36.000Z | conference/tools/voteengine-0.99/ve.py | zevaverbach/epcon | 8352c030ee0d4197f559cdb58a54ee45c7a4471a | [
"BSD-2-Clause"
] | 96 | 2015-01-22T11:03:13.000Z | 2022-01-31T05:35:34.000Z | #!/usr/bin/python
"""
Vote counter by Blake Cretney
This work is distributed AS IS. It is up to you to
determine if it is useful and safe. In particular,
NO WARRANTY is expressed or implied.
I permanently give everyone the rights to use, modify,
copy, distribute, re-distribute, and perform this work,
and all derived works, to the extent that I hold copyright
in them. My intent is to have this work treated as
public domain.
This module is used to run the program where a proper console
is not available. I wrote it for Windows, but maybe it works
on a Mac too. I have no way of knowing.
"""
import votemain
import sys
sys_stdin=sys.stdin
sys_stdout=sys.stdout
pause=1
try:
sys.stdin=open("input.txt")
sys.stdout=open("output.txt","w")
votemain.vote_main()
pause=0
except IOError as e:
sys_stdout.write(str(e) + "\n")
except RuntimeError as e:
sys_stdout.write(e.args[0] + "\n")
if pause:
try:
import msvcrt
sys_stdout.write("Press any key to continue\n")
c = msvcrt.getch()
pause=0
except: pass
| 23.477273 | 61 | 0.731849 |
580e2abeaa9bec5bdc64039b1e5a922e02395d1c | 1,523 | c | C | C02/ex09/ft_strcapitalize.c | dnl007/Piscina-42 | 6e8136163d33852393f0e1cb4368ace7efcac18a | [
"MIT"
] | null | null | null | C02/ex09/ft_strcapitalize.c | dnl007/Piscina-42 | 6e8136163d33852393f0e1cb4368ace7efcac18a | [
"MIT"
] | null | null | null | C02/ex09/ft_strcapitalize.c | dnl007/Piscina-42 | 6e8136163d33852393f0e1cb4368ace7efcac18a | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strcapitalize.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dnascime <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/11/28 17:00:35 by dnascime #+# #+# */
/* Updated: 2019/12/02 14:30:53 by dnascime ### ########.fr */
/* */
/* ************************************************************************** */
char ft_upcase(char c)
{
if (c >= 'a' && c <= 'z')
return (c - 32);
return (c);
}
char ft_lowcase(char c)
{
if (c >= 'A' && c <= 'Z')
return (c + 32);
return (c);
}
char ft_is_alphanumeric(char c)
{
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')))
if (c < '0' || c > '9')
return (0);
return (1);
}
char *ft_strcapitalize(char *str)
{
int i;
i = 0;
while (str[i] != '\0')
{
if (i == 0)
{
str[i] = ft_upcase(str[i]);
i++;
}
if (!ft_is_alphanumeric(str[i - 1]) && ft_is_alphanumeric(str[i]))
str[i] = ft_upcase(str[i]);
else
str[i] = ft_lowcase(str[i]);
i++;
}
return (str);
}
| 27.690909 | 80 | 0.26264 |
6b488a889c7b6fd41f6df363ae638e325be8ccb6 | 12,664 | c | C | src/rt/rt.c | Wei-PSU/BioRT-Flux-PIHM | 7a32acfa467e3211ab52322d88fb7919242b37c2 | [
"MIT"
] | 4 | 2019-04-22T05:22:25.000Z | 2022-01-12T18:44:13.000Z | src/rt/rt.c | Li-Reactive-Water-Group/BioRT-Flux-PIHM | 7a32acfa467e3211ab52322d88fb7919242b37c2 | [
"MIT"
] | 1 | 2021-02-05T11:22:40.000Z | 2021-02-05T11:22:40.000Z | src/rt/rt.c | Li-Reactive-Water-Group/BioRT-Flux-PIHM | 7a32acfa467e3211ab52322d88fb7919242b37c2 | [
"MIT"
] | 8 | 2019-08-19T04:12:35.000Z | 2021-04-11T20:33:11.000Z | /*******************************************************************************
* RT-Flux-PIHM is a finite volume based, reactive transport module that operates
* on top of the hydrological land surface processes described by Flux-PIHM.
* RT-Flux-PIHM tracks the transportation and reaction in a given watershed. It
* uses operator splitting technique to couple transport and reaction.
*****************************************************************************/
#include "pihm.h"
void InitChem(const char cdbs_filen[], const calib_struct *cal,
forc_struct *forc, chemtbl_struct chemtbl[], kintbl_struct kintbl[],
rttbl_struct *rttbl, chmictbl_struct *chmictbl, elem_struct elem[])
{
int i, j;
int chem_ind;
FILE *fp;
fp = fopen(cdbs_filen, "r");
CheckFile(fp, cdbs_filen);
/*
* Look up database to find required parameters and dependencies for
* chemical species
*/
Lookup(fp, cal, chemtbl, kintbl, rttbl);
fclose(fp);
/*
* Apply calibration
*/
#if OBSOLETE
rttbl->pumps[0].Injection_rate *= cal->gwinflux;
rttbl->pumps[0].flow_rate *= cal->gwinflux;
#endif
chem_ind = FindChem("'DOC'", chemtbl, rttbl->NumStc);
if (chem_ind >= 0)
{
rttbl->prcp_conc[chem_ind] *= cal->prcpconc;
if (forc->PrpFlg == 2)
{
for (i = 0; i < forc->nprcpc; i++)
{
for (j = 0; j < forc->prcpc[i].length; j++)
{
forc->prcpc[i].data[j][chem_ind] *= cal->prcpconc;
}
}
}
}
for (i = 0; i < chmictbl->nic; i++)
{
int k;
for (k = 0; k < rttbl->NumStc; k++)
{
chmictbl->ssa[i][k] *= (chemtbl[k].itype == MINERAL) ?
cal->ssa : 1.0;
chmictbl->conc[i][k] *=
(strcmp(chemtbl[k].ChemName, "'DOC'") == 0) ?
cal->initconc : 1.0;
}
}
/*
* Assign initial conditions to different volumes
*/
for (i = 0; i < nelem; i++)
{
int k;
int *ic_type;
ic_type = elem[i].attrib.chem_ic_type;
for (k = 0; k < rttbl->NumStc; k++)
{
elem[i].restart_input[UNSAT_CHMVOL].t_conc[k] =
chmictbl->conc[ic_type[UNSAT_CHMVOL] - 1][k];
elem[i].restart_input[UNSAT_CHMVOL].ssa[k] =
chmictbl->ssa[ic_type[UNSAT_CHMVOL] - 1][k];
elem[i].restart_input[GW_CHMVOL].t_conc[k] =
chmictbl->conc[ic_type[GW_CHMVOL] - 1][k];
elem[i].restart_input[GW_CHMVOL].ssa[k] =
chmictbl->ssa[ic_type[GW_CHMVOL] - 1][k];
#if defined(_FBR_)
elem[i].restart_input[FBRUNSAT_CHMVOL].t_conc[k] =
chmictbl->conc[ic_type[FBRUNSAT_CHMVOL] - 1][k];
elem[i].restart_input[FBRUNSAT_CHMVOL].ssa[k] =
chmictbl->ssa[ic_type[FBRUNSAT_CHMVOL] - 1][k];
elem[i].restart_input[FBRGW_CHMVOL].t_conc[k] =
chmictbl->conc[ic_type[FBRGW_CHMVOL] - 1][k];
elem[i].restart_input[FBRGW_CHMVOL].ssa[k] =
chmictbl->ssa[ic_type[FBRGW_CHMVOL] - 1][k];
#endif
}
}
}
void InitRTVar(const chemtbl_struct chemtbl[], const rttbl_struct *rttbl,
elem_struct elem[], river_struct river[], N_Vector CV_Y)
{
int i;
/*
* Initializing element concentrations
*/
PIHMprintf(VL_VERBOSE, "\n Initializing concentrations... \n");
for (i = 0; i < nelem; i++)
{
double vol_gw;
double vol_unsat;
vol_gw = MAX(GWStrg(elem[i].soil.depth, elem[i].soil.smcmax,
elem[i].soil.smcmin, elem[i].ws.gw), DEPTHR) *
elem[i].topo.area;
vol_unsat = MAX(UnsatWaterStrg(elem[i].soil.depth, elem[i].soil.smcmax,
elem[i].soil.smcmin, elem[i].ws.gw, elem[i].ws.unsat), DEPTHR) *
elem[i].topo.area;
InitChemS(chemtbl, rttbl, &elem[i].restart_input[UNSAT_CHMVOL],
elem[i].soil.smcmax, vol_unsat, &elem[i].chms_unsat);
InitChemS(chemtbl, rttbl, &elem[i].restart_input[GW_CHMVOL],
elem[i].soil.smcmax, vol_gw, &elem[i].chms_gw);
#if defined(_FBR_)
vol_gw = MAX(GWStrg(elem[i].geol.depth, elem[i].geol.smcmax,
elem[i].geol.smcmin, elem[i].ws.fbr_gw), DEPTHR) *
elem[i].topo.area;
vol_unsat = MAX(UnsatWaterStrg(elem[i].geol.depth, elem[i].geol.smcmax,
elem[i].geol.smcmin, elem[i].ws.fbr_gw, elem[i].ws.fbr_unsat),
DEPTHR) * elem[i].topo.area;
InitChemS(chemtbl, rttbl, &elem[i].restart_input[FBRUNSAT_CHMVOL],
elem[i].geol.smcmax, vol_unsat, &elem[i].chms_fbrunsat);
InitChemS(chemtbl, rttbl, &elem[i].restart_input[FBRGW_CHMVOL],
elem[i].geol.smcmax, vol_gw, &elem[i].chms_fbrgw);
#endif
}
/*
* Initialize river concentrations
*/
for (i = 0; i < nriver; i++)
{
double vol_rivbed;
double vol_stream;
int k;
vol_rivbed = MAX(RivBedStrg(&river[i].matl, &river[i].ws), DEPTHR) *
river[i].topo.area;
vol_stream = river[i].topo.area * MAX(river[i].ws.stage, DEPTHR);
for (k = 0; k < rttbl->NumStc; k++)
{
if (chemtbl[k].itype == AQUEOUS)
{
river[i].chms_stream.t_conc[k] =
0.5 * elem[river[i].leftele - 1].chms_gw.t_conc[k] +
0.5 * elem[river[i].rightele - 1].chms_gw.t_conc[k];
river[i].chms_stream.p_actv[k] = river[i].chms_stream.t_conc[k];
river[i].chms_stream.p_conc[k] = river[i].chms_stream.t_conc[k];
river[i].chms_stream.t_mole[k] =
river[i].chms_stream.t_conc[k] * vol_stream;
river[i].chms_rivbed.t_conc[k] =
0.5 * elem[river[i].leftele - 1].chms_gw.t_conc[k] +
0.5 * elem[river[i].rightele - 1].chms_gw.t_conc[k];
river[i].chms_rivbed.p_actv[k] = river[i].chms_rivbed.t_conc[k];
river[i].chms_rivbed.p_conc[k] = river[i].chms_rivbed.t_conc[k];
river[i].chms_rivbed.t_mole[k] =
river[i].chms_rivbed.t_conc[k] * vol_rivbed;
}
else
{
river[i].chms_stream.t_conc[k] = ZERO_CONC;
river[i].chms_stream.p_conc[k] = ZERO_CONC;
river[i].chms_stream.p_actv[k] = ZERO_CONC;
river[i].chms_stream.t_mole[k] = 0.0;
river[i].chms_rivbed.t_conc[k] = ZERO_CONC;
river[i].chms_rivbed.p_conc[k] = ZERO_CONC;
river[i].chms_rivbed.p_actv[k] = ZERO_CONC;
river[i].chms_rivbed.t_mole[k] = 0.0;
}
}
for (k = 0; k < rttbl->NumSsc; k++)
{
river[i].chms_stream.s_conc[k] = ZERO_CONC;
river[i].chms_rivbed.s_conc[k] = ZERO_CONC;
}
}
#if defined(_OPENMP)
# pragma omp parallel for
#endif
for (i = 0; i < nelem; i++)
{
int k;
for (k = 0; k < NumSpc; k++)
{
NV_Ith(CV_Y, UNSAT_MOLE(i, k)) = elem[i].chms_unsat.t_mole[k];
NV_Ith(CV_Y, GW_MOLE(i, k)) = elem[i].chms_gw.t_mole[k];
elem[i].chmf.react_unsat[k] = 0.0;
elem[i].chmf.react_gw[k] = 0.0;
#if defined(_FBR_)
NV_Ith(CV_Y, FBRUNSAT_MOLE(i, k)) = elem[i].chms_fbrunsat.t_mole[k];
NV_Ith(CV_Y, FBRGW_MOLE(i, k)) = elem[i].chms_fbrgw.t_mole[k];
elem[i].chmf.react_fbrunsat[k] = 0.0;
elem[i].chmf.react_fbrgw[k] = 0.0;
#endif
}
}
#if defined(_OPENMP)
# pragma omp parallel for
#endif
for (i = 0; i < nriver; i++)
{
int k;
for (k = 0; k < NumSpc; k++)
{
NV_Ith(CV_Y, STREAM_MOLE(i, k)) = river[i].chms_stream.t_mole[k];
NV_Ith(CV_Y, RIVBED_MOLE(i, k)) = river[i].chms_rivbed.t_mole[k];
}
}
}
void InitChemS(const chemtbl_struct chemtbl[], const rttbl_struct *rttbl,
const rtic_struct *restart_input, double smcmax, double vol,
chmstate_struct *chms)
{
int k;
for (k = 0; k < rttbl->NumStc; k++)
{
if (strcmp(chemtbl[k].ChemName, "'H+'") == 0)
{
chms->t_conc[k] = restart_input->t_conc[k];
chms->p_actv[k] = chms->t_conc[k];
chms->p_conc[k] = chms->t_conc[k];
chms->ssa[k] = restart_input->ssa[k];
}
else if (chemtbl[k].itype == MINERAL)
{
chms->t_conc[k] = restart_input->t_conc[k];
/* Update the concentration of mineral using molar volume */
chms->t_conc[k] *= (rttbl->RelMin == 0) ?
/* Absolute mineral volume fraction */
1000.0 / chemtbl[k].MolarVolume / smcmax :
/* Relative mineral volume fraction */
(1.0 - smcmax) * 1000.0 / chemtbl[k].MolarVolume / smcmax;
chms->p_actv[k] = 1.0;
chms->p_conc[k] = chms->t_conc[k];
chms->ssa[k] = restart_input->ssa[k];
}
else if ((chemtbl[k].itype == CATION_ECHG) ||
(chemtbl[k].itype == ADSORPTION))
{
chms->t_conc[k] = restart_input->t_conc[k];
chms->p_actv[k] = chms->t_conc[k] * 0.5;
/* Change unit of CEC (eq g-1) into C(ion site)
* (eq L-1 porous space), assuming density of solid is always
* 2650 g L-1 */
chms->t_conc[k] *= (1.0 - smcmax) * 2650.0;
chms->p_conc[k] = chms->t_conc[k];
}
else
{
chms->t_conc[k] = restart_input->t_conc[k];
chms->p_actv[k] = chms->t_conc[k] * 0.5;
chms->p_conc[k] = chms->t_conc[k] * 0.5;
chms->ssa[k] = restart_input->ssa[k];
}
}
for (k = 0; k < rttbl->NumSsc; k++)
{
chms->s_conc[k] = ZERO_CONC;
}
/* Speciation */
if (rttbl->RecFlg == KIN_REACTION)
{
_Speciation(chemtbl, rttbl, 1, chms);
}
/* Total moles should be calculated after speciation */
for (k = 0; k < rttbl->NumStc; k++)
{
if (chemtbl[k].itype == AQUEOUS)
{
chms->t_mole[k] = chms->t_conc[k] * vol;
}
else
{
chms->t_mole[k] = 0.0;
}
}
}
double GWStrg(double depth, double smcmax, double smcmin, double gw)
{
double strg;
if (gw < 0.0)
{
strg = 0.0;
}
else if (gw > depth)
{
strg = depth * smcmax + (gw - depth) * (smcmax - smcmin);
}
else
{
strg = gw * smcmax;
}
return strg;
}
double UnsatWaterStrg(double depth, double smcmax, double smcmin, double gw,
double unsat)
{
double deficit;
deficit = depth - gw;
deficit = MIN(deficit, depth);
deficit = MAX(deficit, 0.0);
return deficit * smcmin + MAX(unsat, 0.0) * (smcmax - smcmin);
}
double UnsatSatRatio(double depth, double unsat, double gw)
{
return ((unsat < 0.0) ? 0.0 : ((gw > depth) ? 1.0 : unsat / (depth - gw)));
}
double RivBedStrg(const matl_struct *matl, const river_wstate_struct *ws)
{
double strg;
if (ws->gw < 0.0)
{
strg = 0.0;
}
else if (ws->gw > matl->bedthick)
{
strg = matl->bedthick * (matl->porosity + matl->smcmin) +
(ws->gw - matl->bedthick) * matl->porosity;
}
else
{
strg = ws->gw * (matl->porosity + matl->smcmin);
}
return strg;
}
void UpdatePConc(elem_struct elem[], river_struct river[])
{
int i;
#if defined(_OPENMP)
# pragma omp parallel for
#endif
for (i = 0; i < nelem; i++)
{
int k;
for (k = 0; k < NumSpc; k++)
{
elem[i].chms_unsat.p_conc[k] = elem[i].chms_unsat.t_conc[k];
elem[i].chms_gw.p_conc[k] = elem[i].chms_gw.t_conc[k];
#if defined(_FBR_)
elem[i].chms_fbrunsat.p_conc[k] = elem[i].chms_fbrunsat.t_conc[k];
elem[i].chms_fbrgw.p_conc[k] = elem[i].chms_fbrgw.t_conc[k];
#endif
}
}
#if defined(_OPENMP)
# pragma omp parallel for
#endif
for (i = 0; i < nriver; i++)
{
int k;
for (k = 0; k < NumSpc; k++)
{
river[i].chms_stream.p_conc[k] = river[i].chms_stream.t_conc[k];
river[i].chms_rivbed.p_conc[k] = river[i].chms_rivbed.t_conc[k];
}
}
}
| 30.887805 | 80 | 0.51603 |
043969154678200f43fd3d756f883c596915c257 | 1,321 | kt | Kotlin | sessionize/lib/src/commonMain/kotlin/co/touchlab/sessionize/ScheduleModel.kt | archiegq21/DroidconKotlin | 8c3ec05448d586037c924f245f77fcd0150f0476 | [
"Apache-2.0"
] | null | null | null | sessionize/lib/src/commonMain/kotlin/co/touchlab/sessionize/ScheduleModel.kt | archiegq21/DroidconKotlin | 8c3ec05448d586037c924f245f77fcd0150f0476 | [
"Apache-2.0"
] | 1 | 2021-06-14T11:55:00.000Z | 2021-06-15T15:03:39.000Z | sessionize/lib/src/commonMain/kotlin/co/touchlab/sessionize/ScheduleModel.kt | archiegq21/DroidconKotlin | 8c3ec05448d586037c924f245f77fcd0150f0476 | [
"Apache-2.0"
] | null | null | null | package co.touchlab.sessionize
import co.touchlab.droidcon.db.SessionWithRoom
import co.touchlab.sessionize.db.SessionizeDbHelper
import co.touchlab.sessionize.display.DaySchedule
import co.touchlab.sessionize.display.convertMapToDaySchedule
import co.touchlab.sessionize.display.formatHourBlocks
import co.touchlab.sessionize.util.LogHandler
import kotlinx.coroutines.Dispatchers
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
/**
* Data model for schedule. Configure live data instances.
*/
class ScheduleModel(private val allEvents: Boolean) :
BaseQueryModelView<SessionWithRoom, List<DaySchedule>>(
SessionizeDbHelper.getSessionsQuery(),
{
val dbSessions = it.executeAsList()
val sessions = if (allEvents) {
dbSessions
} else {
dbSessions.filter { it.rsvp != 0L }
}
val hourBlocks = formatHourBlocks(sessions)
convertMapToDaySchedule(hourBlocks)
},
Dispatchers.Main
), KoinComponent {
private val logHandler: LogHandler by inject()
init {
logHandler.log("init ScheduleModel()")
}
fun register(view: ScheduleView) {
super.register(view)
}
interface ScheduleView : View<List<DaySchedule>>
} | 30.022727 | 61 | 0.697956 |
176051bf7c1461b5f0d889d037364911bd88eb22 | 201 | html | HTML | src/app/item/item-detail.component.html | darlandc/doctor | 0546bd032d15091487119be896d8da1a38f3b4d2 | [
"Apache-2.0"
] | null | null | null | src/app/item/item-detail.component.html | darlandc/doctor | 0546bd032d15091487119be896d8da1a38f3b4d2 | [
"Apache-2.0"
] | null | null | null | src/app/item/item-detail.component.html | darlandc/doctor | 0546bd032d15091487119be896d8da1a38f3b4d2 | [
"Apache-2.0"
] | null | null | null | <ActionBar title="Welcome"></ActionBar>
<FlexboxLayout flexDirection="column">
<FlexboxLayout class="m-15">
<Label class="h2" text="Welcome"></Label>
</FlexboxLayout>
</FlexboxLayout>
| 25.125 | 49 | 0.681592 |
989c22044f40ad2cb0a51b8f3cd01f912339eaad | 21,779 | html | HTML | Stanford C++ Lib Doc/web.stanford.edu/class/archive/cs/cs106b/cs106b.1138/materials/cppdoc/index.html | Liquidibrium/PAbstractions | e3cf51b5d713a181abdda87ed5205d998289f878 | [
"MIT"
] | null | null | null | Stanford C++ Lib Doc/web.stanford.edu/class/archive/cs/cs106b/cs106b.1138/materials/cppdoc/index.html | Liquidibrium/PAbstractions | e3cf51b5d713a181abdda87ed5205d998289f878 | [
"MIT"
] | null | null | null | Stanford C++ Lib Doc/web.stanford.edu/class/archive/cs/cs106b/cs106b.1138/materials/cppdoc/index.html | Liquidibrium/PAbstractions | e3cf51b5d713a181abdda87ed5205d998289f878 | [
"MIT"
] | null | null | null | <html>
<!-- Mirrored from web.stanford.edu/class/archive/cs/cs106b/cs106b.1138/materials/cppdoc/ by HTTrack Website Copier/3.x [XR&CO'2014], Sat, 13 Feb 2016 11:47:25 GMT -->
<head>
<title>The Stanford <code>cslib</code> package</title>
<link rel="stylesheet" type="text/css" href="cppdoc.css" />
</head>
<body>
<table class=banner>
<tr>
<td valign=middle><image src="images/StanfordTreeLogo.png" height=32></td>
<td valign=middle><div class=bannerText>
The Stanford <code>cslib</code> package
</div></td>
</tr></table>
<hr>
The <code>StanfordCPPLib</code> package defines a set of libraries that
make it easier to write programs in C++. The facilities provided by
these libraries can be broken down into the following groups:
<ol>
<li><b><i>Function libraries.</i></b>
Several of the interfaces
(<a href="console.html"><code>console.h</code></a>,
<a href="direction.html"><code>direction.h</code></a>,
<a href="error.html"><code>error.h</code></a>,
<a href="filelib.html"><code>filelib.h</code></a>,
<a href="foreach.html"><code>foreach.h</code></a>,
<a href="gmath.html"><code>gmath.h</code></a>,
<a href="random.html"><code>random.h</code></a>,
<a href="simpio.html"><code>simpio.h</code></a>,
<a href="strlib.html"><code>strlib.h</code></a>,
<a href="thread.html"><code>thread.h</code></a>) export collections
of free functions instead of classes.
<p><li><b><i>Collection classes.</i></b>
Several of the classes
(<a href="Graph-class.html"><code>Graph</code></a>,
<a href="Grid-class.html"><code>Grid</code></a>,
<a href="HashMap-class.html"><code>HashMap</code></a>,
<a href="HashSet-class.html"><code>HashSet</code></a>,
<a href="Lexicon-class.html"><code>Lexicon</code></a>,
<a href="Map-class.html"><code>Map</code></a>,
<a href="PriorityQueue-class.html"><code>PriorityQueue</code></a>,
<a href="Queue-class.html"><code>Queue</code></a>,
<a href="Set-class.html"><code>Set</code></a>,
<a href="Stack-class.html"><code>Stack</code></a>,
<a href="Vector-class.html"><code>Vector</code></a>)
represent collections of other objects.
These collections work in much the same way as the similar classes in
the Standard Template Library (STL).
<p><li><b><i>Graphics classes.</i></b>
Most of the classes in the <code>StanfordCPPLib</code> package are used
to support graphics. These classes can themselves be broken down into
the following categories:
<ul>
<li>The <a href="GWindow-class.html"><code>GWindow</code></a> class,
which represents a window that appears on the display screen
<li>A collection of graphics objects, each of which is a subclass of
<a href="GObject-class.html"><code>GObject</code></a>
(<a href="GArc-class.html"><code>GArc</code></a>,
<a href="GCompound-class.html"><code>GCompound</code></a>,
<a href="GImage-class.html"><code>GImage</code></a>,
<a href="GLabel-class.html"><code>GLabel</code></a>,
<a href="GLine-class.html"><code>GLine</code></a>,
<a href="GOval-class.html"><code>GOval</code></a>,
<a href="GPolygon-class.html"><code>GPolygon</code></a>,
<a href="GRect-class.html"><code>GRect</code></a>,
<a href="G3DRect-class.html"><code>G3DRect</code></a>,
<a href="GRoundRect-class.html"><code>GRoundRect</code></a>)
<li>A set of onscreen interactors
(<a href="GCheckBox-class.html"><code>GCheckBox</code></a>,
<a href="GChooser-class.html"><code>GChooser</code></a>,
<a href="GSlider-class.html"><code>GSlider</code></a>,
<a href="GTextField-class.html"><code>GTextField</code></a>,
<a href="GButton-class.html"><code>GButton</code></a>)
<li>A hierarchical set of classes for fielding events
(<a href="GEvent-class.html"><code>GEvent</code></a>,
<a href="GActionEvent-class.html"><code>GActionEvent</code></a>,
<a href="GKeyEvent-class.html"><code>GKeyEvent</code></a>,
<a href="GMouseEvent-class.html"><code>GMouseEvent</code></a>,
<a href="GTimerEvent-class.html"><code>GTimerEvent</code></a>,
<a href="GWindowEvent-class.html"><code>GWindowEvent</code></a>)
<li>A set of classes to encapsulate geometric information
(<a href="GDimension-class.html"><code>GDimension</code></a>,
<a href="GPoint-class.html"><code>GPoint</code></a>,
<a href="GRectangle-class.html"><code>GRectangle</code></a>)
</ul>
<br><li><b><i>Utility classes.</i></b>
The libraries also export several utility classes that don’t
fit easily into the other categories
(<a href="ErrorException-class.html"><code>ErrorException</code></a>,
<a href="Lock-class.html"><code>Lock</code></a>,
<a href="Point-class.html"><code>Point</code></a>,
<a href="Sound-class.html"><code>Sound</code></a>,
<a href="Thread-class.html"><code>Thread</code></a>,
<a href="TokenScanner-class.html"><code>TokenScanner</code></a>).
</ol>
<p>Additional documentation appears in the web pages for the individual
classes, along with sample code.
<table class=index width=100%>
<tr><td class=indexHead colspan=2>Classes</td></tr>
<tr><td class=indexKey><nobr><a href="ErrorException-class.html">ErrorException</a> </nobr></td><td class=indexSynopsis width=100%>This exception is thrown by calls to the <code>error</code> function.</td></tr>
<tr><td class=indexKey><nobr><a href="G3DRect-class.html">G3DRect</a> </nobr></td><td class=indexSynopsis width=100%>This graphical object subclass represents a rectangular box that can be raised or lowered.</td></tr>
<tr><td class=indexKey><nobr><a href="GActionEvent-class.html">GActionEvent</a> </nobr></td><td class=indexSynopsis width=100%>This event subclass represents an action event.</td></tr>
<tr><td class=indexKey><nobr><a href="GArc-class.html">GArc</a> </nobr></td><td class=indexSynopsis width=100%>This graphical object subclass represents an elliptical arc.</td></tr>
<tr><td class=indexKey><nobr><a href="GButton-class.html">GButton</a> </nobr></td><td class=indexSynopsis width=100%>This interactor subclass represents an onscreen button.</td></tr>
<tr><td class=indexKey><nobr><a href="GCheckBox-class.html">GCheckBox</a> </nobr></td><td class=indexSynopsis width=100%>This interactor subclass represents an onscreen check box.</td></tr>
<tr><td class=indexKey><nobr><a href="GChooser-class.html">GChooser</a> </nobr></td><td class=indexSynopsis width=100%>This interactor subclass represents a selectable list.</td></tr>
<tr><td class=indexKey><nobr><a href="GCompound-class.html">GCompound</a> </nobr></td><td class=indexSynopsis width=100%>This graphical object subclass consists of a collection of other graphical objects.</td></tr>
<tr><td class=indexKey><nobr><a href="GDimension-class.html">GDimension</a> </nobr></td><td class=indexSynopsis width=100%>This class contains real-valued width and height fields.</td></tr>
<tr><td class=indexKey><nobr><a href="GEvent-class.html">GEvent</a> </nobr></td><td class=indexSynopsis width=100%>This class is the root of the hierarchy for all events.</td></tr>
<tr><td class=indexKey><nobr><a href="GImage-class.html">GImage</a> </nobr></td><td class=indexSynopsis width=100%>This graphical object subclass represents an image from a file.</td></tr>
<tr><td class=indexKey><nobr><a href="GInteractor-class.html">GInteractor</a> </nobr></td><td class=indexSynopsis width=100%>This abstract class is the superclass for all graphical interactors.</td></tr>
<tr><td class=indexKey><nobr><a href="GKeyEvent-class.html">GKeyEvent</a> </nobr></td><td class=indexSynopsis width=100%>This event subclass represents a key event.</td></tr>
<tr><td class=indexKey><nobr><a href="GLabel-class.html">GLabel</a> </nobr></td><td class=indexSynopsis width=100%>This graphical object subclass represents a text string.</td></tr>
<tr><td class=indexKey><nobr><a href="GLine-class.html">GLine</a> </nobr></td><td class=indexSynopsis width=100%>This graphical object subclass represents a line segment.</td></tr>
<tr><td class=indexKey><nobr><a href="GMouseEvent-class.html">GMouseEvent</a> </nobr></td><td class=indexSynopsis width=100%>This event subclass represents a mouse event.</td></tr>
<tr><td class=indexKey><nobr><a href="GObject-class.html">GObject</a> </nobr></td><td class=indexSynopsis width=100%>This class is the common superclass of all graphical objects that can be displayed on a graphical window.</td></tr>
<tr><td class=indexKey><nobr><a href="GOval-class.html">GOval</a> </nobr></td><td class=indexSynopsis width=100%>This graphical object subclass represents an oval inscribed in a rectangular box.</td></tr>
<tr><td class=indexKey><nobr><a href="GPoint-class.html">GPoint</a> </nobr></td><td class=indexSynopsis width=100%>This class contains real-valued x and y fields.</td></tr>
<tr><td class=indexKey><nobr><a href="GPolygon-class.html">GPolygon</a> </nobr></td><td class=indexSynopsis width=100%>This graphical object subclass represents a polygon bounded by line segments.</td></tr>
<tr><td class=indexKey><nobr><a href="Graph-class.html">Graph<NodeType,ArcType></a> </nobr></td><td class=indexSynopsis width=100%>This class represents a graph with the specified node and arc types.</td></tr>
<tr><td class=indexKey><nobr><a href="GRect-class.html">GRect</a> </nobr></td><td class=indexSynopsis width=100%>This class represents a graphical object whose appearance consists of a rectangular box.</td></tr>
<tr><td class=indexKey><nobr><a href="GRectangle-class.html">GRectangle</a> </nobr></td><td class=indexSynopsis width=100%>This type contains real-valued x, y, width, and height fields.</td></tr>
<tr><td class=indexKey><nobr><a href="Grid-class.html">Grid<ValueType></a> </nobr></td><td class=indexSynopsis width=100%>This class stores an indexed, two-dimensional array.</td></tr>
<tr><td class=indexKey><nobr><a href="GRoundRect-class.html">GRoundRect</a> </nobr></td><td class=indexSynopsis width=100%>This class represents a graphical object whose appearance consists of a rectangular box with rounded corners.</td></tr>
<tr><td class=indexKey><nobr><a href="GSlider-class.html">GSlider</a> </nobr></td><td class=indexSynopsis width=100%>This interactor subclass represents an onscreen slider.</td></tr>
<tr><td class=indexKey><nobr><a href="GTextField-class.html">GTextField</a> </nobr></td><td class=indexSynopsis width=100%>This interactor subclass represents a text field for entering short text strings.</td></tr>
<tr><td class=indexKey><nobr><a href="GTimer-class.html">GTimer</a> </nobr></td><td class=indexSynopsis width=100%>This class implements a simple interval timer that generates a <code>GTimerEvent</code> with a specified frequency.</td></tr>
<tr><td class=indexKey><nobr><a href="GTimerEvent-class.html">GTimerEvent</a> </nobr></td><td class=indexSynopsis width=100%>This event subclass represents a timer event.</td></tr>
<tr><td class=indexKey><nobr><a href="GWindow-class.html">GWindow</a> </nobr></td><td class=indexSynopsis width=100%>This class represents a graphics window that supports simple graphics.</td></tr>
<tr><td class=indexKey><nobr><a href="GWindowEvent-class.html">GWindowEvent</a> </nobr></td><td class=indexSynopsis width=100%>This event subclass represents a window event.</td></tr>
<tr><td class=indexKey><nobr><a href="HashMap-class.html">HashMap<KeyType,ValueType></a> </nobr></td><td class=indexSynopsis width=100%>This class implements an efficient association between <b><i>keys</i></b> and <b><i>values</i></b>.</td></tr>
<tr><td class=indexKey><nobr><a href="HashSet-class.html">HashSet<ValueType></a> </nobr></td><td class=indexSynopsis width=100%>This class implements an efficient abstraction for storing sets of distinct elements.</td></tr>
<tr><td class=indexKey><nobr><a href="Lexicon-class.html">Lexicon</a> </nobr></td><td class=indexSynopsis width=100%>This class is used to represent a <b><i>lexicon,</i></b> or word list.</td></tr>
<tr><td class=indexKey><nobr><a href="Lock-class.html">Lock</a> </nobr></td><td class=indexSynopsis width=100%>This class represents a simple lock used to control concurrency.</td></tr>
<tr><td class=indexKey><nobr><a href="Map-class.html">Map<KeyType,ValueType></a> </nobr></td><td class=indexSynopsis width=100%>This class maintains an association between <b><i>keys</i></b> and <b><i>values</i></b>.</td></tr>
<tr><td class=indexKey><nobr><a href="Point-class.html">Point</a> </nobr></td><td class=indexSynopsis width=100%>This class represents an <i>x</i>-<i>y</i> coordinate point on a two-dimensional integer grid.</td></tr>
<tr><td class=indexKey><nobr><a href="PriorityQueue-class.html">PriorityQueue<ValueType></a> </nobr></td><td class=indexSynopsis width=100%>This class models a structure called a <b><i>priority queue</i></b> in which values are processed in order of priority.</td></tr>
<tr><td class=indexKey><nobr><a href="Queue-class.html">Queue<ValueType></a> </nobr></td><td class=indexSynopsis width=100%>This class models a linear structure called a <b><i>queue</i></b> in which values are added at one end and removed from the other.</td></tr>
<tr><td class=indexKey><nobr><a href="Set-class.html">Set<ValueType></a> </nobr></td><td class=indexSynopsis width=100%>This class stores a collection of distinct elements.</td></tr>
<tr><td class=indexKey><nobr><a href="Sound-class.html">Sound</a> </nobr></td><td class=indexSynopsis width=100%>This class encapsulates a sound file.</td></tr>
<tr><td class=indexKey><nobr><a href="Stack-class.html">Stack<ValueType></a> </nobr></td><td class=indexSynopsis width=100%>This class models a linear structure called a <b><i>stack</i></b> in which values are added and removed only from one end.</td></tr>
<tr><td class=indexKey><nobr><a href="Thread-class.html">Thread</a> </nobr></td><td class=indexSynopsis width=100%>This class encapsulates a lightweight process running in the same address space as the creator.</td></tr>
<tr><td class=indexKey><nobr><a href="TokenScanner-class.html">TokenScanner</a> </nobr></td><td class=indexSynopsis width=100%>This class divides a string into individual tokens.</td></tr>
<tr><td class=indexKey><nobr><a href="Vector-class.html">Vector<ValueType></a> </nobr></td><td class=indexSynopsis width=100%>This class stores an ordered list of values similar to an array.</td></tr>
</table>
<table class=index width=100%>
<tr><td class=indexHead colspan=2>Interface files</td></tr>
<tr><td class=indexKey><nobr><a href="console.html">console.h</a> </nobr></td><td class=indexSynopsis width=100%>This file redirects the <code>cin</code>, <code>cout</code>, and <code>cerr</code> channels to use a console window.</td></tr>
<tr><td class=indexKey><nobr><a href="direction.html">direction.h</a> </nobr></td><td class=indexSynopsis width=100%>This file exports an enumerated type called <code>Direction</code> whose elements are the four compass points: <code>NORTH</code>, <code>EAST</code>, <code>SOUTH</code>, and <code>WEST</code>.</td></tr>
<tr><td class=indexKey><nobr><a href="error.html">error.h</a> </nobr></td><td class=indexSynopsis width=100%>This file defines the <code>ErrorException</code> class and the <code>error</code> function.</td></tr>
<tr><td class=indexKey><nobr><a href="filelib.html">filelib.h</a> </nobr></td><td class=indexSynopsis width=100%>This file exports a standardized set of tools for working with files.</td></tr>
<tr><td class=indexKey><nobr><a href="foreach.html">foreach.h</a> </nobr></td><td class=indexSynopsis width=100%>This file defines the <code>foreach</code> keyword, which implements a substitute for the range-based <code>for</code> loop from C++11.</td></tr>
<tr><td class=indexKey><nobr><a href="gevents.html">gevents.h</a> </nobr></td><td class=indexSynopsis width=100%>This file defines the event types used in the StanfordCPPLib graphics libraries.</td></tr>
<tr><td class=indexKey><nobr><a href="ginteractors.html">ginteractors.h</a> </nobr></td><td class=indexSynopsis width=100%>This file exports a hierarchy of graphical interactors similar to those provided in the Java Swing libraries.</td></tr>
<tr><td class=indexKey><nobr><a href="gmath.html">gmath.h</a> </nobr></td><td class=indexSynopsis width=100%>This file exports several functions for working with graphical geometry along with the mathematical constants <code>PI</code> and <code>E</code>.</td></tr>
<tr><td class=indexKey><nobr><a href="gobjects.html">gobjects.h</a> </nobr></td><td class=indexSynopsis width=100%>This file exports a hierarchy of graphical shapes based on the model developed for the ACM Java Graphics.</td></tr>
<tr><td class=indexKey><nobr><a href="graph.html">graph.h</a> </nobr></td><td class=indexSynopsis width=100%>This file exports a parameterized <code>Graph</code> class used to represent <b><i>graphs,</i></b> which consist of a set of <b><i>nodes</i></b> and a set of <b><i>arcs</i></b>.</td></tr>
<tr><td class=indexKey><nobr><a href="grid.html">grid.h</a> </nobr></td><td class=indexSynopsis width=100%>This file exports the <code>Grid</code> class, which offers a convenient abstraction for representing a two-dimensional array.</td></tr>
<tr><td class=indexKey><nobr><a href="gtimer.html">gtimer.h</a> </nobr></td><td class=indexSynopsis width=100%>This file defines the <code>GTimer</code> class, which implements a general interval timer.</td></tr>
<tr><td class=indexKey><nobr><a href="gtypes.html">gtypes.h</a> </nobr></td><td class=indexSynopsis width=100%>This file defines classes for representing points, dimensions, and rectangles.</td></tr>
<tr><td class=indexKey><nobr><a href="gwindow.html">gwindow.h</a> </nobr></td><td class=indexSynopsis width=100%>This file defines the <code>GWindow</code> class which supports drawing graphical objects on the screen.</td></tr>
<tr><td class=indexKey><nobr><a href="hashmap.html">hashmap.h</a> </nobr></td><td class=indexSynopsis width=100%>This file exports the <code>HashMap</code> class, which stores a set of <i>key</i>-<i>value</i> pairs.</td></tr>
<tr><td class=indexKey><nobr><a href="hashset.html">hashset.h</a> </nobr></td><td class=indexSynopsis width=100%>This file exports the <code>HashSet</code> class, which implements an efficient abstraction for storing sets of values.</td></tr>
<tr><td class=indexKey><nobr><a href="lexicon.html">lexicon.h</a> </nobr></td><td class=indexSynopsis width=100%>This file exports the <code>Lexicon</code> class, which is a compact structure for storing a list of words.</td></tr>
<tr><td class=indexKey><nobr><a href="map.html">map.h</a> </nobr></td><td class=indexSynopsis width=100%>This file exports the template class <code>Map</code>, which maintains a collection of <i>key</i>-<i>value</i> pairs.</td></tr>
<tr><td class=indexKey><nobr><a href="point.html">point.h</a> </nobr></td><td class=indexSynopsis width=100%>This file exports a class representing an integer-valued <i>x</i>-<i>y</i> pair.</td></tr>
<tr><td class=indexKey><nobr><a href="pqueue.html">pqueue.h</a> </nobr></td><td class=indexSynopsis width=100%>This file exports the <code>PriorityQueue</code> class, a collection in which values are processed in priority order.</td></tr>
<tr><td class=indexKey><nobr><a href="queue.html">queue.h</a> </nobr></td><td class=indexSynopsis width=100%>This file exports the <code>Queue</code> class, a collection in which values are ordinarily processed in a first-in/first-out (FIFO) order.</td></tr>
<tr><td class=indexKey><nobr><a href="random.html">random.h</a> </nobr></td><td class=indexSynopsis width=100%>This file exports functions for generating pseudorandom numbers.</td></tr>
<tr><td class=indexKey><nobr><a href="set.html">set.h</a> </nobr></td><td class=indexSynopsis width=100%>This file exports the <code>Set</code> class, which implements a collection for storing a set of distinct elements.</td></tr>
<tr><td class=indexKey><nobr><a href="simpio.html">simpio.h</a> </nobr></td><td class=indexSynopsis width=100%>This file exports a set of functions that simplify input/output operations in C++ and provide some error-checking on console input.</td></tr>
<tr><td class=indexKey><nobr><a href="sound.html">sound.h</a> </nobr></td><td class=indexSynopsis width=100%>This file defines a class that represents a sound.</td></tr>
<tr><td class=indexKey><nobr><a href="stack.html">stack.h</a> </nobr></td><td class=indexSynopsis width=100%>This file exports the <code>Stack</code> class, which implements a collection that processes values in a last-in/first-out (LIFO) order.</td></tr>
<tr><td class=indexKey><nobr><a href="strlib.html">strlib.h</a> </nobr></td><td class=indexSynopsis width=100%>This file exports several useful string functions that are not included in the C++ string library.</td></tr>
<tr><td class=indexKey><nobr><a href="thread.html">thread.h</a> </nobr></td><td class=indexSynopsis width=100%>This file exports a simple, platform-independent thread abstraction, along with simple tools for concurrency control.</td></tr>
<tr><td class=indexKey><nobr><a href="tokenscanner.html">tokenscanner.h</a> </nobr></td><td class=indexSynopsis width=100%>This file exports a <code>TokenScanner</code> class that divides a string into individual logical units called <b><i>tokens</i></b>.</td></tr>
<tr><td class=indexKey><nobr><a href="vector.html">vector.h</a> </nobr></td><td class=indexSynopsis width=100%>This file exports the <code>Vector</code> class, which provides an efficient, safe, convenient replacement for the array type in C++.</td></tr>
</table>
</body>
<!-- Mirrored from web.stanford.edu/class/archive/cs/cs106b/cs106b.1138/materials/cppdoc/ by HTTrack Website Copier/3.x [XR&CO'2014], Sat, 13 Feb 2016 11:47:50 GMT -->
</html>
| 112.262887 | 324 | 0.726893 |
9a87503e31abd72071658301c71bf1bc174596b3 | 4,977 | css | CSS | src/app/module/data-center/source/code/data-source-update-code.component.css | cagegit/chang-ng4 | e21eeb5400d302b855b978321b5a677c3ee6badb | [
"MIT"
] | null | null | null | src/app/module/data-center/source/code/data-source-update-code.component.css | cagegit/chang-ng4 | e21eeb5400d302b855b978321b5a677c3ee6badb | [
"MIT"
] | null | null | null | src/app/module/data-center/source/code/data-source-update-code.component.css | cagegit/chang-ng4 | e21eeb5400d302b855b978321b5a677c3ee6badb | [
"MIT"
] | null | null | null | .code_title {
padding-left: 116px;
background: url("../../../../../assets/img/code_bg.jpg") no-repeat left center;
}
.isource_title {
padding-left: 116px;
background: url("../../../../../assets/img/isource_bg.png") no-repeat left center;
}
.sync_radio {
height: 56px;
line-height: 56px;
padding-left: 25px;
font-size: 14px;
color: #666;
position: relative;
}
.sync_radio input {
display: none;
}
.sync_radio .radio_btn {
position: absolute;
height: 16px;
width: 16px;
border-radius: 50%;
top: 20px;
left: 0;
background-color: #d5d6d8;
}
.sync_radio .radio_btn:before {
display: block;
position: absolute;
width: 12px;
height: 12px;
content: '';
border-radius: 50%;
background-color: #fff;
left: 2px;
top: 2px;
}
.sync_radio input:checked+.radio_btn {
background-color: #5dbea0;
}
.sync_radio input:checked+.radio_btn:after {
display: block;
width: 4px;
height: 4px;
border-radius: 50%;
position: absolute;
content: '';
left: 6px;
top: 6px;
background-color: #5dbea0
}
.sync_select select {
outline: none;
width: 190px;
height: 38px;
line-height: 36px;
border: 1px solid #e6eaec;
background-color: #f7f7f7;
padding: 0 10px;
border-radius: 3px;
color: #666;
font-size: 12px;
float: left;
margin-right: 10px;
}
/****/
.item_box {
width: 400px;
border: 1px solid #e6eaec;
border-radius: 3px;
height: 345px;
margin-bottom: 40px;
position: relative;
}
.item_box_page {
height: 20px;
position: absolute;
bottom: -30px;
left: 0;
width: 100%;
}
.item_title {
height: 42px;
padding: 0 20px;
line-height: 40px;
border-bottom: 1px solid #e6eaec;
font-size: 12px;
color: #333;
background-color: #f7f7f7;
}
.select_tabel {
width: 900px;
}
.item_list {
height: 300px;
}
.item_list li {
height: 38px;
line-height: 38px;
font-size: 14px;
color: #333;
margin-top: 12px;
background-color: #f9f9f9;
padding: 0 40px 0 50px;
cursor: pointer;
position: relative;
}
.item_list li:hover {
background-color: #fffff5;
}
.item_list li.selected {
background-color: #e1e1e1;
}
.item_list i {
color: #859acf;
position: absolute;
top: 0;
}
.item_list i.left_icon {
left: 15px;
}
.item_list i.right_icon {
right: 15px;
}
.has_selected li:before,
.has_selected li:after {
content: '';
position: absolute;
overflow: hidden;
display: block;
font-size: 0;
}
.has_selected li:before {
width: 8px;
height: 2px;
background-color: #859acf;
right: 30px;
top: 18px;
}
.has_selected li:after {
width: 2px;
height: 8px;
background-color: #859acf;
right: 33px;
top: 15px;
}
.item_list .icon-shujubiao {
font-size: 22px;
vertical-align: middle;
}
.item_list .icon-yulan3 {
float: right;
font-size: 18px;
}
.set_gx {
width: 900px;
text-align: right;
margin-top: 15px;
}
.default_sql {
width: 900px;
}
.default_sql i {
margin-right: 5px;
color: #859acf
}
.default_textarea {
width: 900px;
border: 1px solid #e6eaec;
border-radius: 3px;
height: 166px;
position: relative;
}
.default_textarea textarea {
width: 100%;
height: 100%;
padding: 10px 15px;
line-height: 28px;
outline: none;
border: none;
background-color: transparent;
resize: none;
}
.default_textarea i {
position: absolute;
right: -30px;
top: -6px;
font-size: 20px;
color: #859acf;
cursor: pointer;
}
.create_success {
background: url("../../../../../assets/img/create_success_bg.jpg") no-repeat top center;
height: 216px;
}
.self_success_modal {
width: 226px;
}
.success_text p {
margin: 0;
padding: 0;
line-height: 30px;
color: #fff;
}
.success_text p:first-child {
font-size: 18px;
}
.success_text i {
font-size: 14px;
margin-right: 10px;
}
.success_text a {
color: #5bb1ff;
text-decoration: underline;
}
.has_select_project {
margin: 10px 0 13px 0;
line-height: 28px;
color: #666;
padding-left: 20px;
}
.has_select_project button {
width: 100px;
height: 28px;
margin-right: 10px;
vertical-align: middle;
line-height: 28px;
font-size: 14px;
}
.item_title {
position: relative;
}
.search_project {
width: 220px;
height: 24px;
position: absolute;
right: 15px;
top: 8px;
line-height: 24px;
}
.search_project input {
height: 24px;
line-height: 22px;
width: 100%;
border: 1px solid #dfdfdf;
border-radius: 3px;
padding: 0 25px 0 10px;
color: #999;
}
.search_project i {
position: absolute;
color: #b4b7c6;
right: 7px;
top: 0;
font-size: 12px;
}
.sync_radio {
padding-left: 20px;
}
.sync_radio label {
margin-right: 45px;
}
.item_box_page a {
display: inline-block;
width: 20px;
height: 20px;
text-align: center;
line-height: 20px;
text-decoration: none;
background-color: #c1cde7;
color: #fff;
border-radius: 50%;
cursor: pointer;
}
.item_box_page a.disable {
background-color: #efefef;
}
.item_box_page a i {
font-size: 12px;
cursor: default;
}
| 14.901198 | 90 | 0.652602 |
606277f407857fce7752fa6c2d1acce92b5e7e31 | 4,283 | html | HTML | app/content/texts/bengali_wbt/IS18.html | binu-alexander/thevachanonlineproject | 33c318bfc8b37de035d9c8e6b2a9bf8dea153b98 | [
"MIT"
] | 5 | 2019-12-18T05:17:19.000Z | 2020-04-04T07:07:21.000Z | app/content/texts/bengali_wbt/IS18.html | binu-alexander/thevachanonlineproject | 33c318bfc8b37de035d9c8e6b2a9bf8dea153b98 | [
"MIT"
] | 1 | 2020-04-30T01:25:38.000Z | 2020-04-30T01:25:38.000Z | app/content/texts/bengali_wbt/IS18.html | binu-alexander/thevachanonlineproject | 33c318bfc8b37de035d9c8e6b2a9bf8dea153b98 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html><head><meta charset='UTF-8' />
<meta name='viewport' content='width=device-width, initial-scale=1.0, user-scalable=no' />
<title>পবিত্র বাইবেল যিশাইয় 18</title>
<link href='mukti.css' rel='stylesheet' />
<link href='fallback.css' rel='stylesheet' />
</head><body dir='ltr' class='section-document'>
<div class='header'><div class='nav'>
<a class='home' href='index.html'> </a><a class='location mukti' href='IS.html'> যিশাইয় 18 </a>
<a class='prev' href='IS17.html'> </a>
<a class='next' href='IS19.html'> </a>
</div></div>
<div class='chapter section IS18 ben2006 ben IS mukti' dir='ltr' data-id='IS18' data-nextid='IS19' data-previd='IS17' lang='bn'>
<div class='c'>18</div>
<div class='s'>কূশীয়দের প্রতি ঈশ্বরের বাণী </div>
<div class='p'>
<span class='v IS18_1' data-id='IS18_1'><span class='verse1 v-num v-1'>1 </span>কূশীয় নদীগুলির দৈর্ঘ্য বরাবর দেশটির দিকে দেখ| দেশটি পতঙ্গে ভরে গিয়েছে| তুমি তাদের ডানার ভন ভন শব্দ শুনতে পাচ্ছ| </span>
<span class='v IS18_2' data-id='IS18_2'><span class='v-num v-2'>2 </span>ঐ দেশটি ভেলায করে সমুদ্রের ওপারে বার্তাবাহক পাঠাচ্ছে| </span></div>
<div class='b'>
<span class='v IS18_2' data-id='IS18_2'></span></div>
<div class='q'>
<span class='v IS18_2' data-id='IS18_2'>হে দ্রুতগামী বার্তাবাহকগণ, </span></div>
<div class='q2'>
<span class='v IS18_2' data-id='IS18_2'>দীর্ঘকায় ও মসৃণত্বকের লোকদের কাছে যাও| </span></div>
<div class='q'>
<span class='v IS18_2' data-id='IS18_2'>সমস্ত জায়গার লোকরা এই দীর্ঘকায় এবং মসৃণত্বকের লোকদের ভয় পায়, </span></div>
<div class='q2'>
<span class='v IS18_2' data-id='IS18_2'>তারা একটি শক্তিশালী জাতি যারা অন্য জাতিদের পরাজিত করে| </span></div>
<div class='q2'>
<span class='v IS18_2' data-id='IS18_2'>তারা একটি দেশে বাস করে যেটি নদীসমূহ দ্বারা বিভক্ত| </span></div>
<div class='q'>
<span class='v IS18_3' data-id='IS18_3'><span class='v-num v-3'>3 </span>ঐসব লোকদের সাবধান করে দাও যে তাদের কোন না কোন বিপদ ঘটবে| </span></div>
<div class='q2'>
<span class='v IS18_3' data-id='IS18_3'>এই দেশের লোকদের যে বিপদ ঘটবে সারা পৃথিবীর লোক তা দেখতে পাবে| </span></div>
<div class='q'>
<span class='v IS18_3' data-id='IS18_3'>এই সব লম্বা লোকদের কপালে যা ঘটবে তা পৃথিবীর সবাই পর্বতের ওপরে পতাকা ওড়ার দৃশ্যের মতো পরিষ্কার দেখতে পাবে| </span></div>
<div class='q2'>
<span class='v IS18_3' data-id='IS18_3'>যুদ্ধের আগে শিঙা ফোঁকার শব্দের মতো পৃথিবীর সবাই পরিষ্কার ভাবে তা শুনতে পাবে| </span></div>
<div class='b'> </div>
<div class='p'>
<span class='v IS18_4' data-id='IS18_4'><span class='v-num v-4'>4 </span>প্রভু বললেন, “যে জায়গা আমার জন্য তৈরী হয়েছে আমি সেখানে থাকব|<span class='note' id='footnote-201'><a href='#note-201' class='key'>*</a></span> কিন্তু 5আমি শান্তভাবে এইসব ঘটনা পর্যবেক্ষণ করব| গ্রীষ্মের এক মনোরম দুপুরে (যে সময়ে এক ফোঁটা বৃষ্টি হয় না অথচ ভোরে শিশির পড়ে|) </span>
<span class='v IS18_5' data-id='IS18_5'><span class='v-num v-5'>5 </span>একটা ভয়ঙ্কর কিছু ঘটবে| এটি ঘটবে ফসল কাটার সময়ের আগে যখন ফুলগুলি ফুটে যাবে এবং নতুন দ্রাক্ষাগুলি মঞ্জরীত হবে এবং বাড়তে থাকবে; কিন্তু তখন শত্রুরা এসে গাছগুলি কেটে ফেলবে ও দ্রাক্ষা লতাগুলি ছিঁড়ে ফেলবে এবং সেগুলি ছুঁড়ে ফেলে দেবে| </span>
<span class='v IS18_6' data-id='IS18_6'><span class='v-num v-6'>6 </span>দ্রাক্ষা ক্ষেতগুলি পর্বতের পাখি এবং বন্য জন্তুদের খাবার জন্য পড়ে থাকবে| গ্রীষ্মকালে পাখিরা দ্রাক্ষা-লতায বাসা বাঁধবে এবং শীতকালে বন্য জন্তুরা দ্রাক্ষা-লতা খাবে|” </span></div>
<div class='p'>
<span class='v IS18_7' data-id='IS18_7'><span class='v-num v-7'>7 </span>তখন দীর্ঘকায় ও মসৃণত্বকের লোকরা প্রভু সর্বশক্তিমানের জন্য একটি বিশেষ নৈবেদ্য নিয়ে আসবে| সমস্ত জায়গার লোকরা এই দীর্ঘকায়, মসৃণত্বকের লোকদের ভয় পায়| একটি ক্ষমতাবান জাতি যারা অন্য দেশসমূহকে পরাস্ত করে, তারা একটি দেশে বাস করে যেটি নদীসমূহ দ্বারা বিভক্ত| এই নৈবেদ্য সিয়োন পর্বতে, প্রভু যেখানে অধিষ্ঠান করেন, সেখানে আনা হবে| </span></div></div>
<div class='footnotes'>
<span class='footnote' id='note-201'><span class='key'>* </span><a href='#footnote-201' class='backref'>18:4</a> <span class='text'> <span class="fk">যে … থাকব </span><span class="ft">এটা হয়ত জেরুশালেমের মন্দিরকে উল্লেখ করছে|</span></span></span>
</div>
<div class='footer'><div class='nav'>
<a class='prev' href='IS17.html'></a>
<a class='home' href='index.html'></a>
<a class='next' href='IS19.html'></a>
</div></div>
</body></html>
| 75.140351 | 418 | 0.585804 |
e7bee31e7b4d3d20c4e0112d2a6c32b7899b92df | 1,361 | swift | Swift | Tests/WaniKaniClientTests/Requests/LevelProgression/GetAllLevelProgressionsRequestTests.swift | cplaverty/WaniKaniClient | 094d300f3813288c06a069bdd538c7d55def1d33 | [
"MIT"
] | 2 | 2019-12-28T03:32:48.000Z | 2020-04-19T12:56:43.000Z | Tests/WaniKaniClientTests/Requests/LevelProgression/GetAllLevelProgressionsRequestTests.swift | cplaverty/WaniKaniClient | 094d300f3813288c06a069bdd538c7d55def1d33 | [
"MIT"
] | null | null | null | Tests/WaniKaniClientTests/Requests/LevelProgression/GetAllLevelProgressionsRequestTests.swift | cplaverty/WaniKaniClient | 094d300f3813288c06a069bdd538c7d55def1d33 | [
"MIT"
] | null | null | null | import XCTest
@testable import WaniKaniClient
final class GetAllLevelProgressionsRequestTests: XCTestCase {
private let baseURL = URL(string: "https://api.wanikani.com/v2/")!
func testNoParams() {
let expected = URL(string: "level_progressions", relativeTo: baseURL)!.absoluteURL
let request = GetAllLevelProgressionsRequest()
XCTAssertEqual(request.requestURL, expected)
}
func testIDs() {
let expected = URL(string: "level_progressions?ids=3887,3943,4234,4432", relativeTo: baseURL)!.absoluteURL
let request = GetAllLevelProgressionsRequest(ids: [3887, 3943, 4234, 4432])
XCTAssertEqual(request.requestURL, expected)
}
func testUpdatedAfter() {
// DateFormatter only has millisecond precision
let expected = URL(string: "level_progressions?updated_after=2019-03-01T18:10:34.873000Z", relativeTo: baseURL)!.absoluteURL
let request = GetAllLevelProgressionsRequest(updatedAfter: makeUTCDate(year: 2019, month: 3, day: 1, hour: 18, minute: 10, second: 34, microsecond: 873542))
XCTAssertEqual(request.requestURL, expected)
}
static var allTests = [
("testNoParams", testNoParams),
("testIDs", testIDs),
("testUpdatedAfter", testUpdatedAfter),
]
}
| 35.815789 | 164 | 0.664217 |
90e0a3fe73680b6d78c677a08cb847e35af7aaf8 | 364 | py | Python | src/nlp/boneyard/scripts/find_security_group.py | khappucino/global-traffic-management | 81a80ae86c9119066c92df0727554cb5b61f9899 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/nlp/boneyard/scripts/find_security_group.py | khappucino/global-traffic-management | 81a80ae86c9119066c92df0727554cb5b61f9899 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/nlp/boneyard/scripts/find_security_group.py | khappucino/global-traffic-management | 81a80ae86c9119066c92df0727554cb5b61f9899 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | import boto3
def find_security_group(ec2_client):
filters = [{'Name':'tag:Name', 'Values':['int-test-backend-server']}]
results = ec2_client.describe_security_groups(Filters=filters)
if len(results) == 0:
print("none")
return None
else:
print(results['SecurityGroups'][0]['GroupId'])
return results['SecurityGroups'][0]['GroupId']
| 30.333333 | 71 | 0.678571 |
38a1b78a587d4119486040ab04021826afa0de66 | 726 | kt | Kotlin | src/main/kotlin/org/hildan/ipm/helper/galaxy/bonuses/Managers.kt | joffrey-bion/idle-planet-miner-helper | abd74f6fe41d8535a2690361f76b171c2083ecb4 | [
"MIT"
] | 1 | 2021-04-29T20:24:51.000Z | 2021-04-29T20:24:51.000Z | src/main/kotlin/org/hildan/ipm/helper/galaxy/bonuses/Managers.kt | joffrey-bion/idle-planet-miner-helper | abd74f6fe41d8535a2690361f76b171c2083ecb4 | [
"MIT"
] | null | null | null | src/main/kotlin/org/hildan/ipm/helper/galaxy/bonuses/Managers.kt | joffrey-bion/idle-planet-miner-helper | abd74f6fe41d8535a2690361f76b171c2083ecb4 | [
"MIT"
] | null | null | null | package org.hildan.ipm.helper.galaxy.bonuses
import org.hildan.ipm.helper.galaxy.planets.Planet
import org.hildan.ipm.helper.utils.completedBy
import java.util.EnumMap
data class Manager(
private val name: String,
private val planetBonus: PlanetBonus,
private val globalBonus: Bonus = Bonus.NONE
) {
fun toBonus(associatedPlanet: Planet): Bonus =
globalBonus + Bonus(perPlanet = mapOf(associatedPlanet to planetBonus).completedBy { PlanetBonus.NONE })
}
data class ManagerAssignment(
private val assignedManagers: Map<Planet, Manager> = EnumMap(Planet::class.java)
) {
val bonus = assignedManagers
.map { (p, m) -> m.toBonus(p) }
.fold(Bonus.NONE) { b1, b2 -> b1 + b2}
}
| 31.565217 | 116 | 0.710744 |
e9ee97b743eb5eae415e662d6e8be032839ab683 | 4,401 | go | Go | service/route53recoverycluster/doc.go | Skarlso/aws-sdk-go | 6a228d939132a3159d0dce221879efbedd842d61 | [
"Apache-2.0"
] | null | null | null | service/route53recoverycluster/doc.go | Skarlso/aws-sdk-go | 6a228d939132a3159d0dce221879efbedd842d61 | [
"Apache-2.0"
] | null | null | null | service/route53recoverycluster/doc.go | Skarlso/aws-sdk-go | 6a228d939132a3159d0dce221879efbedd842d61 | [
"Apache-2.0"
] | null | null | null | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
// Package route53recoverycluster provides the client and types for making API
// requests to Route53 Recovery Cluster.
//
// Welcome to the Routing Control (Recovery Cluster) API Reference Guide for
// Amazon Route 53 Application Recovery Controller.
//
// With Route 53 ARC, you can use routing control with extreme reliability to
// recover applications by rerouting traffic across Availability Zones or Amazon
// Web Services Regions. Routing controls are simple on/off switches hosted
// on a highly available cluster in Route 53 ARC. A cluster provides a set of
// five redundant Regional endpoints against which you can run API calls to
// get or update the state of routing controls. To implement failover, you set
// one routing control On and another one Off, to reroute traffic from one Availability
// Zone or Amazon Web Services Region to another.
//
// Be aware that you must specify a Regional endpoint for a cluster when you
// work with API cluster operations to get or update routing control states
// in Route 53 ARC. In addition, you must specify the US West (Oregon) Region
// for Route 53 ARC API calls. For example, use the parameter --region us-west-2
// with AWS CLI commands. For more information, see Get and update routing control
// states using the API (https://docs.aws.amazon.com/r53recovery/latest/dg/routing-control.update.api.html)
// in the Amazon Route 53 Application Recovery Controller Developer Guide.
//
// This API guide includes information about the API operations for how to get
// and update routing control states in Route 53 ARC. To work with routing control
// in Route 53 ARC, you must first create the required components (clusters,
// control panels, and routing controls) using the recovery cluster configuration
// API.
//
// For more information about working with routing control in Route 53 ARC,
// see the following:
//
// * Create clusters, control panels, and routing controls by using API operations.
// For more information, see the Recovery Control Configuration API Reference
// Guide for Amazon Route 53 Application Recovery Controller (https://docs.aws.amazon.com/recovery-cluster/latest/api/).
//
// * Learn about the components in recovery control, including clusters,
// routing controls, and control panels, and how to work with Route 53 ARC
// in the Amazon Web Services console. For more information, see Recovery
// control components (https://docs.aws.amazon.com/r53recovery/latest/dg/introduction-components.html#introduction-components-routing)
// in the Amazon Route 53 Application Recovery Controller Developer Guide.
//
// * Route 53 ARC also provides readiness checks that continually audit resources
// to help make sure that your applications are scaled and ready to handle
// failover traffic. For more information about the related API operations,
// see the Recovery Readiness API Reference Guide for Amazon Route 53 Application
// Recovery Controller (https://docs.aws.amazon.com/recovery-readiness/latest/api/).
//
// * For more information about creating resilient applications and preparing
// for recovery readiness with Route 53 ARC, see the Amazon Route 53 Application
// Recovery Controller Developer Guide (https://docs.aws.amazon.com/r53recovery/latest/dg/).
//
// See https://docs.aws.amazon.com/goto/WebAPI/route53-recovery-cluster-2019-12-02 for more information on this service.
//
// See route53recoverycluster package documentation for more information.
// https://docs.aws.amazon.com/sdk-for-go/api/service/route53recoverycluster/
//
// Using the Client
//
// To contact Route53 Recovery Cluster with the SDK use the New function to create
// a new service client. With that client you can make API requests to the service.
// These clients are safe to use concurrently.
//
// See the SDK's documentation for more information on how to use the SDK.
// https://docs.aws.amazon.com/sdk-for-go/api/
//
// See aws.Config documentation for more information on configuring SDK clients.
// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config
//
// See the Route53 Recovery Cluster client Route53RecoveryCluster for more
// information on creating client for this service.
// https://docs.aws.amazon.com/sdk-for-go/api/service/route53recoverycluster/#New
package route53recoverycluster
| 57.907895 | 137 | 0.770052 |
cb263a70422995bec6a5d4a579c86953b37325db | 169 | h | C | prj.tools/augmentation/augmentation_utils.h | usilinsergey/objed | a5d0c82382a6546d5d4c649f153eec94c4ade0ee | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | prj.tools/augmentation/augmentation_utils.h | usilinsergey/objed | a5d0c82382a6546d5d4c649f153eec94c4ade0ee | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | prj.tools/augmentation/augmentation_utils.h | usilinsergey/objed | a5d0c82382a6546d5d4c649f153eec94c4ade0ee | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | #pragma once
#ifndef AUGMENTATION_UTILS_H_INCLUDED
#define AUGMENTATION_UTILS_H_INCLUDED
int normalValue(int mean, int sigma);
#endif // AUGMENTATION_UTILS_H_INCLUDED | 24.142857 | 40 | 0.846154 |
5d574fae34f574b9e231f85b46ec0eadb08e8a7b | 565 | go | Go | tests/nested_easy.go | reddyvinod/partialencode | 27c703181bf10ebc165f5086de3a74b3c2e7a755 | [
"MIT"
] | null | null | null | tests/nested_easy.go | reddyvinod/partialencode | 27c703181bf10ebc165f5086de3a74b3c2e7a755 | [
"MIT"
] | null | null | null | tests/nested_easy.go | reddyvinod/partialencode | 27c703181bf10ebc165f5086de3a74b3c2e7a755 | [
"MIT"
] | null | null | null | package tests
import (
"github.com/reddyvinod/partialencode"
"github.com/reddyvinod/partialencode/jwriter"
)
//partialencode:json
type NestedInterfaces struct {
Value interface{}
Slice []interface{}
Map map[string]interface{}
}
type NestedEasyMarshaler struct {
EasilyMarshaled bool
}
var _ partialencode.Marshaler = &NestedEasyMarshaler{}
func (i *NestedEasyMarshaler) MarshalPartialJSON(w *jwriter.Writer) {
// We use this method only to indicate that partialencode.Marshaler
// interface was really used while encoding.
i.EasilyMarshaled = true
} | 22.6 | 69 | 0.778761 |
274fea63bc618384624b356d1efe1e45f2175447 | 112 | css | CSS | src/components/Nav.css | easherma/netlify-cms-react-starter | 3c95d78a51faaa87063d6f331d5449586582c1b9 | [
"MIT"
] | null | null | null | src/components/Nav.css | easherma/netlify-cms-react-starter | 3c95d78a51faaa87063d6f331d5449586582c1b9 | [
"MIT"
] | null | null | null | src/components/Nav.css | easherma/netlify-cms-react-starter | 3c95d78a51faaa87063d6f331d5449586582c1b9 | [
"MIT"
] | null | null | null | .Nav {
background: white;
position: sticky;
top: 0;
z-index: 1;
}
.Nav--Container {
display: flex;
}
| 10.181818 | 20 | 0.589286 |
b6d0a7824306dcdea929c10794fd20569a4cba71 | 157 | rb | Ruby | project_cookbooks/packages/recipes/enable_internal_sources.rb | shabiel/ehmp-chef-repo | 6cbc7500305aefbf6bb600bcb8ea890408e68818 | [
"Apache-2.0"
] | null | null | null | project_cookbooks/packages/recipes/enable_internal_sources.rb | shabiel/ehmp-chef-repo | 6cbc7500305aefbf6bb600bcb8ea890408e68818 | [
"Apache-2.0"
] | null | null | null | project_cookbooks/packages/recipes/enable_internal_sources.rb | shabiel/ehmp-chef-repo | 6cbc7500305aefbf6bb600bcb8ea890408e68818 | [
"Apache-2.0"
] | null | null | null | #
# Cookbook Name:: no_internet
# Recipe:: default
#
include_recipe "packages::correct_ruby"
include_recipe "yum_wrapper"
include_recipe "rubygems_wrapper"
| 17.444444 | 39 | 0.796178 |
b960dd096c8c815605a819bb6b024d58cf81fd41 | 1,133 | asm | Assembly | programs/oeis/168/A168122.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/168/A168122.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/168/A168122.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A168122: n^2*(n^4+1)/2.
; 0,1,34,369,2056,7825,23346,58849,131104,265761,500050,885841,1493064,2413489,3764866,5695425,8388736,12068929,17006274,23523121,32000200,42883281,56690194,74018209,95551776,122070625,154458226,193710609,240945544,297412081,364500450,443752321,536871424,645734529,772402786,919133425,1088391816,1282863889,1505468914,1759372641,2048000800,2375052961,2744516754,3160682449,3628157896,4151883825,4737149506,5389608769,6115296384,6920644801,7812501250,8798145201,9885306184,11082181969,12397457106,13840321825,15420491296,17148225249,19034347954,21090268561,23328001800,25760189041,28400119714,31261753089,34359740416,37709447425,41326977186,45229193329,49433743624,53959083921,58824502450,64050144481,69657037344,75667115809,82103247826,88989260625,96349967176,104211193009,112599803394,121543730881,131072003200,141214771521,152003339074,163470190129,175649019336,188574761425,202283621266,216813104289,232202047264,248490649441,265720504050,283934630161,303177504904,323495096049,344934894946,367545949825,391378899456,416486007169,442921195234,470740079601
pow $0,2
mov $1,$0
pow $1,3
add $0,$1
div $0,2
| 125.888889 | 1,058 | 0.878199 |
f9c5a6fb5bb7dfddf6a07ac400f32880161c7041 | 6,212 | go | Go | user/email/email.go | alonl/dex | 123ececd100c088bc08eea7ff102b4e965a0ffa8 | [
"Apache-2.0"
] | null | null | null | user/email/email.go | alonl/dex | 123ececd100c088bc08eea7ff102b4e965a0ffa8 | [
"Apache-2.0"
] | null | null | null | user/email/email.go | alonl/dex | 123ececd100c088bc08eea7ff102b4e965a0ffa8 | [
"Apache-2.0"
] | 1 | 2019-11-14T06:39:33.000Z | 2019-11-14T06:39:33.000Z | package email
import (
"net/url"
"time"
"github.com/coreos/go-oidc/jose"
"github.com/coreos/dex/email"
"github.com/coreos/dex/pkg/log"
"github.com/coreos/dex/user"
)
// UserEmailer provides functions for sending emails to Users.
type UserEmailer struct {
ur user.UserRepo
pwi user.PasswordInfoRepo
signerFn signerFunc
tokenValidityWindow time.Duration
issuerURL url.URL
emailer *email.TemplatizedEmailer
fromAddress string
passwordResetURL url.URL
verifyEmailURL url.URL
invitationURL url.URL
}
// NewUserEmailer creates a new UserEmailer.
func NewUserEmailer(ur user.UserRepo,
pwi user.PasswordInfoRepo,
signerFn signerFunc,
tokenValidityWindow time.Duration,
issuerURL url.URL,
emailer *email.TemplatizedEmailer,
fromAddress string,
passwordResetURL url.URL,
verifyEmailURL url.URL,
invitationURL url.URL,
) *UserEmailer {
return &UserEmailer{
ur: ur,
pwi: pwi,
signerFn: signerFn,
tokenValidityWindow: tokenValidityWindow,
issuerURL: issuerURL,
emailer: emailer,
fromAddress: fromAddress,
passwordResetURL: passwordResetURL,
verifyEmailURL: verifyEmailURL,
invitationURL: invitationURL,
}
}
func (u *UserEmailer) userPasswordInfo(email string) (user.User, user.PasswordInfo, error) {
usr, err := u.ur.GetByEmail(nil, email)
if err != nil {
log.Errorf("Error getting user: %q", err)
return user.User{}, user.PasswordInfo{}, err
}
pwi, err := u.pwi.Get(nil, usr.ID)
if err != nil {
log.Errorf("Error getting password: %q", err)
return user.User{}, user.PasswordInfo{}, err
}
return usr, pwi, nil
}
func (u *UserEmailer) signedClaimsToken(claims jose.Claims) (string, error) {
signer, err := u.signerFn()
if err != nil || signer == nil {
log.Errorf("error getting signer: %v (%v)", err, signer)
return "", err
}
jwt, err := jose.NewSignedJWT(claims, signer)
if err != nil {
log.Errorf("error constructing or signing a JWT: %v", err)
return "", err
}
return jwt.Encode(), nil
}
// SendResetPasswordEmail sends a password reset email to the user specified by the email addresss, containing a link with a signed token which can be visitied to initiate the password change/reset process.
// This method DOES NOT check for client ID, redirect URL validity - it is expected that upstream users have already done so.
// A link that can be used to reset the given user's password is returned.
func (u *UserEmailer) SendResetPasswordEmail(email string, redirectURL url.URL, clientID string) (*url.URL, error) {
usr, pwi, err := u.userPasswordInfo(email)
if err != nil {
return nil, err
}
passwordReset := user.NewPasswordReset(usr.ID, pwi.Password, u.issuerURL,
clientID, redirectURL, u.tokenValidityWindow)
token, err := u.signedClaimsToken(passwordReset.Claims)
if err != nil {
return nil, err
}
resetURL := u.passwordResetURL
q := resetURL.Query()
q.Set("token", token)
resetURL.RawQuery = q.Encode()
if u.emailer != nil {
err = u.emailer.SendMail(u.fromAddress, "Reset Your Password", "password-reset",
map[string]interface{}{
"email": usr.Email,
"link": resetURL.String(),
}, usr.Email)
if err != nil {
log.Errorf("error sending password reset email %v: ", err)
}
return nil, err
}
return &resetURL, nil
}
// SendInviteEmail is sends an email that allows the user to both
// reset their password *and* verify their email address. Similar to
// SendResetPasswordEmail, the given url and client id are assumed
// valid. A link that can be used to validate the given email address
// and reset the password is returned.
func (u *UserEmailer) SendInviteEmail(email string, redirectURL url.URL, clientID string) (*url.URL, error) {
usr, pwi, err := u.userPasswordInfo(email)
if err != nil {
return nil, err
}
invitation := user.NewInvitation(usr, pwi.Password, u.issuerURL,
clientID, redirectURL, u.tokenValidityWindow)
token, err := u.signedClaimsToken(invitation.Claims)
if err != nil {
return nil, err
}
resetURL := u.invitationURL
q := resetURL.Query()
q.Set("token", token)
resetURL.RawQuery = q.Encode()
if u.emailer != nil {
err = u.emailer.SendMail(u.fromAddress, "Activate Your Account", "invite",
map[string]interface{}{
"email": usr.Email,
"link": resetURL.String(),
}, usr.Email)
if err != nil {
log.Errorf("error sending password reset email %v: ", err)
}
return nil, err
}
return &resetURL, nil
}
// SendEmailVerification sends an email to the user with the given userID containing a link which when visited marks the user as having had their email verified.
// If there is no emailer is configured, the URL of the aforementioned link is returned, otherwise nil is returned.
func (u *UserEmailer) SendEmailVerification(userID, clientID string, redirectURL url.URL) (*url.URL, error) {
usr, err := u.ur.Get(nil, userID)
if err == user.ErrorNotFound {
log.Errorf("No Such user for ID: %q", userID)
return nil, err
}
if err != nil {
log.Errorf("Error getting user: %q", err)
return nil, err
}
ev := user.NewEmailVerification(usr, clientID, u.issuerURL, redirectURL, u.tokenValidityWindow)
signer, err := u.signerFn()
if err != nil || signer == nil {
log.Errorf("error getting signer: %v (signer: %v)", err, signer)
return nil, err
}
jwt, err := jose.NewSignedJWT(ev.Claims, signer)
if err != nil {
log.Errorf("error constructing or signing EmailVerification JWT: %v", err)
return nil, err
}
token := jwt.Encode()
verifyURL := u.verifyEmailURL
q := verifyURL.Query()
q.Set("token", token)
verifyURL.RawQuery = q.Encode()
if u.emailer != nil {
err = u.emailer.SendMail(u.fromAddress, "Please verify your email address.", "verify-email",
map[string]interface{}{
"email": usr.Email,
"link": verifyURL.String(),
}, usr.Email)
if err != nil {
log.Errorf("error sending email verification email %v: ", err)
}
return nil, err
}
return &verifyURL, nil
}
func (u *UserEmailer) SetEmailer(emailer *email.TemplatizedEmailer) {
u.emailer = emailer
}
type signerFunc func() (jose.Signer, error)
| 29.164319 | 206 | 0.692531 |
560ed946ff2e9d001314f8bb025b6d660ae16699 | 994 | go | Go | pkg/k8s/poddisruptionbudget_test.go | bborbe/world | cf56490b360705677e53c7fb6e1e5ce1e0eba24e | [
"BSD-2-Clause"
] | null | null | null | pkg/k8s/poddisruptionbudget_test.go | bborbe/world | cf56490b360705677e53c7fb6e1e5ce1e0eba24e | [
"BSD-2-Clause"
] | null | null | null | pkg/k8s/poddisruptionbudget_test.go | bborbe/world | cf56490b360705677e53c7fb6e1e5ce1e0eba24e | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) 2018 Benjamin Borbe All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package k8s_test
import (
"bytes"
"testing"
"github.com/go-yaml/yaml"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/format"
"github.com/bborbe/world/pkg/k8s"
)
func TestPodDisruptionBudget(t *testing.T) {
}
var _ = Describe("PodDisruptionBudget", func() {
format.TruncatedDiff = true
It("encode", func() {
content := `apiVersion: policy/v1beta1
kind: PodDisruptionBudget
metadata:
name: test-pdb
labels:
app: test
spec:
maxUnavailable: 1
minAvailable: 1
selector:
matchLabels:
app: test
`
var data k8s.PodDisruptionBudget
err := yaml.NewDecoder(bytes.NewBufferString(content)).Decode(&data)
Expect(err).To(BeNil())
var b bytes.Buffer
err = yaml.NewEncoder(&b).Encode(data)
Expect(err).To(BeNil())
Expect(content).To(Equal(b.String()))
})
})
| 19.88 | 70 | 0.700201 |
5b128499db7f093607d7a4f558e48d5fe6361d18 | 3,426 | h | C | src/misynth/combinators.h | vmishenev/misynth | 5bd977cb32144a6d61670c874efad49982f75932 | [
"MIT"
] | null | null | null | src/misynth/combinators.h | vmishenev/misynth | 5bd977cb32144a6d61670c874efad49982f75932 | [
"MIT"
] | null | null | null | src/misynth/combinators.h | vmishenev/misynth | 5bd977cb32144a6d61670c874efad49982f75932 | [
"MIT"
] | null | null | null | #ifndef COMBINATORS_H
#define COMBINATORS_H
#include "util/vector.h"
class generator_permutation_with_repetitions
{
// URL: https://rosettacode.org/wiki/Permutations_with_repetitions#C.2B.2B
public:
generator_permutation_with_repetitions(int s, int v)
: m_slots(s),
m_values(v),
m_a(s)
{
reset();
}
bool do_next()
{
for (;;)
{
if (m_a[m_next_ind - 1] == m_values)
{
m_next_ind--;
if (m_next_ind == 0)
return false;
}
else
{
m_a[m_next_ind - 1]++;
while (m_next_ind < m_slots)
{
m_next_ind++;
m_a[m_next_ind - 1] = 1;
}
return true;
}
}
}
vector<unsigned int> &get_next()
{
return m_a;
}
void reset()
{
for (unsigned int i = 0; i < m_slots - 1; i++)
{
m_a[i] = 1;
}
m_a[m_slots - 1] = 0;
m_next_ind = m_slots;
}
void do_print()
{
printf("(");
for (int i = 0; i < m_slots; i++)
{
printf("%d", m_a[i]);
}
printf(")");
}
private:
int m_slots;
int m_values;
int m_next_ind;
vector<unsigned int> m_a;
};
class generator_combination_with_repetiton
{
public:
generator_combination_with_repetiton(unsigned int s, unsigned int v)
: m_slots(s),
m_values(v),
m_v(s),
m_is_first(true)
{
//reset();
}
bool do_next()
{
if (!m_is_first)
{
if (m_v.size() == 0)
return false;
m_v[0] += 1;
}
else
{
m_is_first = false;
return true;
}
for (unsigned int i = 0; i < m_slots; ++i) //vai um
{
if (m_v[i] + 1 > m_values)//if (m_v[i] > (m_values - 1))
{
if (i + 1 >= m_slots)
return false;
m_v[i + 1] += 1;
for (int k = i; k >= 0; --k)
{
m_v[k] = m_v[i + 1];
}
}
}
return true;
}
vector<unsigned int> &get_next()
{
return m_v;
}
void reset()
{
m_v.resize(m_slots, 0);
}
void do_print()
{
printf("(");
for (unsigned int i = 0; i < m_slots; i++)
{
printf("%d", m_v[i]);
}
printf(")");
}
private:
unsigned int m_slots;
unsigned int m_values;
vector<unsigned int> m_v;
bool m_is_first;
};
template<class T>
void print_vector(const vector<T> &v)
{
for (size_t i = 0; i < v.size(); ++i)
printf("%d", v[i]);
printf("\n");
}
#endif // COMBINATORS_H
| 21.4125 | 82 | 0.360771 |
c884419c0379d9621e979f1f238e39dc4e1a03c0 | 1,339 | kt | Kotlin | app/src/androidTest/java/pl/gdg/myapplication/ExampleInstrumentedTest.kt | GDG-Wro/android_workshop_16 | 0f7e7bb2f2d3b7b9f06cf34f50310144806cc0f4 | [
"MIT"
] | null | null | null | app/src/androidTest/java/pl/gdg/myapplication/ExampleInstrumentedTest.kt | GDG-Wro/android_workshop_16 | 0f7e7bb2f2d3b7b9f06cf34f50310144806cc0f4 | [
"MIT"
] | 3 | 2020-12-14T00:52:41.000Z | 2020-12-14T17:57:50.000Z | app/src/androidTest/java/pl/gdg/myapplication/ExampleInstrumentedTest.kt | GDG-Wro/android_workshop_16 | 0f7e7bb2f2d3b7b9f06cf34f50310144806cc0f4 | [
"MIT"
] | null | null | null | package pl.gdg.myapplication
import androidx.test.core.app.launchActivity
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("pl.gdg.workshop16", appContext.packageName)
}
@Test
fun changesLabelAfterGoClick() {
launchActivity<MainActivity>().use {
onView(withId(R.id.label)).check(ViewAssertions.matches(withText("Hello World!")))
onView(withText("Go!")).perform(click())
onView(withId(R.id.label)).check(ViewAssertions.matches(withText("Going!")))
}
}
} | 35.236842 | 94 | 0.74832 |
85abb2a71f77035d9a81bc7aac5dc89d88fc61e4 | 1,457 | js | JavaScript | src/misc/helpers.js | shradhaagarwal01/Chat-Application | bd66599041b841c4abb967230e6ef6fd4cb082b0 | [
"MIT"
] | null | null | null | src/misc/helpers.js | shradhaagarwal01/Chat-Application | bd66599041b841c4abb967230e6ef6fd4cb082b0 | [
"MIT"
] | null | null | null | src/misc/helpers.js | shradhaagarwal01/Chat-Application | bd66599041b841c4abb967230e6ef6fd4cb082b0 | [
"MIT"
] | null | null | null | export function getNameInitials(name) {
const splitName = name.toUpperCase().split(' ');
if (splitName.length > 1) {
return splitName[0][0] + splitName[1][0];
}
return splitName[0][0];
}
export function transformToArr(snapVal) {
return snapVal ? Object.keys(snapVal) : [];
}
export function transformToArrWithId(snapVal) {
return snapVal
? Object.keys(snapVal).map(roomId => {
return { ...snapVal[roomId], id: roomId };
})
: [];
}
export async function getUserUpdates(userId, keyToUpdate, value, db) {
const updates = {};
updates[`/profiles/${userId}/${keyToUpdate}`] = value;
const getMsgs = db
.ref('/messages')
.orderByChild('author/uid')
.equalTo(userId)
.once('value');
const getRooms = db
.ref('/rooms')
.orderByChild('lastMessage/author/uid')
.equalTo(userId)
.once('value');
const [mSnap, rSnap] = await Promise.all([getMsgs, getRooms]);
mSnap.forEach(msgSnap => {
updates[`/messages/${msgSnap.key}/author/${keyToUpdate}`] = value;
});
rSnap.forEach(roomSnap => {
updates[`/rooms/${roomSnap.key}/lastMessage/author/${keyToUpdate}`] = value;
});
return updates;
}
export function groupBy(array, groupingKeyFn) {
return array.reduce((result, item) => {
const groupingKey = groupingKeyFn(item);
if (!result[groupingKey]) {
result[groupingKey] = [];
}
result[groupingKey].push(item);
return result;
}, {});
}
| 22.075758 | 80 | 0.634866 |
7c86b441c37fa191396d56d1d9a6756fbab84617 | 668 | swift | Swift | Examples/UIScrollViewDemo/UIScrollViewDemo/CompanyCard/Cells/MyCoRightsRecommendCell.swift | huangboju/Moots | 122f54bc949b7f53a939e6153a8c04c3bef9a0f3 | [
"MIT"
] | 142 | 2016-12-05T07:23:50.000Z | 2022-02-15T05:25:59.000Z | Examples/UIScrollViewDemo/UIScrollViewDemo/CompanyCard/Cells/MyCoRightsRecommendCell.swift | liuchangjun9343/Moots | 9c004da865323d97a7ab929ca95e9881ade97804 | [
"MIT"
] | 1 | 2020-09-12T08:23:40.000Z | 2020-09-12T08:24:55.000Z | Examples/UIScrollViewDemo/UIScrollViewDemo/CompanyCard/Cells/MyCoRightsRecommendCell.swift | liuchangjun9343/Moots | 9c004da865323d97a7ab929ca95e9881ade97804 | [
"MIT"
] | 123 | 2016-11-02T05:52:12.000Z | 2022-02-15T05:26:01.000Z | //
// MyCoRightsRecommendCell.swift
// UIScrollViewDemo
//
// Created by 黄伯驹 on 2017/11/9.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
class MyCoRightsRecommendCell: UITableViewCell {
private lazy var recommendView: MyCoRightsRecommendView = {
let recommendView = MyCoRightsRecommendView()
return recommendView
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(recommendView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 25.692308 | 79 | 0.699102 |
98d88e3f120ced8b2bad3afe49040233fbd0b3a4 | 248 | html | HTML | template.html | timhudson/github-markdown-preview | 597f9eed4ffbb29b65970a0dc335188f56c140de | [
"MIT"
] | 22 | 2015-01-16T05:55:37.000Z | 2021-09-03T01:33:31.000Z | template.html | timhudson/github-markdown-preview | 597f9eed4ffbb29b65970a0dc335188f56c140de | [
"MIT"
] | 3 | 2015-05-24T21:10:41.000Z | 2015-06-24T13:56:01.000Z | template.html | timhudson/github-markdown-preview | 597f9eed4ffbb29b65970a0dc335188f56c140de | [
"MIT"
] | 7 | 2015-05-24T09:58:22.000Z | 2021-06-27T21:57:04.000Z | <link rel="stylesheet" href="github-markdown.css">
<style>
.markdown-body {
min-width: 200px;
max-width: 790px;
margin: 0 auto;
padding: 30px;
}
</style>
<article class="markdown-body">{{markdown}}</article>
| 22.545455 | 53 | 0.592742 |
ddd27aa53b260d630065de209c11f28be968ea74 | 1,797 | go | Go | crdb/crdbgorm/gorm.go | geekhsy/cockroach-go | bde659970ca1031011e097c1347a60ee1f389d09 | [
"Apache-2.0"
] | null | null | null | crdb/crdbgorm/gorm.go | geekhsy/cockroach-go | bde659970ca1031011e097c1347a60ee1f389d09 | [
"Apache-2.0"
] | null | null | null | crdb/crdbgorm/gorm.go | geekhsy/cockroach-go | bde659970ca1031011e097c1347a60ee1f389d09 | [
"Apache-2.0"
] | null | null | null | // Copyright 2016 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
package crdbgorm
import (
"context"
"database/sql"
"github.com/geekhsy/cockroach-go/v2/crdb"
"gorm.io/gorm"
)
// ExecuteTx runs fn inside a transaction and retries it as needed. On
// non-retryable failures, the transaction is aborted and rolled back; on
// success, the transaction is committed.
//
// See crdb.ExecuteTx() for more information.
func ExecuteTx(
ctx context.Context, db *gorm.DB, opts *sql.TxOptions, fn func(tx *gorm.DB) error,
) error {
tx := db.WithContext(ctx).Begin(opts)
if db.Error != nil {
return db.Error
}
return crdb.ExecuteInTx(ctx, gormTxAdapter{tx}, func() error { return fn(tx) })
}
// gormTxAdapter adapts a *gorm.DB to a crdb.Tx.
type gormTxAdapter struct {
db *gorm.DB
}
var _ crdb.Tx = gormTxAdapter{}
// Exec is part of the crdb.Tx interface.
func (tx gormTxAdapter) Exec(_ context.Context, q string, args ...interface{}) error {
return tx.db.Exec(q, args...).Error
}
// Commit is part of the crdb.Tx interface.
func (tx gormTxAdapter) Commit(_ context.Context) error {
return tx.db.Commit().Error
}
// Rollback is part of the crdb.Tx interface.
func (tx gormTxAdapter) Rollback(_ context.Context) error {
return tx.db.Rollback().Error
}
| 29.459016 | 86 | 0.72621 |
c2f5b078bba0e7beebd9d22235247005678eeef2 | 1,099 | go | Go | injection/injection.go | aaronkan007/owl | 6c82591e344a5e59a182cccc68e85da51fbd581f | [
"Apache-2.0"
] | 121 | 2021-08-13T03:40:33.000Z | 2022-02-23T06:14:24.000Z | injection/injection.go | aaronkan007/owl | 6c82591e344a5e59a182cccc68e85da51fbd581f | [
"Apache-2.0"
] | 13 | 2021-08-23T08:00:08.000Z | 2022-02-10T03:09:49.000Z | injection/injection.go | aaronkan007/owl | 6c82591e344a5e59a182cccc68e85da51fbd581f | [
"Apache-2.0"
] | 31 | 2021-08-19T09:43:27.000Z | 2022-01-13T03:43:31.000Z | package injection
import (
"github.com/ibanyu/owl/config"
"github.com/ibanyu/owl/dao"
"github.com/ibanyu/owl/service"
"github.com/ibanyu/owl/service/admin"
"github.com/ibanyu/owl/service/auth"
"github.com/ibanyu/owl/service/auth/login_check"
"github.com/ibanyu/owl/service/checker"
"github.com/ibanyu/owl/service/db_info"
"github.com/ibanyu/owl/service/task"
)
func Injection() {
task.SetBackupDao(dao.BackupDAO)
task.SetTaskDao(dao.Task)
task.SetSubTaskDao(dao.SubTask)
task.SetDbTools(db_info.DBTool)
task.SetChecker(checker.Checker)
checker.SetRuleStatusDao(dao.Rule)
db_info.SetClusterDao(dao.Cluster)
auth.SetLoginService(login_check.LoginService)
service.SetClock(service.RealClock{})
admin.SetAdminDao(dao.Admin)
switch config.Conf.Role.From {
case "conf":
task.SetAuthTools(auth.ConfAuthService)
case "net":
task.SetAuthTools(auth.NetAuthService)
case "admin":
task.SetAuthTools(auth.AdminAuthService)
case "mock":
MockInjection()
default:
task.SetAuthTools(auth.AdminAuthService)
}
}
func MockInjection() {
task.SetAuthTools(auth.MockAuthService)
}
| 24.977273 | 49 | 0.77707 |
7012b0ee0de563f59e1d753ee35ed4840b547dd3 | 710 | asm | Assembly | programs/oeis/033/A033562.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/033/A033562.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/033/A033562.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A033562: a(n) = 2*n^3 + 1.
; 1,3,17,55,129,251,433,687,1025,1459,2001,2663,3457,4395,5489,6751,8193,9827,11665,13719,16001,18523,21297,24335,27649,31251,35153,39367,43905,48779,54001,59583,65537,71875,78609,85751,93313,101307,109745,118639,128001,137843,148177,159015,170369,182251,194673,207647,221185,235299,250001,265303,281217,297755,314929,332751,351233,370387,390225,410759,432001,453963,476657,500095,524289,549251,574993,601527,628865,657019,686001,715823,746497,778035,810449,843751,877953,913067,949105,986079,1024001,1062883,1102737,1143575,1185409,1228251,1272113,1317007,1362945,1409939,1458001,1507143,1557377,1608715,1661169,1714751,1769473,1825347,1882385,1940599
pow $0,3
mul $0,2
add $0,1
| 101.428571 | 652 | 0.815493 |
977b5e47c4aa853844a85364bdd795e082bd6585 | 185 | sql | SQL | lhc_web/doc/update_db/update_199.sql | stroonsN/livehelperchat | 6812f7cc5c89f6c9953dabbb0064acc21c48c226 | [
"Apache-2.0"
] | 1,528 | 2015-01-04T03:19:36.000Z | 2022-03-31T14:25:00.000Z | lhc_web/doc/update_db/update_199.sql | stroonsN/livehelperchat | 6812f7cc5c89f6c9953dabbb0064acc21c48c226 | [
"Apache-2.0"
] | 864 | 2015-01-01T18:06:22.000Z | 2022-03-23T08:39:17.000Z | lhc_web/doc/update_db/update_199.sql | stroonsN/livehelperchat | 6812f7cc5c89f6c9953dabbb0064acc21c48c226 | [
"Apache-2.0"
] | 796 | 2015-01-04T13:39:43.000Z | 2022-03-31T08:08:46.000Z | INSERT INTO `lh_chat_config` (`identifier`,`value`,`type`,`explain`,`hidden`) VALUES ('preload_iframes','0','0','Preload widget. It will avoid loading delay after clicking widget','0'); | 185 | 185 | 0.72973 |
0bb8f8f69bb52fa834faf685df61eb014236845c | 79 | js | JavaScript | lib/examples2.js | shishiawase/drrr-lambot | f814b0ca8c5d1593352c29a0cfc6cbaa3148a63b | [
"MIT"
] | null | null | null | lib/examples2.js | shishiawase/drrr-lambot | f814b0ca8c5d1593352c29a0cfc6cbaa3148a63b | [
"MIT"
] | null | null | null | lib/examples2.js | shishiawase/drrr-lambot | f814b0ca8c5d1593352c29a0cfc6cbaa3148a63b | [
"MIT"
] | null | null | null | const { ytMusic } = require('./lib/tools.js');
globalThis.ytSearch = ytSearch
| 19.75 | 46 | 0.696203 |
c7c1717b45ba66fa9944a35f364ccd17e44f5b42 | 191 | py | Python | python_client/setup.py | girder/slicer-extension-manager | 3aa563d24ed4cedff94a375381a2cf7fd31f3e64 | [
"Apache-2.0"
] | 2 | 2018-02-22T18:33:16.000Z | 2018-02-28T03:55:22.000Z | python_client/setup.py | girder/slicer-extension-manager | 3aa563d24ed4cedff94a375381a2cf7fd31f3e64 | [
"Apache-2.0"
] | 15 | 2018-02-20T23:44:25.000Z | 2018-03-01T02:55:46.000Z | python_client/setup.py | girder/slicer-extension-manager | 3aa563d24ed4cedff94a375381a2cf7fd31f3e64 | [
"Apache-2.0"
] | 1 | 2018-02-16T18:16:58.000Z | 2018-02-16T18:16:58.000Z | # -*- coding: utf-8 -*-
from setuptools import setup
# This file is required to support editable install
# See https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html
setup()
| 21.222222 | 74 | 0.748691 |
c82cafd0266bf5176bf6a4407d9ed75b934ce49a | 576 | asm | Assembly | data/baseStats/typhlosion.asm | adhi-thirumala/EvoYellow | 6fb1b1d6a1fa84b02e2d982f270887f6c63cdf4c | [
"Unlicense"
] | 16 | 2018-08-28T21:47:01.000Z | 2022-02-20T20:29:59.000Z | data/baseStats/typhlosion.asm | adhi-thirumala/EvoYellow | 6fb1b1d6a1fa84b02e2d982f270887f6c63cdf4c | [
"Unlicense"
] | 5 | 2019-04-03T19:53:11.000Z | 2022-03-11T22:49:34.000Z | data/baseStats/typhlosion.asm | adhi-thirumala/EvoYellow | 6fb1b1d6a1fa84b02e2d982f270887f6c63cdf4c | [
"Unlicense"
] | 2 | 2019-12-09T19:46:02.000Z | 2020-12-05T21:36:30.000Z | db DEX_TYPHLOSION ; pokedex id
db 78 ; base hp
db 84 ; base attack
db 78 ; base defense
db 109 ; base speed
db 92 ; base special
db FIRE ; species type 1
db FIRE ; species type 2
db 31 ; catch rate
db 209 ; base exp yield
INCBIN "pic/ymon/typhlosion.pic",0,1 ; sprite dimensions
dw TyphlosionPicFront
dw TyphlosionPicBack
; attacks known at lvl 0
db TACKLE
db LEER
db SAND_ATTACK
db EMBER
db 3 ; growth rate
; learnset
tmlearn 6,8
tmlearn 10
tmlearn 0
tmlearn 28,31,32
tmlearn 34,38,39
tmlearn 44
tmlearn 50,51
db Bank(TyphlosionPicFront) ; padding
| 19.862069 | 57 | 0.725694 |
be2526a221386e53739cc9e771963f16435c05ab | 4,467 | rs | Rust | services/middleware/src/lib.rs | SergeiMal/exonum | 520324a321462bceb8acda9a92b9ed63fcdc3eaf | [
"Apache-2.0"
] | null | null | null | services/middleware/src/lib.rs | SergeiMal/exonum | 520324a321462bceb8acda9a92b9ed63fcdc3eaf | [
"Apache-2.0"
] | null | null | null | services/middleware/src/lib.rs | SergeiMal/exonum | 520324a321462bceb8acda9a92b9ed63fcdc3eaf | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Middleware service providing ways to compose transactions from the simpler building blocks.
//!
//! # Functionality overview
//!
//! ## Transaction batching
//!
//! [Batching] allows to atomically execute several transactions; if an error occurs
//! during execution, changes made by all transactions are rolled back. All transactions
//! in the batch are authorized in the same way as the batch itself.
//!
//! ## Checked call
//!
//! [Checked call] is a way to ensure that the called service corresponds to a specific artifact
//! with an expected version range. Unlike alternatives (e.g., finding out this information via
//! the `services` endpoint of the node HTTP API), using checked calls is most failsafe; by design,
//! it cannot suffer from [TOCTOU] issues. It does impose a certain overhead on the execution, though.
//!
//! [Batching]: trait.MiddlewareInterface.html#tymethod.batch
//! [Checked call]: trait.MiddlewareInterface.html#tymethod.checked_call
//! [TOCTOU]: https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use
#![deny(
unsafe_code,
bare_trait_objects,
missing_docs,
missing_debug_implementations
)]
pub use self::transactions::{
Batch, CheckedCall, Error, MiddlewareInterface, MiddlewareInterfaceMut,
};
pub mod proto;
mod transactions;
use exonum::runtime::{
rust::{DefaultInstance, Service},
InstanceId,
};
use exonum_derive::*;
use failure::format_err;
use semver::VersionReq;
use std::{fmt, str::FromStr};
/// Middleware service.
#[derive(Debug, ServiceDispatcher, ServiceFactory)]
#[service_dispatcher(implements("MiddlewareInterface"))]
#[service_factory(proto_sources = "proto")]
pub struct MiddlewareService;
impl Service for MiddlewareService {}
impl DefaultInstance for MiddlewareService {
const INSTANCE_ID: InstanceId = 1;
const INSTANCE_NAME: &'static str = "middleware";
}
/// Requirement on an artifact.
///
/// # Examples
///
/// Requirements can be used as a stub, generating a [`CheckedCall`].
///
/// [`CheckedCall`]: struct.CheckedCall.html
///
/// ```
/// # use exonum::runtime::InstanceId;
/// # use exonum_derive::*;
/// # use exonum_middleware_service::{ArtifactReq, CheckedCall};
/// // Requirements can be parsed from a string.
/// let req: ArtifactReq = "some.Service@^1.3.0".parse().unwrap();
///
/// // Suppose the interface for `some.Service` is defined as follows:
/// #[exonum_interface]
/// trait SomeService<Ctx> {
/// type Output;
/// fn do_something(&self, ctx: Ctx, arg: String) -> Self::Output;
/// }
///
/// // Then, requirements can be used to perform a checked call to the service.
/// const SERVICE_ID: InstanceId = 100;
/// let checked_call: CheckedCall = req.do_something(SERVICE_ID, "Arg".into());
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct ArtifactReq {
/// Artifact name.
pub name: String,
/// Allowed artifact versions.
pub version: VersionReq,
}
impl FromStr for ArtifactReq {
type Err = failure::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let parts: Vec<_> = s.splitn(2, '@').collect();
match &parts[..] {
[name, version] => Ok(Self {
name: name.to_string(),
version: version.parse()?,
}),
_ => Err(format_err!(
"Invalid artifact requirement. Use `name@version` format, \
e.g., `exonum.Token@^1.3.0`"
)),
}
}
}
impl fmt::Display for ArtifactReq {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{}@{}", self.name, self.version)
}
}
#[test]
fn artifact_req_parsing() {
let req: ArtifactReq = "exonum.Token@^1.0.5".parse().unwrap();
assert_eq!(req.name, "exonum.Token");
assert_eq!(req.version, "^1.0.5".parse().unwrap());
assert_eq!(req.to_string(), "exonum.Token@^1.0.5");
}
| 32.369565 | 102 | 0.675397 |
3b4c479e95dbf792d069f6b9e4cc9ef9cb3c4ff8 | 4,655 | kt | Kotlin | app/src/main/java/com/keelim/comssa/ui/SplashActivity.kt | keelim/comssa | 84c8f15e1d52cab941fa122ff856bc41271583f8 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/keelim/comssa/ui/SplashActivity.kt | keelim/comssa | 84c8f15e1d52cab941fa122ff856bc41271583f8 | [
"Apache-2.0"
] | 45 | 2021-07-15T12:27:15.000Z | 2022-03-30T12:31:43.000Z | app/src/main/java/com/keelim/comssa/ui/SplashActivity.kt | keelim/comssa | 84c8f15e1d52cab941fa122ff856bc41271583f8 | [
"Apache-2.0"
] | null | null | null | /*
* Designed and developed by 2021 keelim (Jaehyun Kim)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.keelim.comssa.ui
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.interstitial.InterstitialAd
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback
import com.keelim.comssa.BuildConfig
import com.keelim.comssa.databinding.ActivitySplashBinding
import com.keelim.comssa.ui.main.MainActivity
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import timber.log.Timber
@AndroidEntryPoint
class SplashActivity : AppCompatActivity() {
private var mInterstitialAd: InterstitialAd? = null
private val binding by lazy { ActivitySplashBinding.inflate(layoutInflater) }
private val test = "ca-app-pub-3940256099942544/1033173712"
private infix fun String.or(that: String): String = if (BuildConfig.DEBUG) this else that
private val scope = MainScope()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initSplash()
}
private fun initSplash() {
val permissions = arrayOf(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
permissions.plus(Manifest.permission.FOREGROUND_SERVICE)
}
if (hasPermissions(permissions)) { // 권한이 있는 경우
showAd()
} else {
ActivityCompat.requestPermissions(this, permissions, MULTIPLE_PERMISSIONS)
}
}
override fun onDestroy() {
super.onDestroy()
scope.cancel()
}
private fun showAd() {
val adRequest = AdRequest.Builder().build()
InterstitialAd.load(
this,
test or "ca-app-pub-3115620439518585/4013096159",
adRequest,
object : InterstitialAdLoadCallback() {
override fun onAdFailedToLoad(adError: LoadAdError) {
super.onAdFailedToLoad(adError)
Timber.d(adError.message)
mInterstitialAd = null
goNext()
}
override fun onAdLoaded(interstitialAd: InterstitialAd) {
super.onAdLoaded(interstitialAd)
Timber.d("Ad was loaded.")
mInterstitialAd = interstitialAd
mInterstitialAd!!.show(this@SplashActivity)
goNext()
}
}
)
}
private fun hasPermissions(permissions: Array<String>): Boolean {
permissions.forEach { permission ->
if (ActivityCompat.checkSelfPermission(
this,
permission
) != PackageManager.PERMISSION_GRANTED
)
return false
}
return true
}
// 권한 요청에 대한 결과 처리
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
MULTIPLE_PERMISSIONS -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
initSplash()
}
}
}
}
private fun goNext() {
scope.launch {
delay(1500)
startActivity(Intent(this@SplashActivity, MainActivity::class.java))
finish()
}
}
override fun onBackPressed() {}
companion object {
const val MULTIPLE_PERMISSIONS = 8888
}
}
| 32.78169 | 104 | 0.647691 |
906df488ef781352833a898b8bc9ccade2df57c0 | 835 | py | Python | cms/urls.py | schwalbe10/Django | 87fcc97669eccf6279e3a5064acacf97c26297cd | [
"MIT"
] | null | null | null | cms/urls.py | schwalbe10/Django | 87fcc97669eccf6279e3a5064acacf97c26297cd | [
"MIT"
] | null | null | null | cms/urls.py | schwalbe10/Django | 87fcc97669eccf6279e3a5064acacf97c26297cd | [
"MIT"
] | null | null | null | from django.conf.urls import patterns, url
from cms import views
urlpatterns = [
url(r'^record/$', views.record_list, name='record_list'), # List
url(r'^record/add/$', views.record_edit, name='record_add'), # Add
url(r'^record/mod/(?P<record_id>\d+)/$', views.record_edit, name='record_mod'), # Edit
url(r'^record/del/(?P<record_id>\d+)/$', views.record_del, name='record_del'), # Delete
url(r'^review/(?P<record_id>\d+)/$', views.ReviewList.as_view(), name='review_list'), # List
url(r'^review/add/(?P<record_id>\d+)/$', views.review_edit, name='review_add'), # Add
url(r'^review/mod/(?P<record_id>\d+)/(?P<review_id>\d+)/$', views.review_edit, name='review_mod'), # Edit
url(r'^review/del/(?P<record_id>\d+)/(?P<review_id>\d+)/$', views.review_del, name='review_del'), # Delete
]
| 55.666667 | 112 | 0.634731 |
817532badf072e0ac82a1a1aca90c916497fbfe7 | 161 | kt | Kotlin | threejs/src/main/kotlin/three/renderers/webgl/WebGLShadowMap.kt | Pozo/threejs-kotlin | a53df48f15f633deba31467e33aa798b453104fc | [
"MIT"
] | 18 | 2017-05-12T07:23:11.000Z | 2020-09-19T00:31:07.000Z | threejs/src/main/kotlin/three/renderers/webgl/WebGLShadowMap.kt | Pozo/threejs-kotlin | a53df48f15f633deba31467e33aa798b453104fc | [
"MIT"
] | null | null | null | threejs/src/main/kotlin/three/renderers/webgl/WebGLShadowMap.kt | Pozo/threejs-kotlin | a53df48f15f633deba31467e33aa798b453104fc | [
"MIT"
] | 1 | 2021-06-02T08:14:31.000Z | 2021-06-02T08:14:31.000Z | @file:JsQualifier("THREE")
package three.renderers.webgl
@JsName("WebGLShadowMap")
external class WebGLShadowMap {
var enabled: Boolean
var type: Int
} | 17.888889 | 31 | 0.745342 |
35f0f168f7a9f68352c68817fc6c0a9399478f91 | 15,478 | swift | Swift | Hockey Game/Retro Experience/In Game/GameViewController.swift | ctdewaters/bitHockey | cfa4b4237f375bdf3f8c5d488c0224495b8fec3b | [
"MIT"
] | null | null | null | Hockey Game/Retro Experience/In Game/GameViewController.swift | ctdewaters/bitHockey | cfa4b4237f375bdf3f8c5d488c0224495b8fec3b | [
"MIT"
] | null | null | null | Hockey Game/Retro Experience/In Game/GameViewController.swift | ctdewaters/bitHockey | cfa4b4237f375bdf3f8c5d488c0224495b8fec3b | [
"MIT"
] | null | null | null | //
// GameViewController.swift
// Hockey Game
//
// Created by Collin DeWaters on 3/18/17.
// Copyright © 2017 Collin DeWaters. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
import AVFoundation
///`GameViewController`: view controller that will display the `GameView` to present the user the game.
class GameViewController: UIViewController, HomeViewControllerDelegate, UIGestureRecognizerDelegate {
@IBOutlet var gameView: GameView!
var panGesture: UIPanGestureRecognizer!
var pauseButton: UIButton!
//MARK: - `UIViewController` overrides.
override func viewDidLoad() {
super.viewDidLoad()
//Setting the rink
Rink.shared.size = CGSize(width: 728, height: 1024)
Rink.shared.scaleMode = .aspectFill
gameView.presentScene(Rink.shared)
Rink.shared.animateCameraScale(toValue: 0.25, withDuration: 0.3)
NotificationCenter.default.addObserver(self, selector: #selector(self.gameEnded), name: .gameDidEnd, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//Setup home view.
self.presentHomeView(animated: false)
retroHomeVC.delegate = self
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden: Bool {
return false
}
//MARK: - Home view presentation.
///Presents the home view.
func presentHomeView(animated: Bool) {
//Add homeVC's view.
retroHomeVC.view.frame = self.view.frame
self.view.addSubview(retroHomeVC.view)
if animated {
retroHomeVC.view.alpha = 0
retroHomeVC.view.frame.origin.y = self.view.frame.maxY
UIView.animate(withDuration: 0.5, animations: {
retroHomeVC.view.alpha = 1
retroHomeVC.view.frame.origin.y = 0
}, completion: {
completed in
})
}
}
///Dismisses the home view.
func dismissHomeView(completion: @escaping ()->Void) {
Rink.shared.animateCameraScale(toValue: 0.6, withDuration: 0.3)
UIView.animate(withDuration: 0.3, animations: {
retroHomeVC.view.frame.origin.y = self.view.frame.maxY
retroHomeVC.view.alpha = 0
}) { (completed) in
if completed {
retroHomeVC.view.removeFromSuperview()
completion()
}
}
}
//MARK: - Game over menu.
///Presents the pause menu, with the game over message.
func presentGameOverMenu() {
//Add pauseVC's view.
pauseVC.view.frame = self.view.frame
//Setup pauseVC info.
pauseVC.homeScoreLabel.text = "\(Score.shared.userScore)"
pauseVC.roadScoreLabel.text = "\(Score.shared.cpuScore)"
pauseVC.timeRemainingLabel.text = "0:00"
pauseVC.blur.effect = nil
pauseVC.blur.contentView.alpha = 0
self.view.addSubview(pauseVC.view)
pauseVC.quitButton.isHidden = true
pauseVC.messageLabel.text = "Game Over"
pauseVC.resumeButton.setTitle("Exit", for: .normal)
pauseVC.blur.contentView.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
pauseVC.resumeButton.addTarget(self, action: #selector(self.exitGame), for: .touchUpInside)
//Animate in.
UIView.animate(withDuration: 0.3, animations: {
pauseVC.blur.effect = UIBlurEffect(style: .light)
pauseVC.blur.contentView.alpha = 1
pauseVC.blur.contentView.transform = .identity
}, completion: nil)
}
//MARK: - Pause menu
///Presents the pause menu.
func presentPauseView() {
Haptics.shared.playPeekHaptic()
//Add pauseVC's view.
pauseVC.view.frame = self.view.frame
//Setup pauseVC info.
pauseVC.homeScoreLabel.text = "\(Score.shared.userScore)"
pauseVC.roadScoreLabel.text = "\(Score.shared.cpuScore)"
pauseVC.timeRemainingLabel.text = Scoreboard.shared.clockView.timeLabel.text!
pauseVC.blur.effect = nil
pauseVC.blur.contentView.alpha = 0
pauseVC.messageLabel.text = "Paused"
self.view.addSubview(pauseVC.view)
pauseVC.quitButton.isHidden = false
pauseVC.resumeButton.setTitle("Resume", for: .normal)
pauseVC.blur.contentView.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
pauseVC.resumeButton.addTarget(self, action: #selector(self.resumeGame), for: .touchUpInside)
pauseVC.quitButton.addTarget(self, action: #selector(self.exitGame), for: .touchUpInside)
//Animate in.
UIView.animate(withDuration: 0.3, animations: {
pauseVC.blur.effect = UIBlurEffect(style: .light)
pauseVC.blur.contentView.alpha = 1
pauseVC.blur.contentView.transform = .identity
}, completion: nil)
}
///Dismisses the pause menu.
func dismissPauseView(completion: @escaping ()->Void) {
UIView.animate(withDuration: 0.3, animations: {
pauseVC.blur.effect = nil
pauseVC.blur.contentView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
pauseVC.blur.contentView.alpha = 0
}) { (completed) in
if completed {
pauseVC.view.removeFromSuperview()
pauseVC.blur.contentView.transform = .identity
completion()
}
}
}
//MARK: - Controls view.
///Presents the controls view.
func presentControlsView() {
controlsVC.view.frame = self.view.frame
controlsVC.blur.effect = nil
controlsVC.image.transform = .identity
controlsVC.image.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
controlsVC.closeButton.alpha = 0
controlsVC.image.alpha = 0
controlsVC.closeButton.addTarget(self, action: #selector(self.dismissControlsView), for: .touchUpInside)
self.view.addSubview(controlsVC.view)
UIView.animate(withDuration: 0.3, animations: {
controlsVC.blur.effect = UIBlurEffect(style: .light)
controlsVC.image.transform = .identity
controlsVC.closeButton.alpha = 1
controlsVC.image.alpha = 1
})
}
///Dismisses the controls view.
@objc func dismissControlsView() {
Haptics.shared.playPopHaptic()
UIView.animate(withDuration: 0.3, animations: {
controlsVC.blur.effect = nil
controlsVC.image.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
controlsVC.closeButton.alpha = 0
})
UIView.animate(withDuration: 0.3, animations: {
controlsVC.blur.effect = nil
controlsVC.image.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
controlsVC.image.alpha = 0
controlsVC.closeButton.alpha = 0
}) { (complete) in
if complete {
controlsVC.view.removeFromSuperview()
}
}
}
//MARK: - Game UI
func addGameUI () {
//Joystick.
if #available(iOS 11.0, *) {
Joystick.shared.frame = CGRect(x: -joystickSize - 20, y: self.gameView.frame.maxY - self.gameView.safeAreaInsets.bottom - joystickSize - 20, width: joystickSize, height: joystickSize)
} else {
// Fallback on earlier versions
Joystick.shared.frame = CGRect(x: -joystickSize - 20, y: self.gameView.frame.maxY - joystickSize - 20, width: joystickSize, height: joystickSize)
}
self.view.addSubview(Joystick.shared)
Joystick.shared.delegate = UserComponent.shared
//Pass / change player button.
SwitchPlayerButton.shared = SwitchPlayerButton(frame: CGRect(x: gameView.frame.maxX + buttonSize + 20 , y: 0, width: buttonSize, height: buttonSize))
SwitchPlayerButton.shared?.center.y = Joystick.shared.center.y
SwitchPlayerButton.shared?.delegate = UserComponent.shared
self.view.addSubview(SwitchPlayerButton.shared!)
//Scoreboard.
let time = TimeInterval(withMinutes: 2, andSeconds: 0)
if #available(iOS 11.0, *) {
Scoreboard.shared = Scoreboard(frame: CGRect(x: -270, y: gameView.frame.minY + gameView.safeAreaInsets.top + 15, width: 250, height: 30), withTotalTime: time)
} else {
// Fallback on earlier versions
Scoreboard.shared = Scoreboard(frame: CGRect(x: -270, y: gameView.frame.minY + 50, width: 250, height: 30), withTotalTime: time)
}
self.view.addSubview(Scoreboard.shared)
//Pan gesture.
self.panGesture = UIPanGestureRecognizer(target: self, action: #selector(self.pan(withGestureRecognizer:)))
self.panGesture.delegate = self
self.gameView.addGestureRecognizer(self.panGesture)
//Pause button.
self.pauseButton = UIButton(frame: CGRect(x: gameView.frame.maxX + (buttonSize * 0.85) + 20, y: Scoreboard.shared.frame.origin.y, width: buttonSize * 0.85, height: 30))
let title = NSAttributedString(string: "PAUSE", attributes: [NSAttributedString.Key.font : UIFont(name: "Rubik", size: 15)!, NSAttributedString.Key.foregroundColor : UIColor.white])
self.pauseButton.setAttributedTitle(title, for: .normal)
self.pauseButton.clipsToBounds = true
self.pauseButton.layer.cornerRadius = 15
self.pauseButton.backgroundColor = UIColor.black.withAlphaComponent(0.9)
self.pauseButton.addTarget(self, action: #selector(self.pauseGame), for: .touchUpInside)
self.view.addSubview(self.pauseButton)
UIView.animate(withDuration: 0.3) {
Joystick.shared.frame.origin.x = 20
Scoreboard.shared.frame.origin.x = 20
SwitchPlayerButton.shared?.frame.origin.x = self.gameView.frame.maxX - buttonSize - 20
self.pauseButton.frame.origin.x = self.gameView.frame.maxX - (buttonSize * 0.85) - 20
}
}
func removeGameUI () {
UIView.animate(withDuration: 0.3, animations: {
Joystick.shared.frame.origin.x = -joystickSize - 20
Scoreboard.shared.frame.origin.x = -270
SwitchPlayerButton.shared?.frame.origin.x = self.gameView.frame.maxX + buttonSize + 20
self.pauseButton.frame.origin.x = self.gameView.frame.maxX + (buttonSize * 0.85) + 20
}) { (completed) in
if completed {
Joystick.shared.removeFromSuperview()
SwitchPlayerButton.shared?.removeFromSuperview()
Scoreboard.shared.removeFromSuperview()
self.pauseButton.removeFromSuperview()
self.gameView.removeGestureRecognizer(self.panGesture)
}
}
}
@objc func pan(withGestureRecognizer recognizer: UIPanGestureRecognizer) {
guard let selectedPlayer = Rink.shared.selectedPlayer else {
return
}
if selectedPlayer.hasPuck {
switch recognizer.state {
case .changed :
let translation = recognizer.translation(in: self.gameView)
let x = translation.x
let y = translation.y
if y < -75 && selectedPlayer.hasPuck {
//Shoot the puck.
let velocity = recognizer.velocity(in: self.gameView)
let shootPoint = CGPoint(x: selectedPlayer.position.x + velocity.x, y: selectedPlayer.position.y - velocity.y)
selectedPlayer.playerComponent?.shootPuck(atPoint: shootPoint)
}
else {
if x > 50 {
//Deke right.
selectedPlayer.playerComponent?.animateDeke(toRight: true)
}
else if x < -50 {
//Deke left.
selectedPlayer.playerComponent?.animateDeke(toRight: false)
}
}
case .ended :
let velocity = recognizer.velocity(in: self.gameView)
let shootPoint = CGPoint(x: selectedPlayer.position.x + velocity.x, y: selectedPlayer.position.y - velocity.y)
if selectedPlayer.hasPuck {
selectedPlayer.playerComponent?.shootPuck(atPoint: shootPoint)
}
default :
break
}
}
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if Joystick.shared.frame.contains(touch.location(in: self.gameView)) {
return false
}
return true
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
//MARK: - Pause, resume, and exit.
@objc func pauseGame() {
//Pause the game.
Rink.shared.pause()
Scoreboard.shared.pauseTimer()
//Show pause menu.
self.presentPauseView()
}
@objc func resumeGame() {
//Resume the game.
Haptics.shared.playPopHaptic()
self.dismissPauseView {
Rink.shared.resume()
Scoreboard.shared.startTimer()
}
}
@objc func exitGame() {
Haptics.shared.sendNotificationHaptic(withType: .warning)
self.dismissPauseView {
Rink.shared.deactivate()
self.removeGameUI()
self.presentHomeView(animated: true)
}
}
//MARK: - Home view controller delegate.
func homeVCDidRespondToPlayButton() {
//Dismiss the home view controller.
Haptics.shared.sendNotificationHaptic(withType: .success)
self.dismissHomeView {
self.addGameUI()
Rink.shared.activate()
}
}
func homeVCDidRespondToControlsButton() {
Haptics.shared.playPeekHaptic()
self.presentControlsView()
}
@objc func gameEnded() {
//Play ending horn.
player = AVPlayer(url: Bundle.main.url(forResource: "gameEnd", withExtension: "wav")!)
player.play()
self.removeGameUI()
self.presentGameOverMenu()
Rink.shared.deactivate()
if Score.shared.userScore > Score.shared.cpuScore {
//User won.
Haptics.shared.sendNotificationHaptic(withType: .success)
}
else if Score.shared.userScore < Score.shared.cpuScore {
//CPU won.
Haptics.shared.sendNotificationHaptic(withType: .warning)
}
else {
//Tie.
Haptics.shared.sendNotificationHaptic(withType: .error)
}
}
}
| 38.695 | 195 | 0.606086 |
5109fc601abaed1bd29d0e3c512db5a371716bca | 686 | swift | Swift | Constrictor/ConstrictorTests/Extensions/NSLayoutAttribute+Finder.swift | NSMyself/Constrictor | 7f8a25c5b68d063f8f5ead908dd816ca9e2a7787 | [
"MIT"
] | null | null | null | Constrictor/ConstrictorTests/Extensions/NSLayoutAttribute+Finder.swift | NSMyself/Constrictor | 7f8a25c5b68d063f8f5ead908dd816ca9e2a7787 | [
"MIT"
] | null | null | null | Constrictor/ConstrictorTests/Extensions/NSLayoutAttribute+Finder.swift | NSMyself/Constrictor | 7f8a25c5b68d063f8f5ead908dd816ca9e2a7787 | [
"MIT"
] | null | null | null | //
// NSLayoutConstraint.Attribute+Finder.swift
// ConstrictorTests
//
// Created by Pedro Carrasco on 23/05/2018.
// Copyright © 2018 Pedro Carrasco. All rights reserved.
//
import UIKit
extension NSLayoutConstraint {
func isFrom(_ attribute: NSLayoutConstraint.Attribute, relatedTo view: UIView?, at index: ConstraintIndex) -> Bool {
return isItem(at: view, from: index, anAttributeFrom: attribute)
}
}
private extension NSLayoutConstraint {
func isItem(at view: UIView?, from index: ConstraintIndex, anAttributeFrom attribute: NSLayoutConstraint.Attribute) -> Bool {
return index.item(from: self) == view && firstAttribute == attribute
}
}
| 26.384615 | 129 | 0.721574 |
59c3ef680f40b23bee348cf82fd533d23a148808 | 1,778 | swift | Swift | MVP/MVP/Utils/TableDataSource.swift | pilot34/ios-architectures | 5cea13899938003214c64e1774266667f61fd1cc | [
"MIT"
] | null | null | null | MVP/MVP/Utils/TableDataSource.swift | pilot34/ios-architectures | 5cea13899938003214c64e1774266667f61fd1cc | [
"MIT"
] | null | null | null | MVP/MVP/Utils/TableDataSource.swift | pilot34/ios-architectures | 5cea13899938003214c64e1774266667f61fd1cc | [
"MIT"
] | null | null | null | //
// TableDataSource.swift
// MVP
//
// Created by Gleb Tarasov on 18/09/2018.
// Copyright © 2018 Gleb Tarasov. All rights reserved.
//
import UIKit
protocol Cell {
associatedtype Data
func update(data: Data)
}
extension Cell {
static var cellIdentifier: String {
return String(describing: self)
}
}
class TableDataSource<CellType, DataType>: NSObject,
UITableViewDelegate,
UITableViewDataSource
where CellType: Cell,
CellType: UITableViewCell,
CellType.Data == DataType {
init(tableView: UITableView, data: [DataType]) {
self.data = data
super.init()
tableView.delegate = self
tableView.dataSource = self
tableView.reloadData()
}
private let data: [DataType]
var didSelect: (DataType) -> Void = { _ in }
// MARK: - UITableViewDataSource & UITableViewDelegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: CellType.cellIdentifier,
for: indexPath) as? CellType else {
fatalError("wrong cell type")
}
cell.update(data: data[indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = data[indexPath.row]
didSelect(item)
}
}
| 29.633333 | 100 | 0.566367 |
3d0311e7781ad53451f3f1f45847b4ac2ee53c70 | 551 | go | Go | instructions/math_instructions/ishl.go | Frederick-S/jvmgo | d1d7e88027adca184aff511ef4ccde0dcb5a6247 | [
"MIT"
] | 1 | 2019-08-04T04:20:42.000Z | 2019-08-04T04:20:42.000Z | instructions/math_instructions/ishl.go | Frederick-S/jvmgo | d1d7e88027adca184aff511ef4ccde0dcb5a6247 | [
"MIT"
] | null | null | null | instructions/math_instructions/ishl.go | Frederick-S/jvmgo | d1d7e88027adca184aff511ef4ccde0dcb5a6247 | [
"MIT"
] | null | null | null | package math_instructions
import (
"github.com/Frederick-S/jvmgo/instructions/base_instructions"
"github.com/Frederick-S/jvmgo/runtime_data_area"
)
// ishl
// Shift left int
type IShl struct {
base_instructions.NoOperandsInstruction
}
func (iShl *IShl) Execute(frame *runtime_data_area.Frame) {
operandStack := frame.GetOperandStack()
integerValue2 := operandStack.PopIntegerValue()
integerValue1 := operandStack.PopIntegerValue()
bitPositions := uint32(integerValue2) & 0x1f
operandStack.PushIntegerValue(integerValue1 << bitPositions)
}
| 25.045455 | 62 | 0.794918 |
f42cb663d2b6fa331667904f5290d5646526d3ca | 377 | go | Go | services.go | equelin/gounity | 4c6f6f9b9b2d9335ef7ecb9e42034b051a83417f | [
"MIT"
] | 4 | 2018-10-23T20:51:45.000Z | 2021-01-14T14:37:32.000Z | services.go | equelin/gounity | 4c6f6f9b9b2d9335ef7ecb9e42034b051a83417f | [
"MIT"
] | null | null | null | services.go | equelin/gounity | 4c6f6f9b9b2d9335ef7ecb9e42034b051a83417f | [
"MIT"
] | 5 | 2018-04-06T14:08:07.000Z | 2022-02-03T08:01:09.000Z | package gounity
import types "github.com/equelin/gounity/types/v1"
//GetDNSServer purpose is to get the DNS configuration of the Unity array.
func (session *Session) GetDNSServer() (resp *types.DNSServer, err error) {
fields := "id,domain,origin,addresses"
err = session.Request("GET", "/api/types/dnsServer/instances", fields, "", false, nil, &resp)
return resp, err
}
| 29 | 94 | 0.734748 |
4f18e8c8fb7bd4f9ed7bd065197d2507323db39a | 317 | swift | Swift | OnlySwitch/View/Setting/Radio/RadioSettingModel.swift | Mu-L/OnlySwitch | 6aedec5d665d54e4af551631b6f2ffd0528eec65 | [
"MIT"
] | null | null | null | OnlySwitch/View/Setting/Radio/RadioSettingModel.swift | Mu-L/OnlySwitch | 6aedec5d665d54e4af551631b6f2ffd0528eec65 | [
"MIT"
] | null | null | null | OnlySwitch/View/Setting/Radio/RadioSettingModel.swift | Mu-L/OnlySwitch | 6aedec5d665d54e4af551631b6f2ffd0528eec65 | [
"MIT"
] | null | null | null | //
// RadioSettingModel.swift
// OnlySwitch
//
// Created by Jacklandrin on 2022/6/8.
//
import Foundation
struct RadioSettingModel {
var radioList:[RadioPlayerItem] = [RadioPlayerItem]()
var selectRow:RadioPlayerItem.ID?
var showErrorToast = false
var errorInfo = ""
var currentTitle = ""
}
| 18.647059 | 57 | 0.690852 |
e512bdc28fd47eb6b83ffaa64850fabf88de9846 | 44,716 | html | HTML | doc/yahoofinance/YahooFinance.html | fthuin/FinanceFromYahoo | 80b3b7dea2e11eb3fd2b1db745cca0e24b027d94 | [
"MIT"
] | null | null | null | doc/yahoofinance/YahooFinance.html | fthuin/FinanceFromYahoo | 80b3b7dea2e11eb3fd2b1db745cca0e24b027d94 | [
"MIT"
] | null | null | null | doc/yahoofinance/YahooFinance.html | fthuin/FinanceFromYahoo | 80b3b7dea2e11eb3fd2b1db745cca0e24b027d94 | [
"MIT"
] | null | null | null | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="fr">
<head>
<!-- Generated by javadoc (version 1.7.0_79) on Fri Jul 10 15:44:48 CEST 2015 -->
<title>YahooFinance</title>
<meta name="date" content="2015-07-10">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="YahooFinance";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-all.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../yahoofinance/Utils.html" title="class in yahoofinance"><span class="strong">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../index.html?yahoofinance/YahooFinance.html" target="_top">Frames</a></li>
<li><a href="YahooFinance.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">yahoofinance</div>
<h2 title="Class YahooFinance" class="title">Class YahooFinance</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>yahoofinance.YahooFinance</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="strong">YahooFinance</span>
extends java.lang.Object</pre>
<div class="block">YahooFinance can be used to retrieve quotes and some extra information on stocks.
There is also the possibility to include historical quotes on the requested stocks.
<p>
When trying to get information on multiple stocks at once, please use the provided
methods that accept a <code>String[]</code> of symbols to get the best performance.
To retrieve the basic quote, statistics and dividend data, a single request can be sent to
Yahoo Finance for multiple stocks at once.
For the historical data however, a separate request has to be sent to Yahoo Finance
for each of the requested stocks. The provided methods will retrieve
all of the required information in the least amount of
requests possible towards Yahoo Finance.
<p>
Please be aware that the data received from Yahoo Finance is not always
complete for every single stock. Stocks on the American stock exchanges
usually have a lot more data available than stocks on other exchanges.
<p>
This API can also be used to send requests for retrieving FX rates.
<p>
Since the data is provided by Yahoo, please check their Terms of Service
at https://info.yahoo.com/legal/us/yahoo/</div>
<dl><dt><span class="strong">Version:</span></dt>
<dd>%I%, %G%</dd>
<dt><span class="strong">Author:</span></dt>
<dd>Stijn Strickx</dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../yahoofinance/YahooFinance.html#HISTQUOTES_BASE_URL">HISTQUOTES_BASE_URL</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static java.util.logging.Logger</code></td>
<td class="colLast"><code><strong><a href="../yahoofinance/YahooFinance.html#logger">logger</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../yahoofinance/YahooFinance.html#QUOTES_BASE_URL">QUOTES_BASE_URL</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../yahoofinance/YahooFinance.html#QUOTES_CSV_DELIMITER">QUOTES_CSV_DELIMITER</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../yahoofinance/YahooFinance.html#TIMEZONE">TIMEZONE</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../yahoofinance/YahooFinance.html#YahooFinance()">YahooFinance</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a></code></td>
<td class="colLast"><code><strong><a href="../yahoofinance/YahooFinance.html#get(java.lang.String)">get</a></strong>(java.lang.String symbol)</code>
<div class="block">Sends a basic quotes request to Yahoo Finance.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static java.util.Map<java.lang.String,<a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a>></code></td>
<td class="colLast"><code><strong><a href="../yahoofinance/YahooFinance.html#get(java.lang.String[])">get</a></strong>(java.lang.String[] symbols)</code>
<div class="block">Sends a basic quotes request to Yahoo Finance.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.util.Map<java.lang.String,<a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a>></code></td>
<td class="colLast"><code><strong><a href="../yahoofinance/YahooFinance.html#get(java.lang.String[],%20boolean)">get</a></strong>(java.lang.String[] symbols,
boolean includeHistorical)</code>
<div class="block">Same as the <code>get(String[])</code> method, but with the option to include
historical stock quote data.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static java.util.Map<java.lang.String,<a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a>></code></td>
<td class="colLast"><code><strong><a href="../yahoofinance/YahooFinance.html#get(java.lang.String[],%20java.util.Calendar)">get</a></strong>(java.lang.String[] symbols,
java.util.Calendar from)</code>
<div class="block">Sends a request for multiple stocks with the historical quotes included
starting from the specified <code>Calendar</code> date until today,
at the default interval (monthly).</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.util.Map<java.lang.String,<a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a>></code></td>
<td class="colLast"><code><strong><a href="../yahoofinance/YahooFinance.html#get(java.lang.String[],%20java.util.Calendar,%20java.util.Calendar)">get</a></strong>(java.lang.String[] symbols,
java.util.Calendar from,
java.util.Calendar to)</code>
<div class="block">Sends a request for multiple stocks with the historical quotes included
starting from the specified <code>Calendar</code> date
until the specified Calendar date (to)
at the default interval (monthly).</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static java.util.Map<java.lang.String,<a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a>></code></td>
<td class="colLast"><code><strong><a href="../yahoofinance/YahooFinance.html#get(java.lang.String[],%20java.util.Calendar,%20java.util.Calendar,%20yahoofinance.histquotes.Interval)">get</a></strong>(java.lang.String[] symbols,
java.util.Calendar from,
java.util.Calendar to,
<a href="../yahoofinance/histquotes/Interval.html" title="enum in yahoofinance.histquotes">Interval</a> interval)</code>
<div class="block">Sends a request for multiple stocks with the historical quotes included
starting from the specified <code>Calendar</code> date
until the specified Calendar date (to)
at the specified interval.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.util.Map<java.lang.String,<a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a>></code></td>
<td class="colLast"><code><strong><a href="../yahoofinance/YahooFinance.html#get(java.lang.String[],%20java.util.Calendar,%20yahoofinance.histquotes.Interval)">get</a></strong>(java.lang.String[] symbols,
java.util.Calendar from,
<a href="../yahoofinance/histquotes/Interval.html" title="enum in yahoofinance.histquotes">Interval</a> interval)</code>
<div class="block">Sends a request for multiple stocks with the historical quotes included
starting from the specified <code>Calendar</code> date until today,
at the specified interval.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static java.util.Map<java.lang.String,<a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a>></code></td>
<td class="colLast"><code><strong><a href="../yahoofinance/YahooFinance.html#get(java.lang.String[],%20yahoofinance.histquotes.Interval)">get</a></strong>(java.lang.String[] symbols,
<a href="../yahoofinance/histquotes/Interval.html" title="enum in yahoofinance.histquotes">Interval</a> interval)</code>
<div class="block">Sends a request for multiple stocks with the historical quotes included
from the past year,
at the specified interval.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a></code></td>
<td class="colLast"><code><strong><a href="../yahoofinance/YahooFinance.html#get(java.lang.String,%20boolean)">get</a></strong>(java.lang.String symbol,
boolean includeHistorical)</code>
<div class="block">Same as the <code>get(String)</code> method, but with the option to include
historical stock quote data.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a></code></td>
<td class="colLast"><code><strong><a href="../yahoofinance/YahooFinance.html#get(java.lang.String,%20java.util.Calendar)">get</a></strong>(java.lang.String symbol,
java.util.Calendar from)</code>
<div class="block">Sends a request with the historical quotes included
starting from the specified <code>Calendar</code> date
at the default interval (monthly).</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a></code></td>
<td class="colLast"><code><strong><a href="../yahoofinance/YahooFinance.html#get(java.lang.String,%20java.util.Calendar,%20java.util.Calendar)">get</a></strong>(java.lang.String symbol,
java.util.Calendar from,
java.util.Calendar to)</code>
<div class="block">Sends a request with the historical quotes included
starting from the specified <code>Calendar</code> date
until the specified Calendar date (to)
at the default interval (monthly).</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a></code></td>
<td class="colLast"><code><strong><a href="../yahoofinance/YahooFinance.html#get(java.lang.String,%20java.util.Calendar,%20java.util.Calendar,%20yahoofinance.histquotes.Interval)">get</a></strong>(java.lang.String symbol,
java.util.Calendar from,
java.util.Calendar to,
<a href="../yahoofinance/histquotes/Interval.html" title="enum in yahoofinance.histquotes">Interval</a> interval)</code>
<div class="block">Sends a request with the historical quotes included
starting from the specified <code>Calendar</code> date
until the specified Calendar date (to)
at the specified interval.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a></code></td>
<td class="colLast"><code><strong><a href="../yahoofinance/YahooFinance.html#get(java.lang.String,%20java.util.Calendar,%20yahoofinance.histquotes.Interval)">get</a></strong>(java.lang.String symbol,
java.util.Calendar from,
<a href="../yahoofinance/histquotes/Interval.html" title="enum in yahoofinance.histquotes">Interval</a> interval)</code>
<div class="block">Sends a request with the historical quotes included
starting from the specified <code>Calendar</code> date
at the specified interval.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a></code></td>
<td class="colLast"><code><strong><a href="../yahoofinance/YahooFinance.html#get(java.lang.String,%20yahoofinance.histquotes.Interval)">get</a></strong>(java.lang.String symbol,
<a href="../yahoofinance/histquotes/Interval.html" title="enum in yahoofinance.histquotes">Interval</a> interval)</code>
<div class="block">Sends a request with the historical quotes included
at the specified interval (DAILY, WEEKLY, MONTHLY).</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../yahoofinance/quotes/fx/FxQuote.html" title="class in yahoofinance.quotes.fx">FxQuote</a></code></td>
<td class="colLast"><code><strong><a href="../yahoofinance/YahooFinance.html#getFx(java.lang.String)">getFx</a></strong>(java.lang.String symbol)</code>
<div class="block">Sends a request for a single FX rate.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static java.util.Map<java.lang.String,<a href="../yahoofinance/quotes/fx/FxQuote.html" title="class in yahoofinance.quotes.fx">FxQuote</a>></code></td>
<td class="colLast"><code><strong><a href="../yahoofinance/YahooFinance.html#getFx(java.lang.String[])">getFx</a></strong>(java.lang.String[] symbols)</code>
<div class="block">Sends a single request to Yahoo Finance to retrieve a quote
for all the requested FX symbols.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="QUOTES_BASE_URL">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>QUOTES_BASE_URL</h4>
<pre>public static final java.lang.String QUOTES_BASE_URL</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../constant-values.html#yahoofinance.YahooFinance.QUOTES_BASE_URL">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="HISTQUOTES_BASE_URL">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>HISTQUOTES_BASE_URL</h4>
<pre>public static final java.lang.String HISTQUOTES_BASE_URL</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../constant-values.html#yahoofinance.YahooFinance.HISTQUOTES_BASE_URL">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="QUOTES_CSV_DELIMITER">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>QUOTES_CSV_DELIMITER</h4>
<pre>public static final java.lang.String QUOTES_CSV_DELIMITER</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../constant-values.html#yahoofinance.YahooFinance.QUOTES_CSV_DELIMITER">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="TIMEZONE">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>TIMEZONE</h4>
<pre>public static final java.lang.String TIMEZONE</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../constant-values.html#yahoofinance.YahooFinance.TIMEZONE">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="logger">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>logger</h4>
<pre>public static final java.util.logging.Logger logger</pre>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="YahooFinance()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>YahooFinance</h4>
<pre>public YahooFinance()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="get(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>get</h4>
<pre>public static <a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a> get(java.lang.String symbol)
throws java.io.IOException</pre>
<div class="block">Sends a basic quotes request to Yahoo Finance. This will return a <a href="../yahoofinance/Stock.html" title="class in yahoofinance"><code>Stock</code></a> object
with its <a href="../yahoofinance/quotes/stock/StockQuote.html" title="class in yahoofinance.quotes.stock"><code>StockQuote</code></a>, <a href="../yahoofinance/quotes/stock/StockStats.html" title="class in yahoofinance.quotes.stock"><code>StockStats</code></a>
and <a href="../yahoofinance/quotes/stock/StockDividend.html" title="class in yahoofinance.quotes.stock"><code>StockDividend</code></a> member fields
filled in with the available data.
Returns null if the data can't be retrieved from Yahoo Finance.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>symbol</code> - the symbol of the stock for which you want to retrieve information</dd>
<dt><span class="strong">Returns:</span></dt><dd>a <a href="../yahoofinance/Stock.html" title="class in yahoofinance"><code>Stock</code></a> object containing the requested information</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.io.IOException</code> - when there's a connection problem</dd></dl>
</li>
</ul>
<a name="get(java.lang.String, boolean)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>get</h4>
<pre>public static <a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a> get(java.lang.String symbol,
boolean includeHistorical)
throws java.io.IOException</pre>
<div class="block">Same as the <code>get(String)</code> method, but with the option to include
historical stock quote data. Including historical data will cause the <a href="../yahoofinance/Stock.html" title="class in yahoofinance"><code>Stock</code></a>
object's member field <a href="../yahoofinance/histquotes/HistoricalQuote.html" title="class in yahoofinance.histquotes"><code>HistoricalQuote</code></a> to be filled in
with the default past year term at monthly intervals.
Returns null if the data can't be retrieved from Yahoo Finance.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>symbol</code> - the symbol of the stock for which you want to retrieve information</dd><dd><code>includeHistorical</code> - indicates if the historical quotes should be included.</dd>
<dt><span class="strong">Returns:</span></dt><dd>a <a href="../yahoofinance/Stock.html" title="class in yahoofinance"><code>Stock</code></a> object containing the requested information</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.io.IOException</code> - when there's a connection problem</dd></dl>
</li>
</ul>
<a name="get(java.lang.String, yahoofinance.histquotes.Interval)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>get</h4>
<pre>public static <a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a> get(java.lang.String symbol,
<a href="../yahoofinance/histquotes/Interval.html" title="enum in yahoofinance.histquotes">Interval</a> interval)
throws java.io.IOException</pre>
<div class="block">Sends a request with the historical quotes included
at the specified interval (DAILY, WEEKLY, MONTHLY).
Returns null if the data can't be retrieved from Yahoo Finance.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>symbol</code> - the symbol of the stock for which you want to retrieve information</dd><dd><code>interval</code> - the interval of the included historical data</dd>
<dt><span class="strong">Returns:</span></dt><dd>a <a href="../yahoofinance/Stock.html" title="class in yahoofinance"><code>Stock</code></a> object containing the requested information</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.io.IOException</code> - when there's a connection problem</dd></dl>
</li>
</ul>
<a name="get(java.lang.String, java.util.Calendar)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>get</h4>
<pre>public static <a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a> get(java.lang.String symbol,
java.util.Calendar from)
throws java.io.IOException</pre>
<div class="block">Sends a request with the historical quotes included
starting from the specified <code>Calendar</code> date
at the default interval (monthly).
Returns null if the data can't be retrieved from Yahoo Finance.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>symbol</code> - the symbol of the stock for which you want to retrieve information</dd><dd><code>from</code> - start date of the historical data</dd>
<dt><span class="strong">Returns:</span></dt><dd>a <a href="../yahoofinance/Stock.html" title="class in yahoofinance"><code>Stock</code></a> object containing the requested information</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.io.IOException</code> - when there's a connection problem</dd></dl>
</li>
</ul>
<a name="get(java.lang.String, java.util.Calendar, yahoofinance.histquotes.Interval)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>get</h4>
<pre>public static <a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a> get(java.lang.String symbol,
java.util.Calendar from,
<a href="../yahoofinance/histquotes/Interval.html" title="enum in yahoofinance.histquotes">Interval</a> interval)
throws java.io.IOException</pre>
<div class="block">Sends a request with the historical quotes included
starting from the specified <code>Calendar</code> date
at the specified interval.
Returns null if the data can't be retrieved from Yahoo Finance.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>symbol</code> - the symbol of the stock for which you want to retrieve information</dd><dd><code>from</code> - start date of the historical data</dd><dd><code>interval</code> - the interval of the included historical data</dd>
<dt><span class="strong">Returns:</span></dt><dd>a <a href="../yahoofinance/Stock.html" title="class in yahoofinance"><code>Stock</code></a> object containing the requested information</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.io.IOException</code> - when there's a connection problem</dd></dl>
</li>
</ul>
<a name="get(java.lang.String, java.util.Calendar, java.util.Calendar)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>get</h4>
<pre>public static <a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a> get(java.lang.String symbol,
java.util.Calendar from,
java.util.Calendar to)
throws java.io.IOException</pre>
<div class="block">Sends a request with the historical quotes included
starting from the specified <code>Calendar</code> date
until the specified Calendar date (to)
at the default interval (monthly).
Returns null if the data can't be retrieved from Yahoo Finance.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>symbol</code> - the symbol of the stock for which you want to retrieve information</dd><dd><code>from</code> - start date of the historical data</dd><dd><code>to</code> - end date of the historical data</dd>
<dt><span class="strong">Returns:</span></dt><dd>a <a href="../yahoofinance/Stock.html" title="class in yahoofinance"><code>Stock</code></a> object containing the requested information</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.io.IOException</code> - when there's a connection problem</dd></dl>
</li>
</ul>
<a name="get(java.lang.String, java.util.Calendar, java.util.Calendar, yahoofinance.histquotes.Interval)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>get</h4>
<pre>public static <a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a> get(java.lang.String symbol,
java.util.Calendar from,
java.util.Calendar to,
<a href="../yahoofinance/histquotes/Interval.html" title="enum in yahoofinance.histquotes">Interval</a> interval)
throws java.io.IOException</pre>
<div class="block">Sends a request with the historical quotes included
starting from the specified <code>Calendar</code> date
until the specified Calendar date (to)
at the specified interval.
Returns null if the data can't be retrieved from Yahoo Finance.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>symbol</code> - the symbol of the stock for which you want to retrieve information</dd><dd><code>from</code> - start date of the historical data</dd><dd><code>to</code> - end date of the historical data</dd><dd><code>interval</code> - the interval of the included historical data</dd>
<dt><span class="strong">Returns:</span></dt><dd>a <a href="../yahoofinance/Stock.html" title="class in yahoofinance"><code>Stock</code></a> object containing the requested information</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.io.IOException</code> - when there's a connection problem</dd></dl>
</li>
</ul>
<a name="get(java.lang.String[])">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>get</h4>
<pre>public static java.util.Map<java.lang.String,<a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a>> get(java.lang.String[] symbols)
throws java.io.IOException</pre>
<div class="block">Sends a basic quotes request to Yahoo Finance. This will return a <code>Map</code> object
that links the symbols to their respective <a href="../yahoofinance/Stock.html" title="class in yahoofinance"><code>Stock</code></a> objects.
The Stock objects have their <a href="../yahoofinance/quotes/stock/StockQuote.html" title="class in yahoofinance.quotes.stock"><code>StockQuote</code></a>, <a href="../yahoofinance/quotes/stock/StockStats.html" title="class in yahoofinance.quotes.stock"><code>StockStats</code></a>
and <a href="../yahoofinance/quotes/stock/StockDividend.html" title="class in yahoofinance.quotes.stock"><code>StockDividend</code></a> member fields
filled in with the available data.
<p>
All the information is retrieved in a single request to Yahoo Finance.
The returned Map only includes the Stocks that could
successfully be retrieved from Yahoo Finance.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>symbols</code> - the symbols of the stocks for which you want to retrieve information</dd>
<dt><span class="strong">Returns:</span></dt><dd>a Map that links the symbols to their respective Stock objects</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.io.IOException</code> - when there's a connection problem</dd></dl>
</li>
</ul>
<a name="get(java.lang.String[], boolean)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>get</h4>
<pre>public static java.util.Map<java.lang.String,<a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a>> get(java.lang.String[] symbols,
boolean includeHistorical)
throws java.io.IOException</pre>
<div class="block">Same as the <code>get(String[])</code> method, but with the option to include
historical stock quote data. Including historical data will cause the <a href="../yahoofinance/Stock.html" title="class in yahoofinance"><code>Stock</code></a>
objects their member field <a href="../yahoofinance/histquotes/HistoricalQuote.html" title="class in yahoofinance.histquotes"><code>HistoricalQuote</code></a> to be filled in
with the default past year term at monthly intervals.
<p>
The latest quotes will be retrieved in a single request to Yahoo Finance.
For the historical quotes (if includeHistorical),
a separate request will be sent for each requested stock.
The returned Map only includes the Stocks that could
successfully be retrieved from Yahoo Finance.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>symbols</code> - the symbols of the stocks for which you want to retrieve information</dd><dd><code>includeHistorical</code> - indicates if the historical quotes should be included</dd>
<dt><span class="strong">Returns:</span></dt><dd>a Map that links the symbols to their respective Stock objects</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.io.IOException</code> - when there's a connection problem</dd></dl>
</li>
</ul>
<a name="get(java.lang.String[], yahoofinance.histquotes.Interval)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>get</h4>
<pre>public static java.util.Map<java.lang.String,<a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a>> get(java.lang.String[] symbols,
<a href="../yahoofinance/histquotes/Interval.html" title="enum in yahoofinance.histquotes">Interval</a> interval)
throws java.io.IOException</pre>
<div class="block">Sends a request for multiple stocks with the historical quotes included
from the past year,
at the specified interval. (DAILY, WEEKLY, MONTHLY)
<p>
The latest quotes will be retrieved in a single request to Yahoo Finance.
For the historical quotes, a separate request will be sent for each requested stock.
The returned Map only includes the Stocks that could
successfully be retrieved from Yahoo Finance.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>symbols</code> - the symbols of the stocks for which you want to retrieve information</dd><dd><code>interval</code> - the interval of the included historical data</dd>
<dt><span class="strong">Returns:</span></dt><dd>a Map that links the symbols to their respective Stock objects.</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.io.IOException</code> - when there's a connection problem</dd></dl>
</li>
</ul>
<a name="get(java.lang.String[], java.util.Calendar)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>get</h4>
<pre>public static java.util.Map<java.lang.String,<a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a>> get(java.lang.String[] symbols,
java.util.Calendar from)
throws java.io.IOException</pre>
<div class="block">Sends a request for multiple stocks with the historical quotes included
starting from the specified <code>Calendar</code> date until today,
at the default interval (monthly).
<p>
The latest quotes will be retrieved in a single request to Yahoo Finance.
For the historical quotes, a separate request will be sent for each requested stock.
The returned Map only includes the Stocks that could
successfully be retrieved from Yahoo Finance.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>symbols</code> - the symbols of the stocks for which you want to retrieve information</dd><dd><code>from</code> - start date of the historical data</dd>
<dt><span class="strong">Returns:</span></dt><dd>a Map that links the symbols to their respective Stock objects.</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.io.IOException</code> - when there's a connection problem</dd></dl>
</li>
</ul>
<a name="get(java.lang.String[], java.util.Calendar, yahoofinance.histquotes.Interval)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>get</h4>
<pre>public static java.util.Map<java.lang.String,<a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a>> get(java.lang.String[] symbols,
java.util.Calendar from,
<a href="../yahoofinance/histquotes/Interval.html" title="enum in yahoofinance.histquotes">Interval</a> interval)
throws java.io.IOException</pre>
<div class="block">Sends a request for multiple stocks with the historical quotes included
starting from the specified <code>Calendar</code> date until today,
at the specified interval.
<p>
The latest quotes will be retrieved in a single request to Yahoo Finance.
For the historical quotes, a separate request will be sent for each requested stock.
The returned Map only includes the Stocks that could
successfully be retrieved from Yahoo Finance.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>symbols</code> - the symbols of the stocks for which you want to retrieve information</dd><dd><code>from</code> - start date of the historical data</dd><dd><code>interval</code> - the interval of the included historical data</dd>
<dt><span class="strong">Returns:</span></dt><dd>a Map that links the symbols to their respective Stock objects.</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.io.IOException</code> - when there's a connection problem</dd></dl>
</li>
</ul>
<a name="get(java.lang.String[], java.util.Calendar, java.util.Calendar)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>get</h4>
<pre>public static java.util.Map<java.lang.String,<a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a>> get(java.lang.String[] symbols,
java.util.Calendar from,
java.util.Calendar to)
throws java.io.IOException</pre>
<div class="block">Sends a request for multiple stocks with the historical quotes included
starting from the specified <code>Calendar</code> date
until the specified Calendar date (to)
at the default interval (monthly).
<p>
The latest quotes will be retrieved in a single request to Yahoo Finance.
For the historical quotes, a separate request will be sent for each requested stock.
The returned Map only includes the Stocks that could
successfully be retrieved from Yahoo Finance.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>symbols</code> - the symbols of the stocks for which you want to retrieve information</dd><dd><code>from</code> - start date of the historical data</dd><dd><code>to</code> - end date of the historical data</dd>
<dt><span class="strong">Returns:</span></dt><dd>a Map that links the symbols to their respective Stock objects.</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.io.IOException</code> - when there's a connection problem</dd></dl>
</li>
</ul>
<a name="get(java.lang.String[], java.util.Calendar, java.util.Calendar, yahoofinance.histquotes.Interval)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>get</h4>
<pre>public static java.util.Map<java.lang.String,<a href="../yahoofinance/Stock.html" title="class in yahoofinance">Stock</a>> get(java.lang.String[] symbols,
java.util.Calendar from,
java.util.Calendar to,
<a href="../yahoofinance/histquotes/Interval.html" title="enum in yahoofinance.histquotes">Interval</a> interval)
throws java.io.IOException</pre>
<div class="block">Sends a request for multiple stocks with the historical quotes included
starting from the specified <code>Calendar</code> date
until the specified Calendar date (to)
at the specified interval.
<p>
The latest quotes will be retrieved in a single request to Yahoo Finance.
For the historical quotes, a separate request will be sent for each requested stock.
The returned Map only includes the Stocks that could
successfully be retrieved from Yahoo Finance.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>symbols</code> - the symbols of the stocks for which you want to retrieve information</dd><dd><code>from</code> - start date of the historical data</dd><dd><code>to</code> - end date of the historical data</dd><dd><code>interval</code> - the interval of the included historical data</dd>
<dt><span class="strong">Returns:</span></dt><dd>a Map that links the symbols to their respective Stock objects.</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.io.IOException</code> - when there's a connection problem</dd></dl>
</li>
</ul>
<a name="getFx(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getFx</h4>
<pre>public static <a href="../yahoofinance/quotes/fx/FxQuote.html" title="class in yahoofinance.quotes.fx">FxQuote</a> getFx(java.lang.String symbol)
throws java.io.IOException</pre>
<div class="block">Sends a request for a single FX rate.
Some common symbols can easily be found in the ENUM <a href="../yahoofinance/quotes/fx/FxSymbols.html" title="class in yahoofinance.quotes.fx"><code>FxSymbols</code></a>
Some examples of accepted symbols:
<ul>
<li> EURUSD=X
<li> USDEUR=X
<li> USDGBP=X
<li> AUDGBP=X
<li> CADUSD=X
</ul></div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>symbol</code> - symbol for the FX rate you want to request</dd>
<dt><span class="strong">Returns:</span></dt><dd>a quote for the requested FX rate</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.io.IOException</code> - when there's a connection problem</dd></dl>
</li>
</ul>
<a name="getFx(java.lang.String[])">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getFx</h4>
<pre>public static java.util.Map<java.lang.String,<a href="../yahoofinance/quotes/fx/FxQuote.html" title="class in yahoofinance.quotes.fx">FxQuote</a>> getFx(java.lang.String[] symbols)
throws java.io.IOException</pre>
<div class="block">Sends a single request to Yahoo Finance to retrieve a quote
for all the requested FX symbols.
See <code>getFx(String)</code> for more information on the
accepted FX symbols.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>symbols</code> - an array of FX symbols</dd>
<dt><span class="strong">Returns:</span></dt><dd>the requested FX symbols mapped to their respective quotes</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.io.IOException</code> - when there's a connection problem or the request is incorrect</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../yahoofinance/YahooFinance.html#getFx(java.lang.String)"><code>getFx(java.lang.String)</code></a></dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-all.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../yahoofinance/Utils.html" title="class in yahoofinance"><span class="strong">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../index.html?yahoofinance/YahooFinance.html" target="_top">Frames</a></li>
<li><a href="YahooFinance.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| 52.607059 | 349 | 0.697133 |
74cdd10b763f14e553fb6c8ab64a13d4519a96ec | 5,542 | rs | Rust | src/game.rs | reniowood/tui-2048 | 0a28d94ad9611f80c66f79daa28c1c4546e0503a | [
"MIT"
] | null | null | null | src/game.rs | reniowood/tui-2048 | 0a28d94ad9611f80c66f79daa28c1c4546e0503a | [
"MIT"
] | null | null | null | src/game.rs | reniowood/tui-2048 | 0a28d94ad9611f80c66f79daa28c1c4546e0503a | [
"MIT"
] | null | null | null | use crate::block::block;
use crate::board::Board;
pub struct Game {
goal: u32,
pub board: Board,
pub width: usize,
pub height: usize,
pub score: u32,
}
impl Game {
pub fn new(goal: u32, width: usize, height: usize) -> Game {
let mut board = Board::new(width, height);
board = Game::put_new_block(board);
board = Game::put_new_block(board);
Game {
goal: goal,
board: board,
width: width,
height: height,
score: 0,
}
}
fn put_new_block(board: Board) -> Board {
if let Some((row, col)) = board.pick_empty_index() {
let block = block::random();
board.put_new_block(row, col, block)
} else {
board
}
}
pub fn win(&self) -> bool {
self.board.has_block_with(self.goal)
}
pub fn lose(&self) -> bool {
!self.win() && !self.board.has_empty_block()
}
pub fn move_up(&mut self) {
let board = self.board.try_to_move_up();
if board.updated {
self.board = Game::put_new_block(board);
}
}
pub fn move_down(&mut self) {
let board = self.board.try_to_move_down();
if board.updated {
self.board = Game::put_new_block(board);
}
}
pub fn move_left(&mut self) {
let board = self.board.try_to_move_left();
if board.updated {
self.board = Game::put_new_block(board);
}
}
pub fn move_right(&mut self) {
let board = self.board.try_to_move_right();
if board.updated {
self.board = Game::put_new_block(board);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_new() {
let width = 4;
let height = 4;
let goal = 32;
let game = Game::new(goal, width, height);
assert_eq!(goal, game.goal);
assert_eq!(width, game.width);
assert_eq!(height, game.height);
assert_eq!(0, game.score);
let mut num_blocks = 0;
for i in 0..height {
for j in 0..width {
if game.board.blocks[i][j] > 0 {
num_blocks += 1;
}
}
}
assert_eq!(2, num_blocks);
}
#[test]
fn test_win_when_there_is_block_with_goal_value() {
let width = 4;
let height = 4;
let goal = 32;
let blocks = vec![
vec![0, 4, 0, 32],
vec![0, 2, 4, 0],
vec![0, 0, 2, 0],
vec![0, 0, 0, 0],
];
let board = Board {
width: width,
height: height,
blocks: blocks,
updated: false
};
let game = Game {
goal: goal,
board: board,
width: width,
height: height,
score: 0
};
assert!(game.win());
}
#[test]
fn test_win_when_there_is_no_block_with_goal_value() {
let width = 4;
let height = 4;
let goal = 32;
let blocks = vec![
vec![0, 4, 0, 31],
vec![0, 2, 4, 0],
vec![0, 0, 2, 0],
vec![0, 0, 0, 0],
];
let board = Board {
width: width,
height: height,
blocks: blocks,
updated: false
};
let game = Game {
goal: goal,
board: board,
width: width,
height: height,
score: 0
};
assert!(!game.win());
}
#[test]
fn test_lose_when_board_is_full() {
let width = 4;
let height = 4;
let goal = 32;
let blocks = vec![
vec![2, 4, 8, 31],
vec![4, 2, 4, 2],
vec![8, 4, 2, 4],
vec![2, 8, 4, 2],
];
let board = Board {
width: width,
height: height,
blocks: blocks,
updated: false
};
let game = Game {
goal: goal,
board: board,
width: width,
height: height,
score: 0
};
assert!(game.lose());
}
#[test]
fn test_lose_when_board_has_empty_block() {
let width = 4;
let height = 4;
let goal = 32;
let blocks = vec![
vec![0, 4, 2, 31],
vec![4, 2, 4, 2],
vec![2, 4, 2, 4],
vec![4, 2, 4, 2],
];
let board = Board {
width: width,
height: height,
blocks: blocks,
updated: false
};
let game = Game {
goal: goal,
board: board,
width: width,
height: height,
score: 0
};
assert!(!game.lose());
}
#[test]
fn test_lose_when_board_is_full_but_has_goal_value() {
let width = 4;
let height = 4;
let goal = 32;
let blocks = vec![
vec![32, 4, 2, 31],
vec![4, 2, 4, 2],
vec![2, 4, 2, 4],
vec![4, 2, 4, 2],
];
let board = Board {
width: width,
height: height,
blocks: blocks,
updated: false
};
let game = Game {
goal: goal,
board: board,
width: width,
height: height,
score: 0
};
assert!(!game.lose());
}
} | 22.437247 | 64 | 0.433418 |
5f39789b325ea7156b409fafdf4e9857501b806c | 4,226 | ts | TypeScript | src/utils/context.ts | Ingenico-ePayments/connect-sdk-jss2s | fa9a616e6ffa7c661117a6dd875d180e9e540ead | [
"CC0-1.0"
] | 12 | 2016-07-11T17:44:03.000Z | 2021-12-26T15:25:03.000Z | src/utils/context.ts | Ingenico-ePayments/connect-sdk-jss2s | fa9a616e6ffa7c661117a6dd875d180e9e540ead | [
"CC0-1.0"
] | 6 | 2016-10-12T21:33:25.000Z | 2020-05-18T12:25:24.000Z | src/utils/context.ts | Ingenico-ePayments/connect-sdk-jss2s | fa9a616e6ffa7c661117a6dd875d180e9e540ead | [
"CC0-1.0"
] | 9 | 2016-09-17T07:15:10.000Z | 2020-01-24T16:05:07.000Z | import crypto = require("crypto");
import _ = require("lodash");
import { Context, Header, Logger, SdkContext } from "../model";
import { ShoppingCartExtension } from "../model/domain/metadata";
/**
* @param {Array} gcsHeaders Collection of headers that need to be sorted; only headers that start with X-GCS will be returned
*/
function getSortedHeadersForContext(gcsHeaders: Header[]): string {
let headers = "";
if (gcsHeaders) {
let sortedXGCSHeaders: Header[] = [];
_.forEach(gcsHeaders, header => {
if (header.key.toUpperCase().indexOf("X-GCS") === 0) {
// add this header
sortedXGCSHeaders.push(header);
}
});
sortedXGCSHeaders = sortedXGCSHeaders.sort((a, b) => {
a.key = a.key.toUpperCase();
b.key = b.key.toUpperCase();
if (a.key < b.key) {
return -1;
} else if (a.key > b.key) {
return 1;
} else {
return 0;
}
});
_.forEach(sortedXGCSHeaders, header => {
headers += header.key.toLowerCase() + ":" + header.value + "\n";
});
}
return headers;
}
class SdkContextImpl implements SdkContext {
private context?: Context;
private logger?: Logger;
private enableLogging?: boolean;
private idempotenceRequestTimestamp?: string | number;
private integrator?: string;
private shoppingCartExtension?: ShoppingCartExtension;
private notSetError<T>(name: string): T {
throw new Error(name + " has not been set");
}
setContext(context: Context): void {
this.context = context;
}
getContext(): Context {
return this.context || this.notSetError("context");
}
getSignature(method: string, contentType: string, date: string, gcsHeaders: Header[], path: string): string {
const headers = getSortedHeadersForContext(gcsHeaders);
return crypto
.createHmac("SHA256", this.getContext().secretApiKey)
.update(method + "\n" + contentType + "\n" + date + "\n" + headers + path + "\n")
.digest("base64");
}
setLogger(logger: Logger): void {
this.logger = logger;
}
getLogger(): Logger {
return this.logger || this.notSetError("logger");
}
setEnableLogging(isLoggingEnabled: boolean): void {
this.enableLogging = isLoggingEnabled;
}
setIdempotenceRequestTimestamp(ts?: string | number): void {
this.idempotenceRequestTimestamp = ts;
}
getIdempotenceRequestTimestamp(): string | number | undefined {
return this.idempotenceRequestTimestamp;
}
setIntegrator(integrator: string): void {
if (this.integrator) {
if (this.isLoggingEnabled()) {
this.getLogger()("error", "integrator has already been set and cannot be overwritten");
}
throw new Error("integrator has already been set and cannot be overwritten");
}
if (!integrator) {
if (this.isLoggingEnabled()) {
this.getLogger()("error", "integrator is required");
}
throw new Error("integrator is required");
}
this.integrator = integrator;
}
getIntegrator(): string {
return this.integrator || this.notSetError("integrator");
}
setShoppingCartExtension(shoppingCartExtension?: ShoppingCartExtension): void {
if (this.shoppingCartExtension) {
if (this.isLoggingEnabled()) {
this.getLogger()("error", "shoppingCartExtension has already been set and cannot be overwritten");
}
throw new Error("shoppingCartExtension has already been set and cannot be overwritten");
}
if (shoppingCartExtension) {
if (shoppingCartExtension.creator && shoppingCartExtension.name && shoppingCartExtension.version) {
this.shoppingCartExtension = shoppingCartExtension;
} else {
if (this.isLoggingEnabled()) {
this.getLogger()(
"warn",
"shoppingCartExtension is missing a required property (creator / name / version). Your shoppingCartExtension: " + JSON.stringify(shoppingCartExtension)
);
}
}
}
}
getShoppingCartExtension(): ShoppingCartExtension | undefined {
return this.shoppingCartExtension;
}
isLoggingEnabled(): boolean {
return this.enableLogging || false;
}
}
const sdkContext: SdkContext = new SdkContextImpl();
export = sdkContext;
| 33.808 | 163 | 0.659962 |
e587edcbc173d6a1c4313d291619a1f92305dfdc | 1,211 | ts | TypeScript | packages/api/src/modules/role/types.ts | UriellViana/unnamed-project | 5dfef4f54d5aa23ac7d5d52580fb5c1b9d09fa12 | [
"MIT"
] | 1 | 2020-11-19T03:55:17.000Z | 2020-11-19T03:55:17.000Z | packages/api/src/modules/role/types.ts | UriellViana/unnamed-project | 5dfef4f54d5aa23ac7d5d52580fb5c1b9d09fa12 | [
"MIT"
] | 39 | 2020-11-04T21:59:59.000Z | 2021-09-13T15:03:58.000Z | packages/api/src/modules/role/types.ts | ditointernet/tradulab | c00d1e38932b00a84bddce9ba181dc9cfd8e1abb | [
"MIT"
] | null | null | null | import { gql } from 'apollo-server-express';
export default gql`
enum InvitedRole {
# viewer
contributor
proofreader
developer
manager
}
type Role {
id: ID!
role: String!
user: String!
project: String!
createdAt: Date!
updatedAt: Date!
}
type RoleWithProject {
id: ID!
role: String!
user: String!
project: Project!
createdAt: Date!
updatedAt: Date!
}
type RoleWithUser {
id: ID!
role: String!
user: User!
project: String!
createdAt: Date!
updatedAt: Date!
}
type RoleWithUserNode {
node: RoleWithUser!
}
type RoleWithUserConnection {
edges: [RoleWithUserNode!]!
pageInfo: PageInfo!
}
extend type Mutation {
inviteUserToProject(
projectId: ID!
userId: ID!
role: InvitedRole!
): RoleWithUser!
updateUserProjectRole(
projectId: ID!
userId: ID!
role: InvitedRole!
): RoleWithUser!
removeUserFromProject(projectId: ID!, userId: ID!): Boolean
}
extend type Query {
projectUsers(
projectId: ID!
limit: Int
startAfter: String
): RoleWithUserConnection!
myRole(projectId: ID!): Role
}
`;
| 16.589041 | 63 | 0.610239 |
b1820d57476d317189a6b1aef81cf791e47b2c3f | 1,386 | h | C | MgpWallet/MGPToken/应用/OTC快捷买卖/订单详情页面/Model/OverTheCounterOrderDetailModel.h | mangochain2020/mangowallet-ios | 8481187bd16efd1f313bc77691aa0ecd47eebd8f | [
"MIT"
] | 1 | 2021-03-03T03:07:47.000Z | 2021-03-03T03:07:47.000Z | MgpWallet/MGPToken/应用/OTC快捷买卖/订单详情页面/Model/OverTheCounterOrderDetailModel.h | mangochain2020/mangowallet-ios | 8481187bd16efd1f313bc77691aa0ecd47eebd8f | [
"MIT"
] | null | null | null | MgpWallet/MGPToken/应用/OTC快捷买卖/订单详情页面/Model/OverTheCounterOrderDetailModel.h | mangochain2020/mangowallet-ios | 8481187bd16efd1f313bc77691aa0ecd47eebd8f | [
"MIT"
] | 3 | 2020-12-27T07:45:04.000Z | 2021-03-03T03:07:49.000Z | //
// OverTheCounterOrderDetailModel.h
// TaiYiToken
//
// Created by mac on 2020/12/31.
// Copyright © 2020 admin. All rights reserved.
//
#import <Foundation/Foundation.h>
/**
类目条目
*/
@interface CategoryDetailModel : NSObject
@property (nonatomic , assign)BOOL isTitle;
@property (nonatomic , copy)NSString *leftTitle;
@property (nonatomic , assign)BOOL isCopy;
@property (nonatomic , copy)NSString *rightTitle;
@end
/**
银行卡支付方式
*/
@interface CardDetailModel : NSObject
@property (nonatomic , copy)NSString *cardName;
@property (nonatomic , copy)NSString *cardNameRightTitle;
@property (nonatomic , copy)NSString *cardIcon;
@property (nonatomic , copy)NSString *userNameL;
@property (nonatomic , copy)NSString *cardNumberL;
@property (nonatomic , copy)NSString *bankNameL;
@property (nonatomic , copy)NSString *accountOpeningBranchL;
@property (nonatomic , copy)NSString *describe;
@property (nonatomic , copy)NSString *userNameR;
@property (nonatomic , copy)NSString *cardNumberR;
@property (nonatomic , copy)NSString *bankNameR;
@property (nonatomic , copy)NSString *accountOpeningBranchR;
@end
NS_ASSUME_NONNULL_BEGIN
@interface OverTheCounterOrderDetailModel : NSObject
@property (nonatomic , strong) NSMutableArray *categoryArrays;
@property (nonatomic , strong) CardDetailModel *cardDetailModel;
@end
NS_ASSUME_NONNULL_END
| 21.65625 | 76 | 0.751804 |
76f90f737379dee6e178845a0fc08f66f6d17b1f | 1,033 | h | C | stab.h | mikequentel/c2ada | d2cc8ed2d42c4ca9ae35b5de144b795c58f97cc1 | [
"MIT"
] | 4 | 2017-06-07T11:43:08.000Z | 2022-03-14T00:29:06.000Z | stab.h | mikequentel/c2ada | d2cc8ed2d42c4ca9ae35b5de144b795c58f97cc1 | [
"MIT"
] | 1 | 2017-11-24T14:59:27.000Z | 2017-12-14T04:19:28.000Z | stab.h | mikequentel/c2ada | d2cc8ed2d42c4ca9ae35b5de144b795c58f97cc1 | [
"MIT"
] | 4 | 2015-06-26T10:48:39.000Z | 2020-04-13T18:05:01.000Z | #ifndef _H_STAB_
#define _H_STAB_
extern symbol_t *new_sym(void);
extern symbol_t *find_sym(char*);
extern void store_sym(symbol_t*);
/* Scopes */
typedef enum {
Unspecified_scope,
Func_scope,
File_scope,
Block_scope,
Proto_scope
} scope_kind_t;
extern scope_kind_t scope_kind(scope_id_t);
extern scope_id_t scope_parent(scope_id_t);
extern symbol_pt scope_symbol(scope_id_t);
extern symbol_pt scope_parent_func( scope_id_t );
extern int scope_level(scope_id_t);
extern void set_scope_kind( scope_id_t scope, scope_kind_t kind);
extern void set_scope_parent( scope_id_t scope, scope_id_t parent);
extern void set_scope_symbol( scope_id_t scope, symbol_pt sym);
extern void scope_push( scope_kind_t kind );
extern void scope_pop( void );
extern int next_param (void);
extern scope_id_t new_scope_id(scope_kind_t kind);
extern scope_id_t new_block_scope(scope_id_t parent);
extern scope_id_t current_scope(void);
extern void set_current_scope(scope_id_t);
#endif /* _H_STAB_ */
| 21.520833 | 67 | 0.774443 |
52d6324055bdbd949c86a36e0fbf44409366118b | 434 | sql | SQL | database/script/2020_10_30_mercado.sql | Smukihub/ProyectoRecuperacion | 6f66797836d099d10eb387cb8ff12c855abc901c | [
"MIT"
] | null | null | null | database/script/2020_10_30_mercado.sql | Smukihub/ProyectoRecuperacion | 6f66797836d099d10eb387cb8ff12c855abc901c | [
"MIT"
] | null | null | null | database/script/2020_10_30_mercado.sql | Smukihub/ProyectoRecuperacion | 6f66797836d099d10eb387cb8ff12c855abc901c | [
"MIT"
] | 1 | 2021-08-21T06:12:00.000Z | 2021-08-21T06:12:00.000Z | CREATE TABLE `categorias` (
`id` int NOT NULL,
`nombre` varchar(20) COLLATE utf8_bin NOT NULL,
`descripcion` varchar(100) COLLATE utf8_bin NOT NULL,
`imagen` varchar(100) COLLATE utf8_bin NOT NULL,
`activa` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
ALTER TABLE `categorias`
ADD PRIMARY KEY (`id`);
ALTER TABLE `categorias`
MODIFY `id` int NOT NULL AUTO_INCREMENT;
COMMIT;
| 28.933333 | 67 | 0.74424 |
46bc14824535b53c49c091dcc4051de806ea373d | 1,915 | css | CSS | src/assets/css/loginPage.css | Accomple/WebApp | afbfb02b544cb1c6e765838a835dac0cd7ae8149 | [
"MIT"
] | null | null | null | src/assets/css/loginPage.css | Accomple/WebApp | afbfb02b544cb1c6e765838a835dac0cd7ae8149 | [
"MIT"
] | null | null | null | src/assets/css/loginPage.css | Accomple/WebApp | afbfb02b544cb1c6e765838a835dac0cd7ae8149 | [
"MIT"
] | null | null | null | .login-form{
height: 100%;
border:solid 2px rgb(96, 195, 173) ;
background-color: white;
width: 40%;
height: 400px;
margin-left: 30%;
margin-top: 50px;
padding: 10px 10px 10px 10px;
}
.perks{
border:1px solid rgba(0,0,0,0.2);
margin-top: 15px;
margin-bottom: 10px;
padding: 4px;
border-radius: 0.25em;
}
.signlink{
font-size: 13px;
margin-bottom: 10px;
}
.step-name{
text-align: center;
}
.Form-content{
width:500px;
border: 2px solid rgb(96, 195, 173);
border-radius: 0.25rem;
padding: 10px;
font-family: Font-Medium;
color: rgb(96, 195, 173);
}
.signup{
width:100%;
text-align: center;
font-family: Font-Bold;
}
.Form3{
display: flex;
flex-direction: column;
align-items: center;
margin-top: 50px;
}
.login-form2{
height: 100%;
border:solid 2px rgb(96, 195, 173) ;
background-color: white;
font-family: Font-Medium;
color: rgb(96, 195, 173);
width: 60%;
height: auto;
margin-left: 20%;
margin-top: 50px;
border-radius: 0.25rem;
padding: 10px 10px 10px 10px;
}
.error-text{
color: red;
font-size: 12px;
padding-bottom: 3px;
}
.wrapper{
width: 100%;
}
.cust-button{
border-radius: 0px;
background-color: rgb(96, 195, 173);
color: rgb(255, 255, 255);
border: 2px solid rgb(96, 195, 173);
padding: 8px 11px;
font-size: 12px;
cursor: pointer;
min-width: 125px;
text-align: center;
text-transform: uppercase;
font-family: Font-Bold;
outline: none;
}
.cust-button:hover{
background-color: white;
color:rgb(96, 195, 173);
border: 2px solid rgb(96, 195, 173);
}
.cust-button:focus{
background-color: white;
color:rgb(96, 195, 173);
border: 2px solid rgb(96, 195, 173);
}
.cust-button:disabled{
background-color: white;
color:rgb(96, 195, 173);
border: 2px solid rgb(96, 195, 173);
}
.otp{
margin: auto;
width: 400px;
text-align: center;
margin-top:200px;
}
.otp-input{
margin-right: 10px;
} | 16.652174 | 40 | 0.65483 |
c7bcb664bcc58934dd16f4662e4af550f74af2c8 | 71,464 | py | Python | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ip_tcp_cfg.py | bopopescu/ACI | dd717bc74739eeed4747b3ea9e36b239580df5e1 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ip_tcp_cfg.py | bopopescu/ACI | dd717bc74739eeed4747b3ea9e36b239580df5e1 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ip_tcp_cfg.py | bopopescu/ACI | dd717bc74739eeed4747b3ea9e36b239580df5e1 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-07-22T04:04:44.000Z | 2020-07-22T04:04:44.000Z | """ Cisco_IOS_XR_ip_tcp_cfg
This module contains a collection of YANG definitions
for Cisco IOS\-XR ip\-tcp package configuration.
This module contains definitions
for the following management objects\:
ip\-tcp\: Global IP TCP configuration
ip\: ip
Copyright (c) 2013\-2017 by Cisco Systems, Inc.
All rights reserved.
"""
from collections import OrderedDict
from ydk.types import Entity, EntityPath, Identity, Enum, YType, YLeaf, YLeafList, YList, LeafDataList, Bits, Empty, Decimal64
from ydk.filters import YFilter
from ydk.errors import YError, YModelError
from ydk.errors.error_handler import handle_type_error as _handle_type_error
class IpTcp(Entity):
"""
Global IP TCP configuration
.. attribute:: directory
TCP directory details
**type**\: :py:class:`Directory <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.IpTcp.Directory>`
**presence node**\: True
.. attribute:: throttle
Throttle TCP receive buffer (in percentage)
**type**\: :py:class:`Throttle <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.IpTcp.Throttle>`
**presence node**\: True
.. attribute:: num_thread
TCP InQueue and OutQueue threads
**type**\: :py:class:`NumThread <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.IpTcp.NumThread>`
**presence node**\: True
.. attribute:: accept_rate
TCP connection accept rate
**type**\: int
**range:** 1..1000
**default value**\: 500
.. attribute:: selective_ack
Enable TCP selective\-ACK
**type**\: :py:class:`Empty<ydk.types.Empty>`
.. attribute:: window_size
TCP receive window size (bytes)
**type**\: int
**range:** 2048..65535
**units**\: byte
.. attribute:: receive_q
TCP receive Queue Size
**type**\: int
**range:** 40..800
.. attribute:: maximum_segment_size
TCP initial maximum segment size
**type**\: int
**range:** 68..10000
.. attribute:: syn_wait_time
Time to wait on new TCP connections in seconds
**type**\: int
**range:** 5..30
**units**\: second
.. attribute:: timestamp
Enable TCP timestamp option
**type**\: :py:class:`Empty<ydk.types.Empty>`
.. attribute:: path_mtu_discovery
Aging time; 0 for infinite, and range be (10,30)
**type**\: int
**range:** \-2147483648..2147483647
**units**\: minute
**default value**\: 10
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(IpTcp, self).__init__()
self._top_entity = None
self.yang_name = "ip-tcp"
self.yang_parent_name = "Cisco-IOS-XR-ip-tcp-cfg"
self.is_top_level_class = True
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_container_classes = OrderedDict([("directory", ("directory", IpTcp.Directory)), ("throttle", ("throttle", IpTcp.Throttle)), ("num-thread", ("num_thread", IpTcp.NumThread))])
self._child_list_classes = OrderedDict([])
self._leafs = OrderedDict([
('accept_rate', YLeaf(YType.uint32, 'accept-rate')),
('selective_ack', YLeaf(YType.empty, 'selective-ack')),
('window_size', YLeaf(YType.uint32, 'window-size')),
('receive_q', YLeaf(YType.uint32, 'receive-q')),
('maximum_segment_size', YLeaf(YType.uint32, 'maximum-segment-size')),
('syn_wait_time', YLeaf(YType.uint32, 'syn-wait-time')),
('timestamp', YLeaf(YType.empty, 'timestamp')),
('path_mtu_discovery', YLeaf(YType.int32, 'path-mtu-discovery')),
])
self.accept_rate = None
self.selective_ack = None
self.window_size = None
self.receive_q = None
self.maximum_segment_size = None
self.syn_wait_time = None
self.timestamp = None
self.path_mtu_discovery = None
self.directory = None
self._children_name_map["directory"] = "directory"
self._children_yang_names.add("directory")
self.throttle = None
self._children_name_map["throttle"] = "throttle"
self._children_yang_names.add("throttle")
self.num_thread = None
self._children_name_map["num_thread"] = "num-thread"
self._children_yang_names.add("num-thread")
self._segment_path = lambda: "Cisco-IOS-XR-ip-tcp-cfg:ip-tcp"
def __setattr__(self, name, value):
self._perform_setattr(IpTcp, ['accept_rate', 'selective_ack', 'window_size', 'receive_q', 'maximum_segment_size', 'syn_wait_time', 'timestamp', 'path_mtu_discovery'], name, value)
class Directory(Entity):
"""
TCP directory details
.. attribute:: directoryname
Directory name
**type**\: str
**mandatory**\: True
.. attribute:: max_debug_files
Set number of Debug files
**type**\: int
**range:** 1..10000
**default value**\: 256
.. attribute:: max_file_size_files
Set size of debug files in bytes
**type**\: int
**range:** 1024..4294967295
**units**\: byte
This class is a :ref:`presence class<presence-class>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(IpTcp.Directory, self).__init__()
self.yang_name = "directory"
self.yang_parent_name = "ip-tcp"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_container_classes = OrderedDict([])
self._child_list_classes = OrderedDict([])
self.is_presence_container = True
self._leafs = OrderedDict([
('directoryname', YLeaf(YType.str, 'directoryname')),
('max_debug_files', YLeaf(YType.uint32, 'max-debug-files')),
('max_file_size_files', YLeaf(YType.uint32, 'max-file-size-files')),
])
self.directoryname = None
self.max_debug_files = None
self.max_file_size_files = None
self._segment_path = lambda: "directory"
self._absolute_path = lambda: "Cisco-IOS-XR-ip-tcp-cfg:ip-tcp/%s" % self._segment_path()
def __setattr__(self, name, value):
self._perform_setattr(IpTcp.Directory, ['directoryname', 'max_debug_files', 'max_file_size_files'], name, value)
class Throttle(Entity):
"""
Throttle TCP receive buffer (in percentage)
.. attribute:: tcpmin_throttle
Min throttle
**type**\: int
**range:** 0..100
**mandatory**\: True
.. attribute:: tcpmaxthrottle
Max throttle
**type**\: int
**range:** 0..100
**mandatory**\: True
This class is a :ref:`presence class<presence-class>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(IpTcp.Throttle, self).__init__()
self.yang_name = "throttle"
self.yang_parent_name = "ip-tcp"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_container_classes = OrderedDict([])
self._child_list_classes = OrderedDict([])
self.is_presence_container = True
self._leafs = OrderedDict([
('tcpmin_throttle', YLeaf(YType.uint32, 'tcpmin-throttle')),
('tcpmaxthrottle', YLeaf(YType.uint32, 'tcpmaxthrottle')),
])
self.tcpmin_throttle = None
self.tcpmaxthrottle = None
self._segment_path = lambda: "throttle"
self._absolute_path = lambda: "Cisco-IOS-XR-ip-tcp-cfg:ip-tcp/%s" % self._segment_path()
def __setattr__(self, name, value):
self._perform_setattr(IpTcp.Throttle, ['tcpmin_throttle', 'tcpmaxthrottle'], name, value)
class NumThread(Entity):
"""
TCP InQueue and OutQueue threads
.. attribute:: tcp_in_q_threads
InQ Threads
**type**\: int
**range:** 1..16
**mandatory**\: True
.. attribute:: tcp_out_q_threads
OutQ Threads
**type**\: int
**range:** 1..16
**mandatory**\: True
This class is a :ref:`presence class<presence-class>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(IpTcp.NumThread, self).__init__()
self.yang_name = "num-thread"
self.yang_parent_name = "ip-tcp"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_container_classes = OrderedDict([])
self._child_list_classes = OrderedDict([])
self.is_presence_container = True
self._leafs = OrderedDict([
('tcp_in_q_threads', YLeaf(YType.uint32, 'tcp-in-q-threads')),
('tcp_out_q_threads', YLeaf(YType.uint32, 'tcp-out-q-threads')),
])
self.tcp_in_q_threads = None
self.tcp_out_q_threads = None
self._segment_path = lambda: "num-thread"
self._absolute_path = lambda: "Cisco-IOS-XR-ip-tcp-cfg:ip-tcp/%s" % self._segment_path()
def __setattr__(self, name, value):
self._perform_setattr(IpTcp.NumThread, ['tcp_in_q_threads', 'tcp_out_q_threads'], name, value)
def clone_ptr(self):
self._top_entity = IpTcp()
return self._top_entity
class Ip(Entity):
"""
ip
.. attribute:: cinetd
Cinetd configuration data
**type**\: :py:class:`Cinetd <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd>`
.. attribute:: forward_protocol
Controls forwarding of physical and directed IP broadcasts
**type**\: :py:class:`ForwardProtocol <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.ForwardProtocol>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(Ip, self).__init__()
self._top_entity = None
self.yang_name = "ip"
self.yang_parent_name = "Cisco-IOS-XR-ip-tcp-cfg"
self.is_top_level_class = True
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_container_classes = OrderedDict([("cinetd", ("cinetd", Ip.Cinetd)), ("Cisco-IOS-XR-ip-udp-cfg:forward-protocol", ("forward_protocol", Ip.ForwardProtocol))])
self._child_list_classes = OrderedDict([])
self._leafs = OrderedDict()
self.cinetd = Ip.Cinetd()
self.cinetd.parent = self
self._children_name_map["cinetd"] = "cinetd"
self._children_yang_names.add("cinetd")
self.forward_protocol = Ip.ForwardProtocol()
self.forward_protocol.parent = self
self._children_name_map["forward_protocol"] = "Cisco-IOS-XR-ip-udp-cfg:forward-protocol"
self._children_yang_names.add("Cisco-IOS-XR-ip-udp-cfg:forward-protocol")
self._segment_path = lambda: "Cisco-IOS-XR-ip-tcp-cfg:ip"
class Cinetd(Entity):
"""
Cinetd configuration data
.. attribute:: services
Describing services of cinetd
**type**\: :py:class:`Services <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services>`
.. attribute:: rate_limit
Number of service requests accepted per second
**type**\: int
**range:** 1..100
**default value**\: 1
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(Ip.Cinetd, self).__init__()
self.yang_name = "cinetd"
self.yang_parent_name = "ip"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_container_classes = OrderedDict([("services", ("services", Ip.Cinetd.Services))])
self._child_list_classes = OrderedDict([])
self._leafs = OrderedDict([
('rate_limit', YLeaf(YType.uint32, 'Cisco-IOS-XR-ipv4-cinetd-cfg:rate-limit')),
])
self.rate_limit = None
self.services = Ip.Cinetd.Services()
self.services.parent = self
self._children_name_map["services"] = "services"
self._children_yang_names.add("services")
self._segment_path = lambda: "cinetd"
self._absolute_path = lambda: "Cisco-IOS-XR-ip-tcp-cfg:ip/%s" % self._segment_path()
def __setattr__(self, name, value):
self._perform_setattr(Ip.Cinetd, ['rate_limit'], name, value)
class Services(Entity):
"""
Describing services of cinetd
.. attribute:: ipv4
IPV4 related services
**type**\: :py:class:`Ipv4 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Ipv4>`
.. attribute:: vrfs
VRF table
**type**\: :py:class:`Vrfs <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs>`
.. attribute:: ipv6
IPV6 related services
**type**\: :py:class:`Ipv6 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Ipv6>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(Ip.Cinetd.Services, self).__init__()
self.yang_name = "services"
self.yang_parent_name = "cinetd"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_container_classes = OrderedDict([("ipv4", ("ipv4", Ip.Cinetd.Services.Ipv4)), ("vrfs", ("vrfs", Ip.Cinetd.Services.Vrfs)), ("ipv6", ("ipv6", Ip.Cinetd.Services.Ipv6))])
self._child_list_classes = OrderedDict([])
self._leafs = OrderedDict()
self.ipv4 = Ip.Cinetd.Services.Ipv4()
self.ipv4.parent = self
self._children_name_map["ipv4"] = "ipv4"
self._children_yang_names.add("ipv4")
self.vrfs = Ip.Cinetd.Services.Vrfs()
self.vrfs.parent = self
self._children_name_map["vrfs"] = "vrfs"
self._children_yang_names.add("vrfs")
self.ipv6 = Ip.Cinetd.Services.Ipv6()
self.ipv6.parent = self
self._children_name_map["ipv6"] = "ipv6"
self._children_yang_names.add("ipv6")
self._segment_path = lambda: "services"
self._absolute_path = lambda: "Cisco-IOS-XR-ip-tcp-cfg:ip/cinetd/%s" % self._segment_path()
class Ipv4(Entity):
"""
IPV4 related services
.. attribute:: small_servers
Describing IPV4 and IPV6 small servers
**type**\: :py:class:`SmallServers <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Ipv4.SmallServers>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(Ip.Cinetd.Services.Ipv4, self).__init__()
self.yang_name = "ipv4"
self.yang_parent_name = "services"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_container_classes = OrderedDict([("small-servers", ("small_servers", Ip.Cinetd.Services.Ipv4.SmallServers))])
self._child_list_classes = OrderedDict([])
self._leafs = OrderedDict()
self.small_servers = Ip.Cinetd.Services.Ipv4.SmallServers()
self.small_servers.parent = self
self._children_name_map["small_servers"] = "small-servers"
self._children_yang_names.add("small-servers")
self._segment_path = lambda: "ipv4"
self._absolute_path = lambda: "Cisco-IOS-XR-ip-tcp-cfg:ip/cinetd/services/%s" % self._segment_path()
class SmallServers(Entity):
"""
Describing IPV4 and IPV6 small servers
.. attribute:: tcp_small_servers
Describing TCP related IPV4 and IPV6 small servers
**type**\: :py:class:`TcpSmallServers <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Ipv4.SmallServers.TcpSmallServers>`
**presence node**\: True
.. attribute:: udp_small_servers
UDP small servers configuration
**type**\: :py:class:`UdpSmallServers <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Ipv4.SmallServers.UdpSmallServers>`
**presence node**\: True
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(Ip.Cinetd.Services.Ipv4.SmallServers, self).__init__()
self.yang_name = "small-servers"
self.yang_parent_name = "ipv4"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_container_classes = OrderedDict([("tcp-small-servers", ("tcp_small_servers", Ip.Cinetd.Services.Ipv4.SmallServers.TcpSmallServers)), ("Cisco-IOS-XR-ip-udp-cfg:udp-small-servers", ("udp_small_servers", Ip.Cinetd.Services.Ipv4.SmallServers.UdpSmallServers))])
self._child_list_classes = OrderedDict([])
self._leafs = OrderedDict()
self.tcp_small_servers = None
self._children_name_map["tcp_small_servers"] = "tcp-small-servers"
self._children_yang_names.add("tcp-small-servers")
self.udp_small_servers = None
self._children_name_map["udp_small_servers"] = "Cisco-IOS-XR-ip-udp-cfg:udp-small-servers"
self._children_yang_names.add("Cisco-IOS-XR-ip-udp-cfg:udp-small-servers")
self._segment_path = lambda: "small-servers"
self._absolute_path = lambda: "Cisco-IOS-XR-ip-tcp-cfg:ip/cinetd/services/ipv4/%s" % self._segment_path()
class TcpSmallServers(Entity):
"""
Describing TCP related IPV4 and IPV6 small
servers
.. attribute:: access_control_list_name
Specify the access list
**type**\: str
.. attribute:: small_server
Set number of allowable TCP small servers, specify 0 for no\-limit
**type**\: union of the below types:
**type**\: :py:class:`SmallServer <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Ipv6.SmallServers.TcpSmallServers.SmallServer>`
**type**\: int
**range:** 0..2147483647
**mandatory**\: True
This class is a :ref:`presence class<presence-class>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(Ip.Cinetd.Services.Ipv4.SmallServers.TcpSmallServers, self).__init__()
self.yang_name = "tcp-small-servers"
self.yang_parent_name = "small-servers"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_container_classes = OrderedDict([])
self._child_list_classes = OrderedDict([])
self.is_presence_container = True
self._leafs = OrderedDict([
('access_control_list_name', YLeaf(YType.str, 'access-control-list-name')),
('small_server', YLeaf(YType.str, 'small-server')),
])
self.access_control_list_name = None
self.small_server = None
self._segment_path = lambda: "tcp-small-servers"
self._absolute_path = lambda: "Cisco-IOS-XR-ip-tcp-cfg:ip/cinetd/services/ipv4/small-servers/%s" % self._segment_path()
def __setattr__(self, name, value):
self._perform_setattr(Ip.Cinetd.Services.Ipv4.SmallServers.TcpSmallServers, ['access_control_list_name', 'small_server'], name, value)
class SmallServer(Enum):
"""
SmallServer (Enum Class)
Set number of allowable TCP small servers,
specify 0 for no\-limit
.. data:: no_limit = 0
Unlimited Servers
"""
no_limit = Enum.YLeaf(0, "no-limit")
class UdpSmallServers(Entity):
"""
UDP small servers configuration
.. attribute:: access_control_list_name
Specify the access list
**type**\: str
.. attribute:: small_server
Set number of allowable small servers, specify 0 for no\-limit
**type**\: union of the below types:
**type**\: :py:class:`SmallServer <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Ipv4.SmallServers.UdpSmallServers.SmallServer>`
**type**\: int
**range:** 0..2147483647
**mandatory**\: True
This class is a :ref:`presence class<presence-class>`
"""
_prefix = 'ip-udp-cfg'
_revision = '2017-07-31'
def __init__(self):
super(Ip.Cinetd.Services.Ipv4.SmallServers.UdpSmallServers, self).__init__()
self.yang_name = "udp-small-servers"
self.yang_parent_name = "small-servers"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_container_classes = OrderedDict([])
self._child_list_classes = OrderedDict([])
self.is_presence_container = True
self._leafs = OrderedDict([
('access_control_list_name', YLeaf(YType.str, 'access-control-list-name')),
('small_server', YLeaf(YType.str, 'small-server')),
])
self.access_control_list_name = None
self.small_server = None
self._segment_path = lambda: "Cisco-IOS-XR-ip-udp-cfg:udp-small-servers"
self._absolute_path = lambda: "Cisco-IOS-XR-ip-tcp-cfg:ip/cinetd/services/ipv4/small-servers/%s" % self._segment_path()
def __setattr__(self, name, value):
self._perform_setattr(Ip.Cinetd.Services.Ipv4.SmallServers.UdpSmallServers, ['access_control_list_name', 'small_server'], name, value)
class SmallServer(Enum):
"""
SmallServer (Enum Class)
Set number of allowable small servers, specify
0 for no\-limit
.. data:: no_limit = 0
Unlimited Servers
"""
no_limit = Enum.YLeaf(0, "no-limit")
class Vrfs(Entity):
"""
VRF table
.. attribute:: vrf
VRF specific data
**type**\: list of :py:class:`Vrf <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs.Vrf>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(Ip.Cinetd.Services.Vrfs, self).__init__()
self.yang_name = "vrfs"
self.yang_parent_name = "services"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_container_classes = OrderedDict([])
self._child_list_classes = OrderedDict([("vrf", ("vrf", Ip.Cinetd.Services.Vrfs.Vrf))])
self._leafs = OrderedDict()
self.vrf = YList(self)
self._segment_path = lambda: "vrfs"
self._absolute_path = lambda: "Cisco-IOS-XR-ip-tcp-cfg:ip/cinetd/services/%s" % self._segment_path()
def __setattr__(self, name, value):
self._perform_setattr(Ip.Cinetd.Services.Vrfs, [], name, value)
class Vrf(Entity):
"""
VRF specific data
.. attribute:: vrf_name (key)
Name of the VRF instance
**type**\: str
**pattern:** [\\w\\\-\\.\:,\_@#%$\\+=\\\|;]+
.. attribute:: ipv6
IPV6 related services
**type**\: :py:class:`Ipv6 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs.Vrf.Ipv6>`
.. attribute:: ipv4
IPV4 related services
**type**\: :py:class:`Ipv4 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs.Vrf.Ipv4>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(Ip.Cinetd.Services.Vrfs.Vrf, self).__init__()
self.yang_name = "vrf"
self.yang_parent_name = "vrfs"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = ['vrf_name']
self._child_container_classes = OrderedDict([("ipv6", ("ipv6", Ip.Cinetd.Services.Vrfs.Vrf.Ipv6)), ("ipv4", ("ipv4", Ip.Cinetd.Services.Vrfs.Vrf.Ipv4))])
self._child_list_classes = OrderedDict([])
self._leafs = OrderedDict([
('vrf_name', YLeaf(YType.str, 'vrf-name')),
])
self.vrf_name = None
self.ipv6 = Ip.Cinetd.Services.Vrfs.Vrf.Ipv6()
self.ipv6.parent = self
self._children_name_map["ipv6"] = "ipv6"
self._children_yang_names.add("ipv6")
self.ipv4 = Ip.Cinetd.Services.Vrfs.Vrf.Ipv4()
self.ipv4.parent = self
self._children_name_map["ipv4"] = "ipv4"
self._children_yang_names.add("ipv4")
self._segment_path = lambda: "vrf" + "[vrf-name='" + str(self.vrf_name) + "']"
self._absolute_path = lambda: "Cisco-IOS-XR-ip-tcp-cfg:ip/cinetd/services/vrfs/%s" % self._segment_path()
def __setattr__(self, name, value):
self._perform_setattr(Ip.Cinetd.Services.Vrfs.Vrf, ['vrf_name'], name, value)
class Ipv6(Entity):
"""
IPV6 related services
.. attribute:: telnet
TELNET server configuration commands
**type**\: :py:class:`Telnet <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Telnet>`
.. attribute:: tftp
TFTP server configuration commands
**type**\: :py:class:`Tftp <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Tftp>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(Ip.Cinetd.Services.Vrfs.Vrf.Ipv6, self).__init__()
self.yang_name = "ipv6"
self.yang_parent_name = "vrf"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_container_classes = OrderedDict([("telnet", ("telnet", Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Telnet)), ("tftp", ("tftp", Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Tftp))])
self._child_list_classes = OrderedDict([])
self._leafs = OrderedDict()
self.telnet = Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Telnet()
self.telnet.parent = self
self._children_name_map["telnet"] = "telnet"
self._children_yang_names.add("telnet")
self.tftp = Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Tftp()
self.tftp.parent = self
self._children_name_map["tftp"] = "tftp"
self._children_yang_names.add("tftp")
self._segment_path = lambda: "ipv6"
class Telnet(Entity):
"""
TELNET server configuration commands
.. attribute:: tcp
TCP details
**type**\: :py:class:`Tcp <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Telnet.Tcp>`
**presence node**\: True
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Telnet, self).__init__()
self.yang_name = "telnet"
self.yang_parent_name = "ipv6"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_container_classes = OrderedDict([("tcp", ("tcp", Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Telnet.Tcp))])
self._child_list_classes = OrderedDict([])
self._leafs = OrderedDict()
self.tcp = None
self._children_name_map["tcp"] = "tcp"
self._children_yang_names.add("tcp")
self._segment_path = lambda: "telnet"
class Tcp(Entity):
"""
TCP details
.. attribute:: access_list_name
Access list
**type**\: str
.. attribute:: maximum_server
Set number of allowable servers
**type**\: int
**range:** 1..100
**mandatory**\: True
This class is a :ref:`presence class<presence-class>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Telnet.Tcp, self).__init__()
self.yang_name = "tcp"
self.yang_parent_name = "telnet"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_container_classes = OrderedDict([])
self._child_list_classes = OrderedDict([])
self.is_presence_container = True
self._leafs = OrderedDict([
('access_list_name', YLeaf(YType.str, 'access-list-name')),
('maximum_server', YLeaf(YType.uint32, 'maximum-server')),
])
self.access_list_name = None
self.maximum_server = None
self._segment_path = lambda: "tcp"
def __setattr__(self, name, value):
self._perform_setattr(Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Telnet.Tcp, ['access_list_name', 'maximum_server'], name, value)
class Tftp(Entity):
"""
TFTP server configuration commands
.. attribute:: udp
UDP details
**type**\: :py:class:`Udp <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Tftp.Udp>`
**presence node**\: True
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Tftp, self).__init__()
self.yang_name = "tftp"
self.yang_parent_name = "ipv6"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_container_classes = OrderedDict([("udp", ("udp", Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Tftp.Udp))])
self._child_list_classes = OrderedDict([])
self._leafs = OrderedDict()
self.udp = None
self._children_name_map["udp"] = "udp"
self._children_yang_names.add("udp")
self._segment_path = lambda: "tftp"
class Udp(Entity):
"""
UDP details
.. attribute:: access_list_name
Access list
**type**\: str
.. attribute:: maximum_server
Set number of allowable servers, 0 for no\-limit
**type**\: int
**range:** 0..2147483647
.. attribute:: home_directory
Specify device name where file is read from (e .g. flash\:)
**type**\: str
**mandatory**\: True
.. attribute:: dscp_value
Set IP DSCP (DiffServ CodePoint) for TFTP Server Packets
**type**\: int
**range:** \-2147483648..2147483647
This class is a :ref:`presence class<presence-class>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Tftp.Udp, self).__init__()
self.yang_name = "udp"
self.yang_parent_name = "tftp"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_container_classes = OrderedDict([])
self._child_list_classes = OrderedDict([])
self.is_presence_container = True
self._leafs = OrderedDict([
('access_list_name', YLeaf(YType.str, 'access-list-name')),
('maximum_server', YLeaf(YType.uint32, 'maximum-server')),
('home_directory', YLeaf(YType.str, 'home-directory')),
('dscp_value', YLeaf(YType.int32, 'dscp-value')),
])
self.access_list_name = None
self.maximum_server = None
self.home_directory = None
self.dscp_value = None
self._segment_path = lambda: "udp"
def __setattr__(self, name, value):
self._perform_setattr(Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Tftp.Udp, ['access_list_name', 'maximum_server', 'home_directory', 'dscp_value'], name, value)
class Ipv4(Entity):
"""
IPV4 related services
.. attribute:: telnet
TELNET server configuration commands
**type**\: :py:class:`Telnet <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Telnet>`
.. attribute:: tftp
TFTP server configuration commands
**type**\: :py:class:`Tftp <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Tftp>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(Ip.Cinetd.Services.Vrfs.Vrf.Ipv4, self).__init__()
self.yang_name = "ipv4"
self.yang_parent_name = "vrf"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_container_classes = OrderedDict([("telnet", ("telnet", Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Telnet)), ("tftp", ("tftp", Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Tftp))])
self._child_list_classes = OrderedDict([])
self._leafs = OrderedDict()
self.telnet = Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Telnet()
self.telnet.parent = self
self._children_name_map["telnet"] = "telnet"
self._children_yang_names.add("telnet")
self.tftp = Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Tftp()
self.tftp.parent = self
self._children_name_map["tftp"] = "tftp"
self._children_yang_names.add("tftp")
self._segment_path = lambda: "ipv4"
class Telnet(Entity):
"""
TELNET server configuration commands
.. attribute:: tcp
TCP details
**type**\: :py:class:`Tcp <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Telnet.Tcp>`
**presence node**\: True
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Telnet, self).__init__()
self.yang_name = "telnet"
self.yang_parent_name = "ipv4"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_container_classes = OrderedDict([("tcp", ("tcp", Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Telnet.Tcp))])
self._child_list_classes = OrderedDict([])
self._leafs = OrderedDict()
self.tcp = None
self._children_name_map["tcp"] = "tcp"
self._children_yang_names.add("tcp")
self._segment_path = lambda: "telnet"
class Tcp(Entity):
"""
TCP details
.. attribute:: access_list_name
Access list
**type**\: str
.. attribute:: maximum_server
Set number of allowable servers
**type**\: int
**range:** 1..100
**mandatory**\: True
This class is a :ref:`presence class<presence-class>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Telnet.Tcp, self).__init__()
self.yang_name = "tcp"
self.yang_parent_name = "telnet"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_container_classes = OrderedDict([])
self._child_list_classes = OrderedDict([])
self.is_presence_container = True
self._leafs = OrderedDict([
('access_list_name', YLeaf(YType.str, 'access-list-name')),
('maximum_server', YLeaf(YType.uint32, 'maximum-server')),
])
self.access_list_name = None
self.maximum_server = None
self._segment_path = lambda: "tcp"
def __setattr__(self, name, value):
self._perform_setattr(Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Telnet.Tcp, ['access_list_name', 'maximum_server'], name, value)
class Tftp(Entity):
"""
TFTP server configuration commands
.. attribute:: udp
UDP details
**type**\: :py:class:`Udp <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Tftp.Udp>`
**presence node**\: True
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Tftp, self).__init__()
self.yang_name = "tftp"
self.yang_parent_name = "ipv4"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_container_classes = OrderedDict([("udp", ("udp", Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Tftp.Udp))])
self._child_list_classes = OrderedDict([])
self._leafs = OrderedDict()
self.udp = None
self._children_name_map["udp"] = "udp"
self._children_yang_names.add("udp")
self._segment_path = lambda: "tftp"
class Udp(Entity):
"""
UDP details
.. attribute:: access_list_name
Access list
**type**\: str
.. attribute:: maximum_server
Set number of allowable servers, 0 for no\-limit
**type**\: int
**range:** 0..2147483647
.. attribute:: home_directory
Specify device name where file is read from (e .g. flash\:)
**type**\: str
**mandatory**\: True
.. attribute:: dscp_value
Set IP DSCP (DiffServ CodePoint) for TFTP Server Packets
**type**\: int
**range:** \-2147483648..2147483647
This class is a :ref:`presence class<presence-class>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Tftp.Udp, self).__init__()
self.yang_name = "udp"
self.yang_parent_name = "tftp"
self.is_top_level_class = False
self.has_list_ancestor = True
self.ylist_key_names = []
self._child_container_classes = OrderedDict([])
self._child_list_classes = OrderedDict([])
self.is_presence_container = True
self._leafs = OrderedDict([
('access_list_name', YLeaf(YType.str, 'access-list-name')),
('maximum_server', YLeaf(YType.uint32, 'maximum-server')),
('home_directory', YLeaf(YType.str, 'home-directory')),
('dscp_value', YLeaf(YType.int32, 'dscp-value')),
])
self.access_list_name = None
self.maximum_server = None
self.home_directory = None
self.dscp_value = None
self._segment_path = lambda: "udp"
def __setattr__(self, name, value):
self._perform_setattr(Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Tftp.Udp, ['access_list_name', 'maximum_server', 'home_directory', 'dscp_value'], name, value)
class Ipv6(Entity):
"""
IPV6 related services
.. attribute:: small_servers
Describing IPV4 and IPV6 small servers
**type**\: :py:class:`SmallServers <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Ipv6.SmallServers>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(Ip.Cinetd.Services.Ipv6, self).__init__()
self.yang_name = "ipv6"
self.yang_parent_name = "services"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_container_classes = OrderedDict([("small-servers", ("small_servers", Ip.Cinetd.Services.Ipv6.SmallServers))])
self._child_list_classes = OrderedDict([])
self._leafs = OrderedDict()
self.small_servers = Ip.Cinetd.Services.Ipv6.SmallServers()
self.small_servers.parent = self
self._children_name_map["small_servers"] = "small-servers"
self._children_yang_names.add("small-servers")
self._segment_path = lambda: "ipv6"
self._absolute_path = lambda: "Cisco-IOS-XR-ip-tcp-cfg:ip/cinetd/services/%s" % self._segment_path()
class SmallServers(Entity):
"""
Describing IPV4 and IPV6 small servers
.. attribute:: tcp_small_servers
Describing TCP related IPV4 and IPV6 small servers
**type**\: :py:class:`TcpSmallServers <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Ipv6.SmallServers.TcpSmallServers>`
**presence node**\: True
.. attribute:: udp_small_servers
UDP small servers configuration
**type**\: :py:class:`UdpSmallServers <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Ipv6.SmallServers.UdpSmallServers>`
**presence node**\: True
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(Ip.Cinetd.Services.Ipv6.SmallServers, self).__init__()
self.yang_name = "small-servers"
self.yang_parent_name = "ipv6"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_container_classes = OrderedDict([("tcp-small-servers", ("tcp_small_servers", Ip.Cinetd.Services.Ipv6.SmallServers.TcpSmallServers)), ("Cisco-IOS-XR-ip-udp-cfg:udp-small-servers", ("udp_small_servers", Ip.Cinetd.Services.Ipv6.SmallServers.UdpSmallServers))])
self._child_list_classes = OrderedDict([])
self._leafs = OrderedDict()
self.tcp_small_servers = None
self._children_name_map["tcp_small_servers"] = "tcp-small-servers"
self._children_yang_names.add("tcp-small-servers")
self.udp_small_servers = None
self._children_name_map["udp_small_servers"] = "Cisco-IOS-XR-ip-udp-cfg:udp-small-servers"
self._children_yang_names.add("Cisco-IOS-XR-ip-udp-cfg:udp-small-servers")
self._segment_path = lambda: "small-servers"
self._absolute_path = lambda: "Cisco-IOS-XR-ip-tcp-cfg:ip/cinetd/services/ipv6/%s" % self._segment_path()
class TcpSmallServers(Entity):
"""
Describing TCP related IPV4 and IPV6 small
servers
.. attribute:: access_control_list_name
Specify the access list
**type**\: str
.. attribute:: small_server
Set number of allowable TCP small servers, specify 0 for no\-limit
**type**\: union of the below types:
**type**\: :py:class:`SmallServer <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Ipv6.SmallServers.TcpSmallServers.SmallServer>`
**type**\: int
**range:** 0..2147483647
**mandatory**\: True
This class is a :ref:`presence class<presence-class>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
super(Ip.Cinetd.Services.Ipv6.SmallServers.TcpSmallServers, self).__init__()
self.yang_name = "tcp-small-servers"
self.yang_parent_name = "small-servers"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_container_classes = OrderedDict([])
self._child_list_classes = OrderedDict([])
self.is_presence_container = True
self._leafs = OrderedDict([
('access_control_list_name', YLeaf(YType.str, 'access-control-list-name')),
('small_server', YLeaf(YType.str, 'small-server')),
])
self.access_control_list_name = None
self.small_server = None
self._segment_path = lambda: "tcp-small-servers"
self._absolute_path = lambda: "Cisco-IOS-XR-ip-tcp-cfg:ip/cinetd/services/ipv6/small-servers/%s" % self._segment_path()
def __setattr__(self, name, value):
self._perform_setattr(Ip.Cinetd.Services.Ipv6.SmallServers.TcpSmallServers, ['access_control_list_name', 'small_server'], name, value)
class SmallServer(Enum):
"""
SmallServer (Enum Class)
Set number of allowable TCP small servers,
specify 0 for no\-limit
.. data:: no_limit = 0
Unlimited Servers
"""
no_limit = Enum.YLeaf(0, "no-limit")
class UdpSmallServers(Entity):
"""
UDP small servers configuration
.. attribute:: access_control_list_name
Specify the access list
**type**\: str
.. attribute:: small_server
Set number of allowable small servers, specify 0 for no\-limit
**type**\: union of the below types:
**type**\: :py:class:`SmallServer <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Ipv6.SmallServers.UdpSmallServers.SmallServer>`
**type**\: int
**range:** 0..2147483647
**mandatory**\: True
This class is a :ref:`presence class<presence-class>`
"""
_prefix = 'ip-udp-cfg'
_revision = '2017-07-31'
def __init__(self):
super(Ip.Cinetd.Services.Ipv6.SmallServers.UdpSmallServers, self).__init__()
self.yang_name = "udp-small-servers"
self.yang_parent_name = "small-servers"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_container_classes = OrderedDict([])
self._child_list_classes = OrderedDict([])
self.is_presence_container = True
self._leafs = OrderedDict([
('access_control_list_name', YLeaf(YType.str, 'access-control-list-name')),
('small_server', YLeaf(YType.str, 'small-server')),
])
self.access_control_list_name = None
self.small_server = None
self._segment_path = lambda: "Cisco-IOS-XR-ip-udp-cfg:udp-small-servers"
self._absolute_path = lambda: "Cisco-IOS-XR-ip-tcp-cfg:ip/cinetd/services/ipv6/small-servers/%s" % self._segment_path()
def __setattr__(self, name, value):
self._perform_setattr(Ip.Cinetd.Services.Ipv6.SmallServers.UdpSmallServers, ['access_control_list_name', 'small_server'], name, value)
class SmallServer(Enum):
"""
SmallServer (Enum Class)
Set number of allowable small servers, specify
0 for no\-limit
.. data:: no_limit = 0
Unlimited Servers
"""
no_limit = Enum.YLeaf(0, "no-limit")
class ForwardProtocol(Entity):
"""
Controls forwarding of physical and directed IP
broadcasts
.. attribute:: udp
Packets to a specific UDP port
**type**\: :py:class:`Udp <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.ForwardProtocol.Udp>`
"""
_prefix = 'ip-udp-cfg'
_revision = '2017-07-31'
def __init__(self):
super(Ip.ForwardProtocol, self).__init__()
self.yang_name = "forward-protocol"
self.yang_parent_name = "ip"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_container_classes = OrderedDict([("udp", ("udp", Ip.ForwardProtocol.Udp))])
self._child_list_classes = OrderedDict([])
self._leafs = OrderedDict()
self.udp = Ip.ForwardProtocol.Udp()
self.udp.parent = self
self._children_name_map["udp"] = "udp"
self._children_yang_names.add("udp")
self._segment_path = lambda: "Cisco-IOS-XR-ip-udp-cfg:forward-protocol"
self._absolute_path = lambda: "Cisco-IOS-XR-ip-tcp-cfg:ip/%s" % self._segment_path()
class Udp(Entity):
"""
Packets to a specific UDP port
.. attribute:: ports
Port configuration
**type**\: :py:class:`Ports <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.ForwardProtocol.Udp.Ports>`
.. attribute:: disable
Disable IP Forward Protocol UDP
**type**\: :py:class:`Empty<ydk.types.Empty>`
"""
_prefix = 'ip-udp-cfg'
_revision = '2017-07-31'
def __init__(self):
super(Ip.ForwardProtocol.Udp, self).__init__()
self.yang_name = "udp"
self.yang_parent_name = "forward-protocol"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_container_classes = OrderedDict([("ports", ("ports", Ip.ForwardProtocol.Udp.Ports))])
self._child_list_classes = OrderedDict([])
self._leafs = OrderedDict([
('disable', YLeaf(YType.empty, 'disable')),
])
self.disable = None
self.ports = Ip.ForwardProtocol.Udp.Ports()
self.ports.parent = self
self._children_name_map["ports"] = "ports"
self._children_yang_names.add("ports")
self._segment_path = lambda: "udp"
self._absolute_path = lambda: "Cisco-IOS-XR-ip-tcp-cfg:ip/Cisco-IOS-XR-ip-udp-cfg:forward-protocol/%s" % self._segment_path()
def __setattr__(self, name, value):
self._perform_setattr(Ip.ForwardProtocol.Udp, ['disable'], name, value)
class Ports(Entity):
"""
Port configuration
.. attribute:: port
Well\-known ports are enabled by default and non well\-known ports are disabled by default. It is not allowed to configure the default
**type**\: list of :py:class:`Port <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.ForwardProtocol.Udp.Ports.Port>`
"""
_prefix = 'ip-udp-cfg'
_revision = '2017-07-31'
def __init__(self):
super(Ip.ForwardProtocol.Udp.Ports, self).__init__()
self.yang_name = "ports"
self.yang_parent_name = "udp"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = []
self._child_container_classes = OrderedDict([])
self._child_list_classes = OrderedDict([("port", ("port", Ip.ForwardProtocol.Udp.Ports.Port))])
self._leafs = OrderedDict()
self.port = YList(self)
self._segment_path = lambda: "ports"
self._absolute_path = lambda: "Cisco-IOS-XR-ip-tcp-cfg:ip/Cisco-IOS-XR-ip-udp-cfg:forward-protocol/udp/%s" % self._segment_path()
def __setattr__(self, name, value):
self._perform_setattr(Ip.ForwardProtocol.Udp.Ports, [], name, value)
class Port(Entity):
"""
Well\-known ports are enabled by default and
non well\-known ports are disabled by default.
It is not allowed to configure the default.
.. attribute:: port_id (key)
Port number
**type**\: int
**range:** 1..65535
.. attribute:: enable
Specify 'false' to disable well\-known ports Domain (53), TFTP (69), NameServer (42), TACACS (49), NetBiosNameService (137), or NetBiosDatagramService (138). Specify 'true' to enable non well\-known ports
**type**\: bool
**mandatory**\: True
"""
_prefix = 'ip-udp-cfg'
_revision = '2017-07-31'
def __init__(self):
super(Ip.ForwardProtocol.Udp.Ports.Port, self).__init__()
self.yang_name = "port"
self.yang_parent_name = "ports"
self.is_top_level_class = False
self.has_list_ancestor = False
self.ylist_key_names = ['port_id']
self._child_container_classes = OrderedDict([])
self._child_list_classes = OrderedDict([])
self._leafs = OrderedDict([
('port_id', YLeaf(YType.uint16, 'port-id')),
('enable', YLeaf(YType.boolean, 'enable')),
])
self.port_id = None
self.enable = None
self._segment_path = lambda: "port" + "[port-id='" + str(self.port_id) + "']"
self._absolute_path = lambda: "Cisco-IOS-XR-ip-tcp-cfg:ip/Cisco-IOS-XR-ip-udp-cfg:forward-protocol/udp/ports/%s" % self._segment_path()
def __setattr__(self, name, value):
self._perform_setattr(Ip.ForwardProtocol.Udp.Ports.Port, ['port_id', 'enable'], name, value)
def clone_ptr(self):
self._top_entity = Ip()
return self._top_entity
| 42.361589 | 293 | 0.451038 |
0f411e0daf137115e863f6edac5e9e7d40227cf0 | 43 | lua | Lua | ftplugin/yaml.lua | brainplot/nvim | 34726d41027575e02fe6d1a30fe187bdd5cf8bbe | [
"MIT"
] | 1 | 2020-07-21T12:23:02.000Z | 2020-07-21T12:23:02.000Z | ftplugin/yaml.lua | brainplot/nvim | 34726d41027575e02fe6d1a30fe187bdd5cf8bbe | [
"MIT"
] | null | null | null | ftplugin/yaml.lua | brainplot/nvim | 34726d41027575e02fe6d1a30fe187bdd5cf8bbe | [
"MIT"
] | 2 | 2020-05-05T01:04:00.000Z | 2020-07-21T08:04:43.000Z | vim.bo.tabstop = 2
vim.bo.expandtab = true
| 14.333333 | 23 | 0.72093 |
fb44d185d7370f3049acf65122bfa9e3e2b361c7 | 369 | h | C | matrix/mat_ones_kernel.h | YeonwooSung/DNN_Builder | b009aaca55665f581276b024b570744db7f72358 | [
"MIT"
] | null | null | null | matrix/mat_ones_kernel.h | YeonwooSung/DNN_Builder | b009aaca55665f581276b024b570744db7f72358 | [
"MIT"
] | null | null | null | matrix/mat_ones_kernel.h | YeonwooSung/DNN_Builder | b009aaca55665f581276b024b570744db7f72358 | [
"MIT"
] | null | null | null | #include <cuda_runtime.h>
#ifndef _mat_ones_kernel_
#define _mat_ones_kernel_
__global__ void mat_ones_kernel (const float * __restrict__ src,
float * __restrict__ dst, int m, int n);
#ifdef __cplusplus
extern "C" {
#endif
void mat_ones_kernel_exec(const float *src, float *dst, int m, int n);
#ifdef __cplusplus
};
#endif
#endif
| 21.705882 | 74 | 0.691057 |
f083521712fdd7bcc50f7023b5b94d04976a33ac | 1,121 | js | JavaScript | pc_project/js/demo1.js | 1033291362/html-css-js | 4e17e843d8e4197d74c33ad78955768d8e1c3e6b | [
"MIT"
] | null | null | null | pc_project/js/demo1.js | 1033291362/html-css-js | 4e17e843d8e4197d74c33ad78955768d8e1c3e6b | [
"MIT"
] | null | null | null | pc_project/js/demo1.js | 1033291362/html-css-js | 4e17e843d8e4197d74c33ad78955768d8e1c3e6b | [
"MIT"
] | null | null | null | $(function(){
//首页链接
$(".t_bottom li").click(function(){
var index = $(".t_bottom li").index(this);
$(".t_bottom li").css({
"background":"#1a8fcb"
})
$(".t_bottom li").eq(index).css({
"background":"#00cc33"
})
})
//主页面图片切换
var user = {};
user.time = null;
index = 0;
user.pic=[
"img/1.jpg",
"img/2.jpg",
"img/3.jpg",
"img/4.jpg",
]
$(".but li").eq(0).css({
"background":"#ffd306"
})
exec(0)
var test = setInterval(function(){
index++;
if(index>user.pic.length-1)index=0;
exec(index);
},3000)
function exec(index){
$(".pic li").stop(true,true).css({
"background":"url("+user.pic[index]+") no-repeat",
"background-size":"1680px",
"opacity":"0"
}).animate({
"opacity":"1"
},1000)
$(".but li").css({
"background":"#1a8fcb"
})
$(".but li").eq(index).css({
"background":"#ffd306"
})
}
$(".but li").mouseover(function(){
clearInterval(test);
index = $(".but li").index(this);
exec(index);
}).mouseout(function(){
test = setInterval(function(){
index++;
if(index>user.pic.length-1)index=0;
exec(index);
},3000)
})
}) | 18.683333 | 53 | 0.553078 |
40862d825ecfa36e98ae5a3ba1c02f58d5ccfa19 | 3,709 | swift | Swift | X10 Pelmanism/Pelmanism/GameScene.swift | JulesMoorhouse/100DaysOfSwift | 2435fefb42ca00e152ca954de2a3ec7e3d8dc2ee | [
"MIT"
] | 1 | 2019-08-12T08:24:55.000Z | 2019-08-12T08:24:55.000Z | X10 Pelmanism/Pelmanism/GameScene.swift | JulesMoorhouse/100DaysOfSwift | 2435fefb42ca00e152ca954de2a3ec7e3d8dc2ee | [
"MIT"
] | null | null | null | X10 Pelmanism/Pelmanism/GameScene.swift | JulesMoorhouse/100DaysOfSwift | 2435fefb42ca00e152ca954de2a3ec7e3d8dc2ee | [
"MIT"
] | null | null | null | //
// GameScene.swift
// Pelmanism
//
// Created by Julian Moorhouse on 10/09/2019.
// Copyright © 2019 Mindwarp Consultancy Ltd. All rights reserved.
//
import GameplayKit
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var cards = [PlayingCard]()
var wonGame: MessageNode!
var symbols: [String] = ["😂", "🥰", "😎", "🤓", "🤩", "😂", "😤", "🤯", "🤬", "😱", "😍", "😆"]
var cardSymbols: [String] = []
override func didMove(to view: SKView) {
backgroundColor = UIColor(red: 0.3961, green: 0.698, blue: 0, alpha: 1.0)
symbols.shuffle()
cardSymbols += symbols
symbols.shuffle()
cardSymbols += symbols
createPlayingCards()
physicsWorld.contactDelegate = self
wonGame = MessageNode(color: .yellow, size: CGSize(width: 400, height: 110))
wonGame.position = CGPoint(x: (size.width / 2), y: (size.height / 2))
wonGame.setup(message: "You Won!",fontSize: 80)
wonGame.zPosition = 5
}
func createPlayingCards() {
var counter: Int = 0
var blue = UIColor(red: 0, green: 0.5569, blue: 0.8784, alpha: 1.0)
for currentX in stride(from: 255, to: CGFloat(size.width - 50), by: 125) {
for currentY in stride(from: 175, to: CGFloat(size.height - 50), by: 175) {
let size = CGSize(width: 100, height: 150)
let card = PlayingCard(color: blue, size: size)
// from centre
card.position = CGPoint(x: currentX - (size.width / 2), y: currentY - (size.height / 2))
card.setup(symbol: cardSymbols[counter])
addChild(card)
cards.append(card)
counter += 1
}
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let location = touch.location(in: self)
let tappedNodes = nodes(at: location)
for node in tappedNodes {
guard let item = node as? PlayingCard else { continue }
if item.faceUp == true {
continue
}
if totalFaceUpCards() == 2 {
resetCards()
}
if item.name == "playingCard" {
print("Tapped card")
item.flip()
}
if totalFaceUpCards() == 2 {
if cardsMatch() {
//
}
}
}
}
func totalFaceUpCards() -> Int {
let count = cards.filter { $0.faceUp == true }.count
print("totalFaceUpCards=\(count)")
return count
}
func resetCards() {
for card in cards {
if card.faceUp == true {
card.flip()
}
}
}
func cardsMatch() -> Bool {
let theseCards = cards.filter { $0.faceUp == true }
if theseCards.count == 2 {
if theseCards[0].cardSymbol == theseCards[1].cardSymbol {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.cards.removeAll(where: { $0.cardSymbol == theseCards[0].cardSymbol && $0.faceUp == true })
theseCards[0].removeFromParent()
theseCards[1].removeFromParent()
if self.cards.count == 0 {
self.addChild(self.wonGame)
}
}
return true
}
}
return false
}
}
| 31.432203 | 115 | 0.489889 |
9ec93f28b4296098ac849583156968f3623de761 | 1,633 | rs | Rust | christmastree/src/main.rs | Braafisch/rust-sandbox | aff6e343a46d7a6bb055478089dbfc7db52c6f88 | [
"Unlicense"
] | null | null | null | christmastree/src/main.rs | Braafisch/rust-sandbox | aff6e343a46d7a6bb055478089dbfc7db52c6f88 | [
"Unlicense"
] | null | null | null | christmastree/src/main.rs | Braafisch/rust-sandbox | aff6e343a46d7a6bb055478089dbfc7db52c6f88 | [
"Unlicense"
] | null | null | null | use clap::{App, Arg};
struct ChristmasTree {
height: u32,
has_star: bool,
}
impl ChristmasTree {
fn draw(&self) {
if self.has_star {
self.draw_star();
}
self.draw_tree();
self.draw_trunk();
}
fn draw_star(&self) {
self.output("*");
}
fn draw_tree(&self) {
for i in 0..self.height {
let level_width = (i * 2 + 1) as usize;
self.output(&std::iter::repeat("X").take(level_width).collect::<String>());
}
}
fn draw_trunk(&self) {
self.output("I")
}
fn output(&self, a: &str) {
println!("{}", format!("{: ^1$}", a, self.width() as usize));
}
fn width(&self) -> u32 {
self.height * 2 - 1
}
}
fn main() {
let matches = App::new("christmastree")
.version("0.1.0")
.author("wolfi")
.about("prints a pretty christmas tree (merry christmas!)")
.arg(
Arg::with_name("withStar")
.short("w")
.long("--withStar")
.help("add a little start on-top"),
)
.arg(
Arg::with_name("height")
.value_name("HEIGHT")
.index(1)
.required(true)
.help("height of the tree"),
)
.get_matches();
let tree = ChristmasTree {
height: matches
.value_of("height")
.expect("Missing argument HEIGHT")
.parse::<u32>()
.expect("Unable to parse integer"),
has_star: matches.is_present("withStar"),
};
tree.draw();
}
| 22.680556 | 87 | 0.469688 |
f1dac3ad8681849a5b795b4642381141876570db | 193 | rb | Ruby | app/policies/result_policy.rb | MIT-IR/abet | 53d46c394fcdd7832735e78b056b5bac6b3f4c6f | [
"MIT"
] | 4 | 2016-10-13T19:30:11.000Z | 2018-07-29T08:47:02.000Z | app/policies/result_policy.rb | MIT-IR/abet | 53d46c394fcdd7832735e78b056b5bac6b3f4c6f | [
"MIT"
] | 156 | 2015-06-03T13:55:36.000Z | 2017-07-06T20:39:53.000Z | app/policies/result_policy.rb | MIT-IR/abet | 53d46c394fcdd7832735e78b056b5bac6b3f4c6f | [
"MIT"
] | 3 | 2015-06-02T21:20:44.000Z | 2018-04-12T18:44:04.000Z | class ResultPolicy < ApplicationPolicy
def create?
user.manage_results?(record.assignment.subject_department)
end
def update?
create?
end
def destroy?
create?
end
end
| 13.785714 | 62 | 0.715026 |
bd8dfd8db80900f9a24760865ec8b2661cdd3f9f | 7,333 | rs | Rust | util/src/date/mod.rs | SimonOsaka/rust-web-server-example | 624bc0091c5feb06c7abb4d7842cffcf1f25f9c5 | [
"MIT"
] | 5 | 2022-01-04T01:51:25.000Z | 2022-01-30T10:20:04.000Z | util/src/date/mod.rs | SimonOsaka/rust-web-server-example | 624bc0091c5feb06c7abb4d7842cffcf1f25f9c5 | [
"MIT"
] | null | null | null | util/src/date/mod.rs | SimonOsaka/rust-web-server-example | 624bc0091c5feb06c7abb4d7842cffcf1f25f9c5 | [
"MIT"
] | 1 | 2021-12-16T09:59:41.000Z | 2021-12-16T09:59:41.000Z | pub mod error;
pub mod format;
pub mod timezone;
use time::{format_description, OffsetDateTime, UtcOffset};
use self::{
error::DateError,
format::{
FORMAT_PATTERN_DAY, FORMAT_PATTERN_HOUR, FORMAT_PATTERN_MINUTE, FORMAT_PATTERN_MONTH,
FORMAT_PATTERN_SECOND, FORMAT_PATTERN_YEAR, FORMAT_PATTERN_YMD_HMS_TZ,
},
};
pub type DateResult = Result<OffsetDateTime, DateError>;
pub type DateStringResult = Result<String, DateError>;
/// `OffsetDateTime`'s util
/// - Format `OffsetDateTime` to String
/// - Parse String to `OffsetDateTime`
#[derive(Debug, Clone)]
pub struct Date;
impl Date {
/// get utc `OffsetDateTime`
#[cfg(not(feature = "local"))]
pub fn get_now() -> DateResult {
Ok(OffsetDateTime::now_utc())
}
/// get local `OffsetDateTime`
#[cfg(any(feature = "local"))]
pub fn get_now() -> DateResult {
use self::timezone::TIMEZONE;
Self::get_now_with_tz(TIMEZONE.0, TIMEZONE.1)
}
/// now unix timestamp
pub fn get_now_unix_timestamp() -> Result<i64, DateError> {
Ok(Self::get_now()?.unix_timestamp())
}
/// from `timestamp` to `OffsetDateTime`
pub fn from_unix_timestamp(ts: i64) -> DateResult {
OffsetDateTime::from_unix_timestamp(ts).map_err(|e| DateError::FormatRange { e })
}
/// get datetime with timezone
pub fn get_now_with_tz(hour: i8, minute: u8) -> DateResult {
Ok(OffsetDateTime::now_utc().to_offset(
UtcOffset::from_hms(hour, minute as i8, 0).map_err(|e| DateError::FormatRange { e })?,
))
}
/// format any datetime and pattern
///
/// ```
/// [year]-[month]-[day] [hour]:[minute]:[second] [offset_hour sign:mandatory]:[offset_minute]:[offset_second]
/// ```
pub fn format_with(odt: OffsetDateTime, fmt: &str) -> DateStringResult {
let f = format_description::parse(fmt)
.map_err(|e| DateError::FormatInvalid { fmt: fmt.into(), e })?;
odt.format(&f).map_err(|e| DateError::Format { e })
}
/// format year
///
/// ```
/// [year]
/// ```
pub fn format_with_year(odt: OffsetDateTime) -> DateStringResult {
Self::format_with(odt, FORMAT_PATTERN_YEAR)
}
/// format month
///
/// ```
/// [month]
/// ```
pub fn format_with_month(odt: OffsetDateTime) -> DateStringResult {
Self::format_with(odt, FORMAT_PATTERN_MONTH)
}
/// format day
///
/// ```
/// [day]
/// ```
pub fn format_with_day(odt: OffsetDateTime) -> DateStringResult {
Self::format_with(odt, FORMAT_PATTERN_DAY)
}
/// format year:month:day
///
/// ```
/// [year]-[month]-[day]
/// ```
pub fn format_with_ymd(odt: OffsetDateTime) -> DateStringResult {
Ok(format!(
"{}-{}-{}",
Self::format_with_year(odt)?,
Self::format_with_month(odt)?,
Self::format_with_day(odt)?
))
}
/// format hour
///
/// ```
/// [hour]
/// ```
pub fn format_with_hour(odt: OffsetDateTime) -> DateStringResult {
Self::format_with(odt, FORMAT_PATTERN_HOUR)
}
/// format minute
///
/// ```
/// [minute]
/// ```
pub fn format_with_minute(odt: OffsetDateTime) -> DateStringResult {
Self::format_with(odt, FORMAT_PATTERN_MINUTE)
}
/// format second
///
/// ```
/// [second]
/// ```
pub fn format_with_second(odt: OffsetDateTime) -> DateStringResult {
Self::format_with(odt, FORMAT_PATTERN_SECOND)
}
/// format hour:minute:second
///
/// ```
/// [hour]:[minute]:[second]
/// ```
pub fn format_with_hms(odt: OffsetDateTime) -> DateStringResult {
Ok(format!(
"{}:{}:{}",
Self::format_with_hour(odt)?,
Self::format_with_minute(odt)?,
Self::format_with_second(odt)?
))
}
/// format year-month-day hour:minute:second
///
/// ```
/// '[year]-[month]-[day] [hour]:[minute]:[second]'
/// ```
pub fn format_with_ymd_hms(odt: OffsetDateTime) -> DateStringResult {
Ok(format!(
"{} {}",
Self::format_with_ymd(odt)?,
Self::format_with_hms(odt)?
))
}
/// parse date string with given pattern to OffsetDateTime
///
/// ```
/// "[year]-[month]-[day] [hour]:[minute]:[second] [offset_hour sign:mandatory]:[offset_minute]"
/// "2022-07-01 02:30:57 +00:30"
/// ```
pub fn parse_with(date_str: &str, pattern: &str) -> DateResult {
let format = format_description::parse(pattern).map_err(|e| {
DateError::ParseInvalidPatternError {
pattern: pattern.into(),
e,
}
})?;
OffsetDateTime::parse(date_str, &format).map_err(|e| DateError::ParseError {
pattern: pattern.into(),
e,
})
}
/// parse date and time string to OffsetDateTime
///
/// ```
/// Pattern: [year]-[month]-[day] [hour]:[minute]:[second]
/// Example: "2022-07-01 02:30:57"
/// ```
pub fn parse_with_ymd_hms(date_str: &str) -> DateResult {
Self::parse_with(
format!("{} {}", date_str, Self::gen_timezone()).as_str(),
FORMAT_PATTERN_YMD_HMS_TZ,
)
}
/// parse date string to OffsetDateTime
///
/// ```
/// Pattern: [year]-[month]-[day]
/// Example: "2022-07-01"
/// ```
pub fn parse_with_ymd(date_str: &str) -> DateResult {
Self::parse_with(
format!("{} 00:00:00 {}", date_str, Self::gen_timezone()).as_str(),
FORMAT_PATTERN_YMD_HMS_TZ,
)
}
#[cfg(not(feature = "local"))]
fn gen_timezone() -> String {
String::from("+00:00")
}
#[cfg(any(feature = "local"))]
fn gen_timezone() -> String {
use self::timezone::TIMEZONE;
let mut sign = "+";
let mut offset_hour = TIMEZONE.0;
if TIMEZONE.0 < 0 {
sign = "-";
offset_hour = -offset_hour;
}
format!("{sign}{0:0>2}:{1:0>2}", offset_hour, TIMEZONE.1)
}
}
#[cfg(test)]
mod tests {
use crate::Date;
#[test]
fn test_today() {
let now = Date::get_now();
println!("{now:?}");
let odt = now.unwrap();
println!("{odt}");
let s_date = Date::format_with_ymd(odt);
println!("{s_date:?}");
let s_time = Date::format_with_hms(odt);
println!("{s_time:?}");
let tz_date = Date::get_now_with_tz(25, 0);
println!("{tz_date:?}");
let s_ymd_hms = Date::format_with_ymd_hms(odt);
println!("{s_ymd_hms:?}");
}
#[test]
fn test_parse_with() {
let s_ymd_hms = Date::parse_with_ymd_hms("2022-05-11 18:15:12");
println!("{s_ymd_hms:?}");
let s_ymd_hms = Date::parse_with_ymd("2022-05-12");
println!("{s_ymd_hms:?}");
let s_ymd_hms = Date::parse_with(
"2022-05-11 00:00:00 +08:00",
"[year]-[month]-[day] [hour]:[minute]:[second] [offset_hour sign:mandatory]:[offset_minute]",
);
println!("{s_ymd_hms:?}");
}
#[test]
fn test_gen_timezone() {
let tz = Date::gen_timezone();
println!("{tz}");
}
}
| 27.464419 | 114 | 0.549707 |
2aa1a688cd9d6ae13f7772b6d3e9f633078c3f07 | 3,357 | sql | SQL | database/d_delete.sql | Guergeiro/bd2-group2 | 34520e40ef915dc7bb89486ac2322f8994ac9862 | [
"MIT"
] | null | null | null | database/d_delete.sql | Guergeiro/bd2-group2 | 34520e40ef915dc7bb89486ac2322f8994ac9862 | [
"MIT"
] | 12 | 2019-11-17T21:22:49.000Z | 2020-01-19T18:10:00.000Z | database/d_delete.sql | Guergeiro/bd2-group2 | 34520e40ef915dc7bb89486ac2322f8994ac9862 | [
"MIT"
] | 2 | 2019-11-15T16:47:21.000Z | 2019-11-17T13:59:40.000Z | -- Delete Clientes
CREATE OR REPLACE PROCEDURE deleteclientes(VARCHAR(10))
LANGUAGE plpgsql
AS $deleteclientes$
BEGIN
DELETE FROM clientes WHERE cod_cliente = $1;
END
$deleteclientes$;
-- Delete Consumos
CREATE OR REPLACE PROCEDURE deleteconsumos(VARCHAR(10))
LANGUAGE plpgsql
AS $deleteconsumos$
BEGIN
DELETE FROM consumos WHERE cod_consumo = $1;
END
$deleteconsumos$;
-- Delete Locais
CREATE OR REPLACE PROCEDURE deletelocais(VARCHAR(10))
LANGUAGE plpgsql
AS $deletelocais$
BEGIN
DELETE FROM locais WHERE cod_local = $1;
END
$deletelocais$;
-- Delete Restaurantes
CREATE OR REPLACE PROCEDURE deleterestaurantes(VARCHAR(10))
LANGUAGE plpgsql
AS $deleterestaurantes$
BEGIN
DELETE FROM restaurantes WHERE cod_restaurante = $1;
END
$deleterestaurantes$;
-- Delete Funcionarios
CREATE OR REPLACE PROCEDURE deletefuncionarios(VARCHAR(10))
LANGUAGE plpgsql
AS $deletefuncionarios$
BEGIN
DELETE FROM funcionarios WHERE cod_funcionario = $1;
END
$deletefuncionarios$;
-- Delete LocaisConsumo
CREATE OR REPLACE PROCEDURE deletelocaisconsumo(VARCHAR(10))
LANGUAGE plpgsql
AS $deletelocaisconsumo$
BEGIN
DELETE FROM locaisconsumo WHERE cod_localconsumo = $1;
END
$deletelocaisconsumo$;
-- Delete TiposEmenta
CREATE OR REPLACE PROCEDURE deletetiposementa(VARCHAR(10))
LANGUAGE plpgsql
AS $deletetiposementa$
BEGIN
DELETE FROM tiposementa WHERE cod_tipoementa = $1;
END
$deletetiposementa$;
-- Delete TiposItem
CREATE OR REPLACE PROCEDURE deletetipositem(VARCHAR(10))
LANGUAGE plpgsql
AS $deletetipositem$
BEGIN
DELETE FROM tipositem WHERE cod_tipoitem = $1;
END
$deletetipositem$;
-- Delete Itens
CREATE OR REPLACE PROCEDURE deleteitens(VARCHAR(10))
LANGUAGE plpgsql
AS $deleteitens$
BEGIN
DELETE FROM itens WHERE cod_item = $1;
END
$deleteitens$;
-- Delete DatasEmenta
CREATE OR REPLACE PROCEDURE deletedatasementa(VARCHAR(10))
LANGUAGE plpgsql
AS $deletedatasementa$
BEGIN
DELETE FROM datasementa WHERE cod_dataementa = $1;
END
$deletedatasementa$;
-- Delete TiposRefeicao
CREATE OR REPLACE PROCEDURE deletetiposrefeicao(VARCHAR(10))
LANGUAGE plpgsql
AS $deletetiposrefeicao$
BEGIN
DELETE FROM tiposrefeicao WHERE cod_tiporefeicao = $1;
END
$deletetiposrefeicao$;
-- Delete Ementas
CREATE OR REPLACE PROCEDURE deleteementas(VARCHAR(10))
LANGUAGE plpgsql
AS $deleteementas$
BEGIN
DELETE FROM ementas WHERE cod_ementa = $1;
END
$deleteementas$;
-- Delete Alergias
CREATE OR REPLACE PROCEDURE deletealergias(VARCHAR(10))
LANGUAGE plpgsql
AS $deletealergias$
BEGIN
DELETE FROM alergias WHERE cod_alergia = $1;
END
$deletealergias$;
-- Delete EmentasItens
CREATE OR REPLACE PROCEDURE deleteementasitens(VARCHAR(10), VARCHAR(10))
LANGUAGE plpgsql
AS $deleteementasitens$
BEGIN
DELETE FROM ementasitens WHERE cod_ementa = $1 AND cod_item = $1;
END
$deleteementasitens$;
-- Delete ItensAlergias
CREATE OR REPLACE PROCEDURE deleteitensalergias(VARCHAR(10), VARCHAR(10))
LANGUAGE plpgsql
AS $deleteitensalergias$
BEGIN
DELETE FROM itensalergias WHERE cod_item = $1 AND cod_alergia = $2;
END
$deleteitensalergias$;
-- Delete ItensAlergias
CREATE OR REPLACE PROCEDURE deleteconsumosementas(VARCHAR(10), VARCHAR(10))
LANGUAGE plpgsql
AS $deleteconsumosementas$
BEGIN
DELETE FROM consumosementas WHERE cod_consumo = $1 AND cod_ementa = $2;
END
$deleteconsumosementas$;
| 19.073864 | 75 | 0.786416 |
0a1654e9bd673a58672b2fcf2c627e810704a509 | 695 | tsx | TypeScript | example/App.tsx | lastmagic/flax | b894d695ac307fd54bc26cf61f0f9b15e9e60ec1 | [
"MIT"
] | 3 | 2021-03-18T09:51:38.000Z | 2022-02-15T09:09:57.000Z | example/App.tsx | lastmagic/flax | b894d695ac307fd54bc26cf61f0f9b15e9e60ec1 | [
"MIT"
] | 3 | 2020-12-14T07:57:58.000Z | 2020-12-15T14:00:07.000Z | example/App.tsx | lastmagic/flax | b894d695ac307fd54bc26cf61f0f9b15e9e60ec1 | [
"MIT"
] | 3 | 2020-12-14T07:37:44.000Z | 2021-10-06T09:24:59.000Z | import React from 'react';
import {Link, Route, BrowserRouter, Switch} from 'react-router-dom';
import {Main} from './Main';
import {Page} from './Page';
import {PageChild} from './PageChild';
export function App() {
return (
<>
<BrowserRouter>
<div id="App">
<Link to="/">Main</Link> / <Link to="/page">Page</Link> /{' '}
<Link to="/page/child">Page Child</Link>
<hr />
<Switch>
<Route exact path="/" component={Main} />
<Route exact path="/page" component={Page} />
<Route exact path="/page/child" component={PageChild} />
</Switch>
</div>
</BrowserRouter>
</>
);
}
| 27.8 | 72 | 0.530935 |
dfa8eb0ef043732ccec94614a131f5acdaef0d83 | 2,999 | lua | Lua | Users/Shared/Binaries/stardust.lua | thesharpdev/Fuchas | 8941e8115e5c5ff63ad32184533c60fee7b27ee0 | [
"MIT"
] | null | null | null | Users/Shared/Binaries/stardust.lua | thesharpdev/Fuchas | 8941e8115e5c5ff63ad32184533c60fee7b27ee0 | [
"MIT"
] | null | null | null | Users/Shared/Binaries/stardust.lua | thesharpdev/Fuchas | 8941e8115e5c5ff63ad32184533c60fee7b27ee0 | [
"MIT"
] | null | null | null | local fs = require("filesystem")
local shell = require("shell")
local sec = require("security")
-- Free some memory
if package.loaded["OCX/OCDraw"] then
require("OCX/OCDraw").requestMemory()
end
if not sec.requestPermission("component.unrestricted") then
io.stderr:write("Stardust programs requires unrestricted access to components (admin access).\n")
return
end
local args, flags = shell.parse(...)
if #args < 1 then
io.stderr:write("Usage: stardust <path to OpenOS program>\n")
return
end
local path = shell.resolve(args[1])
if path == nil then
io.stderr:write(args[1] .. " doesn't exists\n")
return
end
--[[for k, v in pairs(package.loaded) do
if k:sub(1, 8) == "stardust" then
package.loaded[k] = nil
end
end]]
local libs = {
component = require("component").unrestricted,
computer = require("stardust/computer"),
filesystem = require("stardust/filesystem"), -- no porting necessary.. yet
colors = require("stardust/colors"),
unicode = _G.unicode,
io = require("stardust/io"),
rc = require("stardust/rc"),
sides = require("stardust/sides"),
os = require("stardust/os"),
term = require("stardust/term"),
serialization = require("stardust/serialization"),
text = require("stardust/text"),
event = require("event"), -- TODO: re-implement
buffer = require("buffer") -- TODO: re-implement
}
local function req(name)
if libs[name] then
return libs[name]
else
return require(name)
end
end
local function loadfile(path)
local file, reason = require("stardust/filesystem").open(path, "r")
if not file then
return nil, reason
end
local buffer = ""
local data, reason = "", ""
while data do
data, reason = file:read(math.huge)
buffer = buffer .. (data or "")
end
file:close()
return load(buffer, "=" .. path, "bt", _G)
end
local function dofile(file, ...)
local program, reason = loadfile(file)
if program then
return program(...)
else
error(reason)
end
end
local env = {
require = req,
_OSVERSION = "OpenOS 1.7.5",
io = require("stardust/io"),
math = _G.math,
coroutine = _G.coroutine,
bit32 = _G.bit32,
string = _G.string,
table = _G.table,
unicode = _G.unicode,
debug = _G.debug,
assert = _G.assert,
error = _G.error,
getmetatable = _G.getmetatable,
ipairs = _G.ipairs,
load = _G.load,
next = _G.next,
pairs = _G.pairs,
pcall = _G.pcall,
rawequal = _G.rawequal,
rawget = _G.rawget,
rawlen = _G.rawlen,
rawset = _G.rawset,
select = _G.select,
setmetatable = _G.setmetatable,
tonumber = _G.tonumber,
tostring = _G.tostring,
type = _G.type,
xpcall = _G.xpcall,
print = _G.print,
loadfile = loadfile,
dofile = dofile
}
local handle = io.open(path)
local code = handle:read("a")
handle:close()
local f, err = load(code, args[1], "bt", env)
table.remove(args, 1)
if f then
xpcall(f, debug.traceback, args)
else
error(err)
end
-- Cleanup: the OpenOS program might have messed up with GPU which in turns mess up with driver optimizations
component.gpu.setForeground(0xFFFFFF)
component.gpu.setBackground(0)
| 22.548872 | 109 | 0.694231 |
12c60798d7f4d181b9c4c69ef5dd5eb854aacf8a | 13,534 | html | HTML | _site/index.html | fjbautistas/fjbautistas.github.io | 59d01ec90c87309b92f6d9549b198f1fd5743ee8 | [
"MIT"
] | null | null | null | _site/index.html | fjbautistas/fjbautistas.github.io | 59d01ec90c87309b92f6d9549b198f1fd5743ee8 | [
"MIT"
] | null | null | null | _site/index.html | fjbautistas/fjbautistas.github.io | 59d01ec90c87309b92f6d9549b198f1fd5743ee8 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="en"><head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Frank Bautista | Physicist.</title><!-- Begin Jekyll SEO tag v2.6.1 -->
<meta name="generator" content="Jekyll v3.9.0" />
<meta property="og:title" content="Physicist." />
<meta property="og:locale" content="en_US" />
<link rel="canonical" href="http://localhost:4000/" />
<meta property="og:url" content="http://localhost:4000/" />
<meta property="og:site_name" content="Physicist." />
<script type="application/ld+json">
{"url":"http://localhost:4000/","@type":"WebSite","headline":"Physicist.","name":"Physicist.","@context":"https://schema.org"}</script>
<!-- End Jekyll SEO tag -->
<link rel="stylesheet" href="/assets/main.css">
<link rel="shortcut icon" type="image/x-icon" href="/assets/favicon.ico"></head>
<body class="dark"><div class="container header-contianer">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-8 header-left">
<h1>Frank Bautista</h1>
<h2>Physicist.</h2>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4 header-right">
<ul class="icons no-print"><li>
<a target="_blank" href="https://github.com/fjbautistas" class="button button--sacnite button--round-l">
<i class="fab fa-github" title="Github link"></i>
</a>
</li><li>
<a target="_blank" href="https://www.instagram.com/fjbautistas" class="button button--sacnite button--round-l">
<i class="fab fa-instagram" title="Instagram link"></i>
</a>
</li><li>
<a target="_blank" href="https://www.linkedin.com/in/fjbautistas" class="button button--sacnite button--round-l">
<i class="fab fa-linkedin" title="Linkedin link"></i>
</a>
</li><li>
<a target="_blank" href="https://twitter.com/fjbautistas" class="button button--sacnite button--round-l">
<i class="fab fa-twitter" title="Twitter link"></i>
</a>
</li>
</ul><p>
Email: <a href="mailto:fjbautistas@unal.edu.co" target="_blank">fjbautistas@unal.edu.co</a>
</p><p>
Phone: (+57) 318 5022890
</p><p>
Web:
<a href="https://fjbautistas.github.io/" target="_blank" class="">https://fjbautistas.github.io/</a>
</p></div>
</div>
</div>
<main class="page-content" aria-label="Content">
<div class="wrapper"><div class="container intro-container">
<h3>About Me</h3>
<div class="row clearfix"><div class="col-xs-12 col-sm-4 col-md-3 no-print">
<span class="profile-img" style="background-image: url(/images/prof.jpg)"></span>
</div><div class="col-xs-12 col-sm-8 col-md-9 col-print-12">
<p>I’m a physicist and candidate of Master of Sciences in physics from the Universidad Nacional de Colombia, currently living in Bogotá D. C. I have experience in nuclear physics (theoretical and experimental). Also, I have over two years using machine learning methods and Bayesian inference. I want to apply all of this to practical physics projects.</p>
<p>My professional interests include nuclear physics, nuclear instrumentation, data analysis, bayesian inferences and, astronomy and software development in general.</p>
</div>
</div>
</div>
<div class="container list-container">
<h3>Experience</h3>
<div class="row clearfix layout layout-right">
<div class="col-xs-12 col-sm-4 col-md-3 col-print-12 details">
<h4>Servicio Geológico Colombiano (SGC)</h4><p><b>Regulatory Inspector</b></p><p>October 2018 - present</p>
<a href="https://www.sgc.gov.co/" target="_blank" class="link">https://www.sgc.gov.co/</a><p class="no-print aditional-links">
</p>
</div>
<div class="col-xs-12 col-sm-8 col-md-9 col-print-12 content"><p class="quote">Physicist
</p><p>Inspector of the regulatory authority in Colombia for the correct handling of radioactive materials in industry, medicine and science.</p>
<ul>
<li>Carry out technical guides and scientific reports.</li>
<li>Conduct inspection visits to verify the conditions, security and correct use of radiactive materials.</li>
</ul>
</div>
</div>
<div class="row clearfix layout layout-right">
<div class="col-xs-12 col-sm-4 col-md-3 col-print-12 details">
<h4>Universidad Nacional de Colombia</h4><p><b>Junior research</b></p><p>October 2018 - present</p>
<a href="//gfnun.unal.edu.co/" target="_blank" class="link">gfnun.unal.edu.co/</a><p class="no-print aditional-links">
</p>
</div>
<div class="col-xs-12 col-sm-8 col-md-9 col-print-12 content"><p class="quote">Physicist
</p><p>Study of the environmental impact of 131 I and 99m Tc, in waste water from the Central Police Hospital of Colombia.</p>
<ul>
<li>Using an HPGe detector with a fixed experimental geometry to determine the sample activity and the concentrations in ppm.</li>
<li>Carried out experimental sets up to obtain different volume of samples.</li>
<li>Software development for data analysis.</li>
</ul>
</div>
</div>
<div class="row clearfix layout layout-right">
<div class="col-xs-12 col-sm-4 col-md-3 col-print-12 details">
<h4>Universidad Nacional de Colombia</h4><p><b>Junior research</b></p><p>October 2018 - present</p>
<a href="//gfnun.unal.edu.co/" target="_blank" class="link">gfnun.unal.edu.co/</a><p class="no-print aditional-links">
</p>
</div>
<div class="col-xs-12 col-sm-8 col-md-9 col-print-12 content"><p class="quote">Junior research
</p><p>Design of new analytic methods for $\gamma$ spectroscopy applied to basic research focused on:</p>
<ul>
<li>Software development for gamma spectroscopy analyses employing C++ and Python.</li>
<li>Characterization of efficiency and resoluction for HPGe detectors, scintillator detectors such as NaI(2x2), NaI(3x3), CsI(2x2), BGO(2x2) detectors, among others.</li>
<li>Modeling of extended source and position optimization for HPGe detector.</li>
</ul>
</div>
</div>
</div>
<div class="container list-container">
<h3>Education</h3>
<div class="row clearfix layout layout-left">
<div class="col-xs-12 col-sm-4 col-md-3 col-print-12 details">
<h4>Universidad Nacional de Colombia</h4><p><b>M.Sc. in Physics</b></p><p>2018 - present</p><p class="no-print aditional-links">
</p>
</div>
<div class="col-xs-12 col-sm-8 col-md-9 col-print-12 content"><p class="quote">Master of Science candidate
</p><p>Two year master’s degree candidate at the top-1 <a href="https://www.topuniversities.com/universities/universidad-nacional-de-colombia/undergrad">university</a> in Colombia. I used machine learning and bayesian inference to determine phycical characteristics of exoplanetary systems. Currently, I am writing the thesis <em>Bayesian constraints on observable properties of exoplanetary systems using planet population synthesis simulations.</em></p>
</div>
</div>
<div class="row clearfix layout layout-left">
<div class="col-xs-12 col-sm-4 col-md-3 col-print-12 details">
<h4>Universidad Nacional de Colombia</h4><p><b>B.Sc. in Physics</b></p><p>2011 - 2017</p><p class="no-print aditional-links">
</p>
</div>
<div class="col-xs-12 col-sm-8 col-md-9 col-print-12 content"><p class="quote">Bachelor's degree
</p><p>Bachelor degree in Physics, at the top-1 <a href="https://www.topuniversities.com/universities/universidad-nacional-de-colombia/undergrad">university</a> in Colombia. I wrote a thesis on experimental nuclear physics: <em>Comparison of measurements of NORM by gamma ray spectroscopy using detectors of Ge, CsI, NaI, and BGO</em>, in the Nuclear Physics Group (GFNUN).</p>
</div>
</div>
</div>
<div class="container text-container">
<h3>Research products</h3>
<div class="row clearfix">
<div class="col-md-12">
<p>Here are some academic contributions that I have made across time. They are arranged chronologically and by relevance (paper, talk, poster,…).</p>
<ul>
<li><strong>Publications</strong>:
<ul>
<li>G. Chaparro Molano, F. Bautista, Y. Miguel. (2019). <a href="https://arxiv.org/abs/1901.07078#:~:text=Transitional%20disk%20archeology%20from%20exoplanet%20population%20synthesis,-Germ%C3%A1n%20Chaparro%20Molano&text=Increasingly%20better%20observations%20of%20resolved,interpreted%20as%20signatures%20of%20planets.">Transitional disk archeology from exoplanet population synthesis</a>, <em>Proceedings IAU Symposium No. 345.</em></li>
<li>P. Ochoa, F. Bautista, E. Fajardo, W. Rodriguez, F. Cristancho. (2018). <a href="https://inis.iaea.org/search/search.aspx?orig_q=RN:50004883">Measuring activity concentrations using a High Purity Germanium detector: Extended source efficiency correction and optimization of sample position</a>, <em>NORM-VIII, International Atomic Energy Agency (IAEA).</em></li>
</ul>
</li>
<li><strong>Summer schools</strong>:
<ul>
<li><a href="https://nucleartalent.github.io/Bayes2019/">Learning from Data: Bayesian Methods and Machine Learning. Training in Advance Low Energy Nuclear Theorys</a>. University of York, York, U.K., 2019.</li>
</ul>
<p>Contribution: <em>Bayesian Model Evaluation of a Gaussian Mixture Classification of Exoplanetary Systems.</em></p>
<ul>
<li><a href="http://www.sbfisica.org.br/~evjasfne/xx/index.php/pt/2-uncategorised/32-grupo-c">XX Summer School Jorge André Swieca on Experimental Nuclear Physics</a>. Universidad de Sao Paulo, Sao Paulo, Brasil, 2018.</li>
</ul>
<p>Contribution: <em>Comparison of measurement of NORM by gamma-ray spectroscopy.</em></p>
</li>
<li><strong>Participation in events</strong>:
<ul>
<li>
<p><a href="https://as595.github.io/RADABigData/">RADA Big Data Workshop</a>, Medellín, Colombia, 2019.</p>
<p>Contribution: <em>Machine Learning Classification of Pulsar Candidates</em>, ASTRO-PROJECT group.</p>
</li>
<li>
<p><a href="https://www.rad2017.rad-conference.org/welcome.php">Fifth International Conference on Radiation and Applications in Various Fields of Research - RAD</a>, Budva, Montenegro, 2017.</p>
<p>Contribution: <em>Comparison of measurement of NORM by gamma-ray spectroscopy using detectors of HPGe, CsI, NaI and BGO.</em></p>
</li>
<li>
<p><a href="http://gfnun.unal.edu.co/index.php?id=xi-lasnpa&L=4">The 11th Latin American Symposium on Nuclear Physics and Applications</a>, Medellín, Colombia, 2015.</p>
<p>Contribution: <em>Measurement of the concentration of natural radionuclides by γ-ray spectroscopy using a NaI detector</em></p>
</li>
<li>
<p><a href="http://gfnun.unal.edu.co/index.php?id=2864&L=4">Second Latinamerican School on Medical Physics</a>, Medellín, Colombia, 2015.</p>
</li>
<li>
<p><a href="http://www.gfnun.unal.edu.co/andeanschool/#:~:text=The%20aim%20of%20the%20%22Second,experimental%20studies%20in%20nuclear%20structure%2C&text=imaging%20techniques%20in%20medical%20physics,Research%20Reactors.">Second Andean School on Nuclear Physics</a>, Bogotá, Colombia, 2014.</p>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
<div class="container list-container">
<h3>Awards</h3>
<div class="row clearfix layout layout-top-right">
<div class="col-xs-12 col-sm-4 col-md-3 col-print-12 details">
<h4>Universidad Nacional de Colombia</h4><p><b>M.Sc. Scolarship</b></p><p>2018 - 2020</p><p class="no-print aditional-links">
</p>
</div>
<div class="col-xs-12 col-sm-8 col-md-9 col-print-12 content">
</div>
</div>
<div class="row clearfix layout layout-top-right">
<div class="col-xs-12 col-sm-4 col-md-3 col-print-12 details">
<h4>Universidad Nacional de Colombia</h4><p><b>Undergraduate Scolarship</b></p><p>2016 - 2017</p><p class="no-print aditional-links">
</p>
</div>
<div class="col-xs-12 col-sm-8 col-md-9 col-print-12 content">
</div>
</div>
</div>
<div class="container text-container">
<h3>A Little More About Me</h3>
<div class="row clearfix">
<div class="col-md-12">
<p>When I am not in the academic world, I enjoy reading, accompanied by a good coffee cup. The last book I read was <a href="https://www.amazon.com/Man-High-Castle-Philip-Dick/dp/0547572484">The Man in the High Castle</a>, an excellent novel. I hope to watch the TV serie soon.</p>
<p>I am a cycling enthusiast; I believe that riding a bicycle removes sorrows and worries. I ride my bike whenever I can.</p>
<p class="aligncenter">
<img src="/images/bici.jpg" alt="centered image" width="650" height="400" />
</p>
<p>I like photography, however I’m not very good but I keep practicing it. I love nature and animals, especially cats and my pets. You can follow me in my social networks.</p>
</div>
</div>
</div>
</div>
</main><div class="container footer-container">
<p>
Frank Bautista -
<a href="mailto:fjbautistas@unal.edu.co" target="_blank">fjbautistas@unal.edu.co</a> - References on request</p>
</div>
</body>
</html>
| 50.312268 | 455 | 0.664844 |
f038a863268c516819dbf950a745c99c6fc026b5 | 6,375 | py | Python | tutorials/03-advanced/image_captioning/model.py | xuwangyin/pytorch-tutorial | d6a29c19288c817432b3b101765596e037e01989 | [
"MIT"
] | 11 | 2017-08-20T18:12:34.000Z | 2020-03-18T18:03:16.000Z | tutorials/03-advanced/image_captioning/model.py | xuwangyin/pytorch-tutorial | d6a29c19288c817432b3b101765596e037e01989 | [
"MIT"
] | null | null | null | tutorials/03-advanced/image_captioning/model.py | xuwangyin/pytorch-tutorial | d6a29c19288c817432b3b101765596e037e01989 | [
"MIT"
] | 5 | 2017-08-10T05:15:37.000Z | 2021-12-01T08:23:30.000Z | import torch
import torch.nn as nn
import torchvision.models as models
from torch.nn.utils.rnn import pack_padded_sequence as pack
from torch.nn.utils.rnn import pad_packed_sequence as unpack
from torch.autograd import Variable
class EncoderCNN(nn.Module):
def __init__(self, embed_size):
"""Load the pretrained ResNet-152 and replace top fc layer."""
super(EncoderCNN, self).__init__()
resnet = models.resnet152(pretrained=True)
modules = list(resnet.children())[:-1] # delete the last fc layer.
self.resnet = nn.Sequential(*modules)
self.linear = nn.Linear(resnet.fc.in_features, embed_size)
self.bn = nn.BatchNorm1d(embed_size, momentum=0.01)
self.init_weights()
def init_weights(self):
"""Initialize the weights."""
self.linear.weight.data.normal_(0.0, 0.02)
self.linear.bias.data.fill_(0)
def forward(self, images):
"""Extract the image feature vectors."""
features = self.resnet(images)
features = Variable(features.data)
features = features.view(features.size(0), -1)
features = self.bn(self.linear(features))
return features
class LayoutEncoder(nn.Module):
def __init__(self, layout_encoding_size, hidden_size, vocab_size, num_layers):
"""Set the hyper-parameters and build the layers."""
super(LayoutEncoder, self).__init__()
self.label_encoder = nn.Embedding(vocab_size, layout_encoding_size)
self.location_encoder = nn.Linear(4, layout_encoding_size)
self.lstm = nn.LSTM(layout_encoding_size, hidden_size, num_layers, batch_first=True)
self.init_weights()
def init_weights(self):
"""Initialize weights."""
self.label_encoder.weight.data.uniform_(-0.1, 0.1)
self.location_encoder.weight.data.uniform_(-0.1, 0.1)
self.location_encoder.bias.data.fill_(0)
def forward(self, label_seqs, location_seqs, lengths):
# sort label sequences and location sequences in batch dimension according to length
batch_idx = sorted(range(len(lengths)), key=lambda k: lengths[k], reverse=True)
reverse_batch_idx = torch.LongTensor([batch_idx.index(i) for i in range(len(batch_idx))])
lens_sorted = sorted(lengths, reverse=True)
label_seqs_sorted = torch.index_select(label_seqs, 0, torch.LongTensor(batch_idx))
location_seqs_sorted = torch.index_select(location_seqs, 0, torch.LongTensor(batch_idx))
# assert torch.equal(torch.index_select(label_seqs_sorted, 0, reverse_batch_idx), label_seqs)
# assert torch.equal(torch.index_select(location_seqs_sorted, 0, reverse_batch_idx), location_seqs)
if torch.cuda.is_available():
reverse_batch_idx = reverse_batch_idx.cuda()
label_seqs_sorted = label_seqs_sorted.cuda()
location_seqs_sorted = location_seqs_sorted.cuda()
# create Variables
label_seqs_sorted_var = Variable(label_seqs_sorted, requires_grad=False)
location_seqs_sorted_var = Variable(location_seqs_sorted, requires_grad=False)
# encode label sequences
label_encoding = self.label_encoder(label_seqs_sorted_var)
# encode location sequences
location_seqs_sorted_var = location_seqs_sorted_var.view(-1, 4)
location_encoding = self.location_encoder(location_seqs_sorted_var)
location_encoding = location_encoding.view(label_encoding.size(0), -1, location_encoding.size(1))
# layout encoding - batch_size x max_seq_len x embed_size
layout_encoding = label_encoding + location_encoding
packed = pack(layout_encoding, lens_sorted, batch_first=True)
hiddens, _ = self.lstm(packed)
# unpack hiddens and get last hidden vector
hiddens_unpack = unpack(hiddens, batch_first=True)[0] # batch_size x max_seq_len x embed_size
last_hidden_idx = torch.zeros(hiddens_unpack.size(0), 1, hiddens_unpack.size(2)).long()
for i in range(hiddens_unpack.size(0)):
last_hidden_idx[i, 0, :] = lens_sorted[i] - 1
if torch.cuda.is_available():
last_hidden_idx = last_hidden_idx.cuda()
last_hidden = torch.gather(hiddens_unpack, 1, Variable(last_hidden_idx, requires_grad=False)) # batch_size x 1 x embed_size
last_hidden = torch.squeeze(last_hidden, 1) # batch_size x embed_size
# convert back to original batch order
last_hidden = torch.index_select(last_hidden, 0, Variable(reverse_batch_idx, requires_grad=False))
return last_hidden
class DecoderRNN(nn.Module):
def __init__(self, embed_size, hidden_size, vocab_size, num_layers):
"""Set the hyper-parameters and build the layers."""
super(DecoderRNN, self).__init__()
self.embed = nn.Embedding(vocab_size, embed_size)
self.lstm = nn.LSTM(embed_size, hidden_size, num_layers, batch_first=True)
self.linear = nn.Linear(hidden_size, vocab_size)
self.init_weights()
def init_weights(self):
"""Initialize weights."""
self.embed.weight.data.uniform_(-0.1, 0.1)
self.linear.weight.data.uniform_(-0.1, 0.1)
self.linear.bias.data.fill_(0)
def forward(self, features, captions, lengths):
"""Decode image feature vectors and generates captions."""
embeddings = self.embed(captions)
embeddings = torch.cat((features.unsqueeze(1), embeddings), 1)
packed = pack(embeddings, lengths, batch_first=True)
hiddens, _ = self.lstm(packed)
outputs = self.linear(hiddens[0])
return outputs
def sample(self, features, states=None):
"""Samples captions for given image features (Greedy search)."""
sampled_ids = []
inputs = features.unsqueeze(1)
for i in range(20): # maximum sampling length
hiddens, states = self.lstm(inputs, states) # (batch_size, 1, hidden_size),
outputs = self.linear(hiddens.squeeze(1)) # (batch_size, vocab_size)
predicted = outputs.max(1)[1]
sampled_ids.append(predicted)
inputs = self.embed(predicted)
sampled_ids = torch.cat(sampled_ids, 1) # (batch_size, 20)
return sampled_ids.squeeze() | 47.574627 | 132 | 0.674039 |
2677022d0f06ba2edd1595f12925003d5f558f34 | 1,510 | java | Java | src/main/java/com/max/util/Array2DUtils.java | mstepan/elements-of-programmin-interviews | f66a1ae02c693b3ea279fc7063df7c29a8df86cc | [
"MIT"
] | null | null | null | src/main/java/com/max/util/Array2DUtils.java | mstepan/elements-of-programmin-interviews | f66a1ae02c693b3ea279fc7063df7c29a8df86cc | [
"MIT"
] | 4 | 2020-12-08T08:40:58.000Z | 2022-01-04T16:35:48.000Z | src/main/java/com/max/util/Array2DUtils.java | mstepan/elements-of-programmin-interviews | f66a1ae02c693b3ea279fc7063df7c29a8df86cc | [
"MIT"
] | null | null | null | package com.max.util;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Utility class for 2D arrays.
*/
public final class Array2DUtils {
private Array2DUtils() {
throw new IllegalStateException("Utility only class");
}
/**
* Deep copy of 2D array.
*/
public static void deepCopy(boolean[][] from, boolean[][] to) {
checkNotNull(from);
checkNotNull(to);
checkArgument(from.length == to.length, "Dimensions aren't equals ('rows' not equal), can't copy 2D arrays.");
for (int row = 0; row < from.length; ++row) {
checkArgument(from[row].length == to[row].length,
"Dimensions aren't equals ('cols' not equal), can't copy 2D arrays.");
System.arraycopy(from[row], 0, to[row], 0, to[row].length);
}
}
/**
* Fill 2D boolean array with appropriate values.
*/
public static void fill(boolean[][] data, boolean value) {
checkNotNull(data);
for (int row = 0; row < data.length; ++row) {
for (int col = 0; col < data[row].length; ++col) {
data[row][col] = value;
}
}
}
public static boolean[][] create(int rows, int cols) {
boolean[][] data = new boolean[rows][cols];
for (int row = 0; row < rows; ++row) {
data[row] = new boolean[cols];
}
return data;
}
}
| 26.034483 | 118 | 0.566225 |
080757e9bf383b75e6168b052f4afb683d5000c1 | 1,289 | html | HTML | client/404.html | sdarmaputra/linkbucket | 660c607e189d7270dbda067d3188ae1a9255af6a | [
"MIT"
] | null | null | null | client/404.html | sdarmaputra/linkbucket | 660c607e189d7270dbda067d3188ae1a9255af6a | [
"MIT"
] | null | null | null | client/404.html | sdarmaputra/linkbucket | 660c607e189d7270dbda067d3188ae1a9255af6a | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Quicksand:300" rel="stylesheet">
<title>LinkBucket | You've got lost :(</title>
<style>
html {
height: 100%;
}
body {
padding: 0;
margin: 0;
height: 100%;
color: #222;
font-family: 'Quicksand', sans-serif;
}
a, a:visited, a:focus {
color: #9f51a5;
text-decoration: none;
}
a:hover {
color: #79397e;
}
.container {
padding: 48px;
text-align: center;
height: 100%;
box-sizing: border-box;
}
.container__center {
position: absolute;
top: 25%;
left: 50%;
transform: translate(-50%, -25%);
}
.sub-title {
color: #bbb;
}
.text-red {
color: #e74153;
}
.footer {
position: absolute;
bottom: 12px;
left: 0;
right: 0;
text-align: center;
padding: 18px;
color: #666;
}
</style>
</head>
<body>
<div class="container">
<div class="container__center">
<h1 class="title">You've Got Lost :(</h1>
<h5 class="sub-title">Don't worry. Let's go back <a href="/">home</a></h5>
</div>
<div class="footer">Crafted with <span class="text-red">♥</span> by <a href="https://github.com/sdarmaputra" target="blank">sdarmaputra</a></div>
</div>
</body>
</html>
| 20.140625 | 154 | 0.596587 |
4073ae892cf743011bae401a26ea43702e91762a | 3,884 | py | Python | py/utils/string_utils.py | arccode/factory | a1b0fccd68987d8cd9c89710adc3c04b868347ec | [
"BSD-3-Clause"
] | 3 | 2022-01-06T16:52:52.000Z | 2022-03-07T11:30:47.000Z | py/utils/string_utils.py | arccode/factory | a1b0fccd68987d8cd9c89710adc3c04b868347ec | [
"BSD-3-Clause"
] | null | null | null | py/utils/string_utils.py | arccode/factory | a1b0fccd68987d8cd9c89710adc3c04b868347ec | [
"BSD-3-Clause"
] | 1 | 2021-10-24T01:47:22.000Z | 2021-10-24T01:47:22.000Z | # Copyright 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""This module provides utility functions for string processing."""
from collections import namedtuple
import logging
def DecodeUTF8(data):
"""Decodes data as UTF-8, replacing any bad characters.
If data is not bytes type, returns as-is.
"""
if isinstance(data, bytes):
return data.decode('utf-8', errors='replace')
return data
def _ParseDictRecursive(lines, delimiter=':'):
"""Equilavant to `ParseDict(lines, recursive=True)`"""
def _IndentLevel(line):
return len(line) - len(line.lstrip())
Node = namedtuple('Node', ['line', 'childs', 'level'])
stack = [Node('root' + delimiter, [], -1)] # root node
for line in lines:
# Skip empty line
if len(line.strip()) == 0:
continue
level = _IndentLevel(line)
while level <= stack[-1].level:
node = stack.pop()
stack[-1].childs.append(node)
stack.append(Node(line, [], level))
while len(stack) > 1:
node = stack.pop()
stack[-1].childs.append(node)
def _BuildDictRecursive(node):
key, value = map(str.strip, node.line.split(delimiter, 1))
if len(node.childs) == 0:
return key, value
output_dict = {}
for child in node.childs:
output_dict.update([_BuildDictRecursive(child)])
return key, output_dict
return _BuildDictRecursive(stack.pop())[-1]
def ParseDict(lines, delimiter=':', recursive=False):
"""Parses list of lines into a dict. Each line is a string containing
key, value pair, where key and value are separated by delimiter, and are
stripped. If key, value pair can not be found in the line, that line will be
skipped.
Args:
lines: A list of strings.
delimiter: The delimiter string to separate key and value in each line.
recursive: Whether to parse the dict recursively.
Returns:
A dict, where both keys and values are string.
"""
if recursive:
return _ParseDictRecursive(lines, delimiter)
ret = dict()
for line in lines:
try:
key, value = line.split(delimiter, 1)
except ValueError:
logging.warning('Can not extract key, value pair in %s', line)
else:
ret[key.strip()] = value.strip()
return ret
def ParseString(value):
"""Parses a string if it is actually a True/False/None/Int value.
Args:
value: A string.
Returns:
True if the string matches one of 'True' and 'true. False if the string
matches one of 'False' and 'false'. None if the string matches 'None'.
An int if the string can be casted to an integer. Returns a string if
nothing matched.
"""
if value in ['True', 'true']:
value = True
elif value in ['False', 'false']:
value = False
elif value == 'None':
value = None
else:
try:
value = int(value)
except ValueError:
pass # No sweat
return value
def ParseUrl(url):
"""Parses a URL string according to RFC 1738.
Note: We allow '/' character in 'user', so we can specify workgroup of smb
user.
Args:
url: An URL string.
Returns:
A dict with optional keys 'scheme', 'user', 'password', 'host', 'port', and
'urlpath'.
"""
result = {}
scheme, delimiter, schemepart = url.partition('://')
if not delimiter:
return {}
result['scheme'] = scheme
userpass, unused_delimiter, hostpath = schemepart.rpartition('@')
if userpass:
user, delimiter, password = userpass.partition(':')
result['user'] = user
if delimiter:
result['password'] = password
hostport, delimiter, path = hostpath.partition('/')
if delimiter:
result['path'] = '/' + path
host, unused_delimiter, port = hostport.partition(':')
if host:
result['host'] = host
else:
return {}
if port:
result['port'] = port
return result
| 24.738854 | 79 | 0.654995 |
9c2a89e7067edbb780d2230a11183518b23b1af3 | 155 | ts | TypeScript | src/config/common/API_NAME.ts | ardalanamini/express-api-template | 89487b93cdc1d110a6fce889bf3ec3af48eed652 | [
"MIT"
] | 8 | 2022-02-07T23:59:35.000Z | 2022-02-24T21:48:08.000Z | src/config/common/API_NAME.ts | ardalanamini/express-api-template | 89487b93cdc1d110a6fce889bf3ec3af48eed652 | [
"MIT"
] | 25 | 2022-03-01T08:12:52.000Z | 2022-03-30T23:58:46.000Z | src/config/common/API_NAME.ts | ardalanamini/express-api-template | 89487b93cdc1d110a6fce889bf3ec3af48eed652 | [
"MIT"
] | null | null | null | // eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { name } from "#package.json";
export const API_NAME = name as string;
| 25.833333 | 61 | 0.729032 |
e95760a1e153bf30c72080eb589ad9e16cf3a5d6 | 2,025 | go | Go | registry/custom/custom.go | bn0ir/fabio | bf654ba0f4c94b855b25134e467e35f9c75b1637 | [
"MIT"
] | 3,725 | 2017-04-14T05:48:03.000Z | 2022-03-30T00:09:40.000Z | registry/custom/custom.go | bn0ir/fabio | bf654ba0f4c94b855b25134e467e35f9c75b1637 | [
"MIT"
] | 612 | 2017-04-14T06:14:10.000Z | 2022-03-26T19:16:39.000Z | registry/custom/custom.go | bn0ir/fabio | bf654ba0f4c94b855b25134e467e35f9c75b1637 | [
"MIT"
] | 444 | 2017-04-14T05:44:15.000Z | 2022-03-24T12:16:38.000Z | package custom
import (
"crypto/tls"
"encoding/json"
"fmt"
"github.com/fabiolb/fabio/config"
"github.com/fabiolb/fabio/route"
"log"
"net/http"
"time"
)
func customRoutes(cfg *config.Custom, ch chan string) {
var Routes *[]route.RouteDef
var trans *http.Transport
var URL string
if !cfg.CheckTLSSkipVerify {
trans = &http.Transport{}
} else {
trans = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
client := &http.Client{
Transport: trans,
Timeout: cfg.Timeout,
}
if cfg.QueryParams != "" {
URL = fmt.Sprintf("%s://%s/%s?%s", cfg.Scheme, cfg.Host, cfg.Path, cfg.QueryParams)
} else {
URL = fmt.Sprintf("%s://%s/%s", cfg.Scheme, cfg.Host, cfg.Path)
}
req, err := http.NewRequest("GET", URL, nil)
if err != nil {
log.Printf("[ERROR] Can not generate new HTTP request")
}
req.Close = true
for {
log.Printf("[DEBUG] Custom Registry starting request %s \n", time.Now())
resp, err := client.Do(req)
if err != nil {
ch <- fmt.Sprintf("Error Sending HTTPs Request To Custom be - %s -%s", URL, err.Error())
time.Sleep(cfg.PollInterval)
continue
}
if resp.StatusCode != 200 {
ch <- fmt.Sprintf("Error Non-200 return (%v) from -%s", resp.StatusCode, URL)
time.Sleep(cfg.PollInterval)
continue
}
log.Printf("[DEBUG] Custom Registry begin decoding json %s \n", time.Now())
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&Routes)
if err != nil {
ch <- fmt.Sprintf("Error decoding request - %s -%s", URL, err.Error())
time.Sleep(cfg.PollInterval)
continue
}
log.Printf("[DEBUG] Custom Registry building table %s \n", time.Now())
t, err := route.NewTableCustom(Routes)
if err != nil {
ch <- fmt.Sprintf("Error generating new table - %s", err.Error())
}
log.Printf("[DEBUG] Custom Registry building table complete %s \n", time.Now())
route.SetTable(t)
log.Printf("[DEBUG] Custom Registry table set complete %s \n", time.Now())
ch <- "OK"
time.Sleep(cfg.PollInterval)
}
}
| 24.39759 | 91 | 0.65037 |
ba5a1df631795649ec244537f787ad14f53153a5 | 15,126 | sql | SQL | SQLDataDump/SQL_Full_Export.sql | Modus28/mos-eisley-cantina | 0b0fdcddfbd6a4269660b676fbeb14c2a2b931f1 | [
"MIT"
] | null | null | null | SQLDataDump/SQL_Full_Export.sql | Modus28/mos-eisley-cantina | 0b0fdcddfbd6a4269660b676fbeb14c2a2b931f1 | [
"MIT"
] | null | null | null | SQLDataDump/SQL_Full_Export.sql | Modus28/mos-eisley-cantina | 0b0fdcddfbd6a4269660b676fbeb14c2a2b931f1 | [
"MIT"
] | null | null | null | -- MySQL dump 10.13 Distrib 5.7.17, for macos10.12 (x86_64)
--
-- Host: localhost Database: bar
-- ------------------------------------------------------
-- Server version 5.7.16
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `Bill`
--
DROP TABLE IF EXISTS `Bill`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Bill` (
`billNum` int(10) NOT NULL,
`c_id` int(10) DEFAULT NULL,
`e_id` int(5) DEFAULT NULL,
`tip` int(5) NOT NULL,
PRIMARY KEY (`billNum`),
KEY `customer_bill_fk_idx` (`c_id`),
KEY `employee_bill_fk_idx` (`e_id`),
CONSTRAINT `customer_bill_fk` FOREIGN KEY (`c_id`) REFERENCES `customer` (`c_id`) ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `employee_bill_fk` FOREIGN KEY (`e_id`) REFERENCES `employee` (`e_id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `Bill`
--
LOCK TABLES `Bill` WRITE;
/*!40000 ALTER TABLE `Bill` DISABLE KEYS */;
INSERT INTO `Bill` VALUES (0,0,0,5),(1,1,1,4),(10,10,10,6),(11,11,11,9),(100,100,100,30),(101,101,101,8),(110,110,110,6),(111,111,111,7),(1000,1000,1000,120),(1001,1001,1001,3),(1011,1011,0,5),(1100,1100,1,9),(1101,1101,10,258),(1110,1110,11,1),(1111,1111,100,88),(10000,10000,101,9),(10001,10001,110,12),(10010,10010,111,36),(10011,10011,1000,67),(10100,10100,1001,8),(10101,0,0,66),(10110,100,1,22),(10111,1100,10,5),(11000,110,11,89),(11001,101,100,506),(11010,111,101,1),(11011,1101,111,2),(11100,100,1000,23),(11101,10100,1001,29);
/*!40000 ALTER TABLE `Bill` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `Drinks`
--
DROP TABLE IF EXISTS `Drinks`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Drinks` (
`d_id` int(5) NOT NULL,
`dname` varchar(25) NOT NULL,
`p_id` int(5) DEFAULT NULL,
`alchohol` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`d_id`),
KEY `priceTable_drinks_fk_idx` (`p_id`),
CONSTRAINT `priceTable_drinks_fk` FOREIGN KEY (`p_id`) REFERENCES `priceTable` (`p_id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `Drinks`
--
LOCK TABLES `Drinks` WRITE;
/*!40000 ALTER TABLE `Drinks` DISABLE KEYS */;
INSERT INTO `Drinks` VALUES (1,'fuzzy navel',5,1),(2,'martini',4,1),(3,'bloody mary',3,1),(4,'margarita',3,1),(5,'rum punch',4,1),(6,'Mai Tai',5,1),(7,'vodka',3,1),(8,'beer',2,1),(9,'captian morgan',3,1),(10,'Spiked Lemondae',5,1),(11,'whiskey',3,1),(12,'hurricane',4,1),(13,'bahama mama',4,1),(14,'mojitos',3,1),(15,'Rasberry Daiquiri',4,1),(16,'Pina Colada',4,1),(17,'fountain drinks',1,0),(18,'water',0,0),(19,'juice',2,0),(20,'smoothie',3,0);
/*!40000 ALTER TABLE `Drinks` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `customer`
--
DROP TABLE IF EXISTS `customer`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `customer` (
`c_id` int(5) NOT NULL,
`cname` varchar(45) NOT NULL,
`age` int(3) DEFAULT NULL,
PRIMARY KEY (`c_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `customer`
--
LOCK TABLES `customer` WRITE;
/*!40000 ALTER TABLE `customer` DISABLE KEYS */;
INSERT INTO `customer` VALUES (0,'Artanis',600),(1,'Zeratul',700),(10,'Abathur',50),(11,'Raynor',38),(100,'Kerrigen',35),(101,'Nova',21),(110,'Tassadar',800),(111,'Diablo',999),(1000,'Tyrael',999),(1001,'Zagara',10),(1010,'Dehaka',67),(1011,'Auriel',999),(1100,'Azmodan',400),(1101,'Tychus',40),(1110,'Xul',60),(1111,'Sylvanas',25),(10000,'Jaina',30),(10001,'Varian',35),(10010,'Li Li',15),(10011,'Rexxar',50),(10100,'Medivh',40);
/*!40000 ALTER TABLE `customer` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `drinkpurchase`
--
DROP TABLE IF EXISTS `drinkpurchase`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `drinkpurchase` (
`billNum` int(10) NOT NULL,
`d_id` int(5) NOT NULL,
`qty` int(5) DEFAULT NULL,
PRIMARY KEY (`billNum`,`d_id`),
KEY `drinks_drinkpurchase_fk_idx` (`d_id`),
CONSTRAINT `bill_drinkpurchase_fk` FOREIGN KEY (`billNum`) REFERENCES `Bill` (`billNum`) ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `drinks_drinkpurchase_fk` FOREIGN KEY (`d_id`) REFERENCES `Drinks` (`d_id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `drinkpurchase`
--
LOCK TABLES `drinkpurchase` WRITE;
/*!40000 ALTER TABLE `drinkpurchase` DISABLE KEYS */;
INSERT INTO `drinkpurchase` VALUES (0,3,1),(0,18,2),(1,4,2),(1,11,2),(1,16,1),(1,18,2),(10,9,2),(10,17,1),(10,18,3),(11,2,1),(11,19,1),(100,5,1),(100,6,1),(101,20,1),(110,3,1),(111,8,1),(111,18,1),(1000,4,1),(1000,19,1),(1001,18,1),(1011,1,1),(1100,6,1),(1101,7,1),(1101,18,1),(1110,18,1),(1111,4,1),(1111,5,1);
/*!40000 ALTER TABLE `drinkpurchase` ENABLE KEYS */;
UNLOCK TABLES;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE Trigger CheckIfCustomerIsOver21 before insert on drinkpurchase
for each row
begin
if ((SELECT Drinks.alchohol from bar.Drinks WHERE NEW.d_id = Drinks.d_id) = 1 and (SELECT age from Customer, Bill Where Bill.billNum = New.billNum and Bill.c_id = Customer.c_id) < 21)
then
signal sqlstate '45000' set message_text = 'Cannot by drink, customer underage';
end if;
end;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Table structure for table `employee`
--
DROP TABLE IF EXISTS `employee`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `employee` (
`e_id` int(5) NOT NULL,
`ename` varchar(45) NOT NULL,
`salary` float DEFAULT NULL,
`datehired` varchar(10) DEFAULT NULL,
`m_id` int(5) DEFAULT NULL,
PRIMARY KEY (`e_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `employee`
--
LOCK TABLES `employee` WRITE;
/*!40000 ALTER TABLE `employee` DISABLE KEYS */;
INSERT INTO `employee` VALUES (0,'Hinata',2000,'12/15',5),(1,'Kotori',5000,'1/1',5),(5,'Bob',21000,'12/15',NULL),(10,'Umi',7500,'1/1',5),(11,'Sakura',3000,'6/3',5),(100,'Ruby',1500,'7/30',5),(101,'Honoka',2500,'9/10',5),(110,'Aoi',3600,'4/2',5),(111,'Rin',3100,'9/10',5),(1000,'Kekyo',1000,'10/30',5),(1001,'Kagome',4100,'8/25',5);
/*!40000 ALTER TABLE `employee` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `fooditem`
--
DROP TABLE IF EXISTS `fooditem`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `fooditem` (
`f_id` int(5) NOT NULL,
`fname` varchar(45) NOT NULL,
`p_id` int(10) DEFAULT NULL,
`vegan` tinyint(1) DEFAULT NULL,
`glutenfree` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`f_id`),
KEY `priceTable_fooditem_fk_idx` (`p_id`),
CONSTRAINT `priceTable_fooditem_fk` FOREIGN KEY (`p_id`) REFERENCES `priceTable` (`p_id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `fooditem`
--
LOCK TABLES `fooditem` WRITE;
/*!40000 ALTER TABLE `fooditem` DISABLE KEYS */;
INSERT INTO `fooditem` VALUES (1,'onion rings',4,1,0),(2,'fries',3,1,0),(3,'chicken wings',7,0,0),(4,'potato skins',6,0,0),(5,'nachos',5,0,0),(6,'loaded nachos',8,0,0),(7,'soft pretzles',8,0,0),(8,'chips and salsa',5,1,0),(9,'spinach and artichoke dip',4,1,1),(10,'BBQ pork sandwhich',9,0,0),(11,'gyro',9,0,0);
/*!40000 ALTER TABLE `fooditem` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `foodpurchase`
--
DROP TABLE IF EXISTS `foodpurchase`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `foodpurchase` (
`billNum` int(10) NOT NULL,
`f_id` int(5) NOT NULL,
`qty` int(5) DEFAULT NULL,
PRIMARY KEY (`billNum`,`f_id`),
KEY `fooditem_foodpurchase_fk_idx` (`f_id`),
CONSTRAINT `bill_foodpurchase_fk` FOREIGN KEY (`billNum`) REFERENCES `Bill` (`billNum`) ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `fooditem_foodpurchase_fk` FOREIGN KEY (`f_id`) REFERENCES `fooditem` (`f_id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `foodpurchase`
--
LOCK TABLES `foodpurchase` WRITE;
/*!40000 ALTER TABLE `foodpurchase` DISABLE KEYS */;
INSERT INTO `foodpurchase` VALUES (0,1,2),(0,10,1),(1,3,2),(1,5,2),(1,6,1),(1,7,2),(10,4,1),(10,6,3),(10,8,2),(11,1,1),(11,2,1),(100,2,1),(100,5,1),(100,10,2),(101,3,1),(101,4,2),(101,8,1),(110,5,1),(110,7,3),(110,9,1),(110,11,3),(111,1,1),(111,2,3),(111,3,1),(1000,3,1),(1000,5,1),(1000,7,1),(1000,9,1),(1001,2,1),(1001,4,2),(1001,8,2),(1001,10,1),(1011,2,1),(1011,3,2),(1011,6,1),(1011,9,1),(1100,5,1),(1100,6,1),(1100,7,1),(1100,11,1),(1101,2,1),(1101,3,2),(1101,9,1),(1101,10,1),(1110,1,1),(1110,2,1),(1110,3,2),(1110,5,1),(1110,10,1),(1110,11,1),(1111,1,1),(1111,5,2),(1111,9,1),(1111,10,1),(1111,11,1),(10000,1,1),(10000,4,1),(10000,8,1),(10001,1,1),(10001,5,1),(10001,7,1),(10001,8,1),(10001,11,1),(10010,2,2),(10010,3,2),(10011,1,1),(10011,2,2),(10011,3,1),(10011,4,1),(10011,5,1),(10011,6,1),(10100,1,1),(10100,2,1),(10100,6,1),(10100,11,1),(10101,11,2),(10110,1,1),(10110,2,2),(10111,1,1),(11000,3,1),(11000,4,2),(11001,1,1),(11001,2,1),(11001,3,1),(11010,3,1),(11010,7,1),(11010,9,1),(11011,9,1),(11011,10,1),(11100,11,3),(11101,10,1);
/*!40000 ALTER TABLE `foodpurchase` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `priceTable`
--
DROP TABLE IF EXISTS `priceTable`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `priceTable` (
`p_id` int(5) NOT NULL,
`price` float NOT NULL,
PRIMARY KEY (`p_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `priceTable`
--
LOCK TABLES `priceTable` WRITE;
/*!40000 ALTER TABLE `priceTable` DISABLE KEYS */;
INSERT INTO `priceTable` VALUES (0,0),(1,1),(2,2),(3,5),(4,7),(5,10),(6,12),(7,15),(8,17),(9,20);
/*!40000 ALTER TABLE `priceTable` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping routines for database 'bar'
--
/*!50003 DROP PROCEDURE IF EXISTS `dynamic1` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `dynamic1`(c_id integer(5))
BEGIN
SET @q1 =CONCAT("select bill.billNum, sum(priceTable.price * foodpurchase.qty)
from foodpurchase, bill, fooditem, priceTable
where foodpurchase.billNum = bill.billNum
and bill.c_id =", c_id," and fooditem.f_id = foodpurchase.f_id
and fooditem.p_id = priceTable.p_id
group by(bill.billNum)");
Prepare stmt1 From @q1;
execute stmt1;
deallocate prepare stmt1;
End ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sumfoodpurchaseofcustomer` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sumfoodpurchaseofcustomer`(c_id integer(5))
BEGIN
SET @q1 =CONCAT("select bill.billNum, sum(priceTable.price * foodpurchase.qty)
from foodpurchase, bill, fooditem, priceTable
where foodpurchase.billNum = bill.billNum
and bill.c_id =", c_id," and fooditem.f_id = foodpurchase.f_id
and fooditem.p_id = priceTable.p_id
group by(bill.billNum)");
Prepare stmt1 From @q1;
execute stmt1;
deallocate prepare stmt1;
End ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2017-04-29 15:28:20
| 46.256881 | 1,046 | 0.68769 |
3889e199a13cbe830c7289c9365a49741c212e9b | 1,394 | c | C | d/deku/dark/elite.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-07-19T05:24:44.000Z | 2021-11-18T04:08:19.000Z | d/deku/dark/elite.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 4 | 2021-03-15T18:56:39.000Z | 2021-08-17T17:08:22.000Z | d/deku/dark/elite.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-09-12T06:22:38.000Z | 2022-01-31T01:15:12.000Z | #include <std.h>
#include <objects.h>
inherit ROOM;
void create() {
::create();
set_property("light",0);
set_property("indoors",1);
set_property("no sticks",1);
set_terrain(BUILT_CAVE);
set_travel(DIRT_ROAD);
set_short("Darkelf elite guards");
set_long(
@KAYLA
Many skeletal forms lie near the east entrance to this cavern. A number
of rotting weapons and sundered pieces of decrepit armor are scattered
amongst the grisly debris. Near the west wall are the large skeletal
remains of a man hunched against the rock wall. Beneath these bones
is the rusting remnant of a great shield.
KAYLA
);
set_smell("default","You smell the stench of mortal flesh.");
set_exits(([
"north" : "/d/deku/dark/queen",
"east" : "/d/deku/dark/room2"
] ));
set_pre_exit_functions(({"north"}),({"GoThroughDoor"}));
set_items(([
] ));
}
void reset() {
::reset();
if(!present("elf")) {
new("/d/deku/monster/elite")->move(TO);
new("/d/deku/monster/elite")->move(TO);
if(!random(4))
new("/d/deku/monster/captain")->move(TO);
if(!random(3))
new("/d/deku/monster/elite")->move(TO);
}
}
int GoThroughDoor() {
if(present("darkelf")){
tell_room(environment(this_player()), "The guards forbid "+this_player()->query_cap_name()+" from entering the chamber of their queen!");
return 0;
}
return 1;
}
| 26.807692 | 141 | 0.646341 |
4157cf26d2e3ef5f4b5b74c827d876f5994fb45e | 215 | h | C | MXInke/MXInke/Classes/Base/MXTabBarController.h | dibaicongyouwangzi/MXInke | c537e36ca948d4447f539ad5e3766bff16b4c651 | [
"MIT"
] | 1 | 2017-04-16T17:17:44.000Z | 2017-04-16T17:17:44.000Z | MXInke/MXInke/Classes/Base/MXTabBarController.h | dibaicongyouwangzi/MXInke | c537e36ca948d4447f539ad5e3766bff16b4c651 | [
"MIT"
] | null | null | null | MXInke/MXInke/Classes/Base/MXTabBarController.h | dibaicongyouwangzi/MXInke | c537e36ca948d4447f539ad5e3766bff16b4c651 | [
"MIT"
] | null | null | null | //
// MXTabBarController.h
// MXInke
//
// Created by 迪拜葱油王子 on 2017/4/14.
// Copyright © 2017年 迪拜葱油王子. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface MXTabBarController : UITabBarController
@end
| 15.357143 | 50 | 0.702326 |
c2d128cf2c6484afe771f02eb48006a8293c6e33 | 674 | go | Go | main.go | marema31/villip | 704fa5ccbf39e12546581869b5b7fc8db9f46655 | [
"BSD-2-Clause"
] | null | null | null | main.go | marema31/villip | 704fa5ccbf39e12546581869b5b7fc8db9f46655 | [
"BSD-2-Clause"
] | 5 | 2021-07-20T12:19:22.000Z | 2021-09-23T21:17:07.000Z | main.go | marema31/villip | 704fa5ccbf39e12546581869b5b7fc8db9f46655 | [
"BSD-2-Clause"
] | 1 | 2020-10-05T08:40:13.000Z | 2020-10-05T08:40:13.000Z | package main
import (
"os"
"golang.org/x/sync/errgroup"
"github.com/sirupsen/logrus"
"github.com/marema31/villip/filterlist"
)
func main() {
log := logrus.New()
filters := filterlist.New()
log.SetLevel(logrus.InfoLevel)
if _, ok := os.LookupEnv("VILLIP_DEBUG"); ok {
log.SetLevel(logrus.DebugLevel)
}
upLog := log.WithField("app", "villip")
filters.ReadConfig(upLog)
servers := filters.CreateServers(upLog)
if len(servers) == 0 {
log.Fatal("No filter configuration provided")
}
g := new(errgroup.Group)
for _, s := range servers {
g.Go(s.Serve)
}
if err := g.Wait(); err != nil {
log.Fatalf("One server exiting in error: %v", err)
}
}
| 16.439024 | 52 | 0.660237 |
6994e2f4b3b46a653a3f74cc798c0d3bef7b8997 | 845 | kt | Kotlin | app/src/main/kotlin/com/numero/itube/ui/video/detail/playlist/item/PlaylistHeaderItem.kt | NUmeroAndDev/iTube-android | f1ed07fd0efb98239563c8940f69d498ba6f2602 | [
"MIT"
] | 3 | 2018-07-27T15:03:30.000Z | 2019-07-22T09:53:01.000Z | app/src/main/kotlin/com/numero/itube/ui/video/detail/playlist/item/PlaylistHeaderItem.kt | NUmeroAndDev/iTube-android | f1ed07fd0efb98239563c8940f69d498ba6f2602 | [
"MIT"
] | 15 | 2018-04-27T03:13:52.000Z | 2018-11-02T12:40:00.000Z | app/src/main/kotlin/com/numero/itube/ui/video/detail/playlist/item/PlaylistHeaderItem.kt | NUmeroAndDev/iTube-android | f1ed07fd0efb98239563c8940f69d498ba6f2602 | [
"MIT"
] | null | null | null | package com.numero.itube.ui.video.detail.playlist.item
import com.numero.itube.R
import com.numero.itube.model.PlaylistDetail
import com.numero.itube.model.PlaylistId
import com.xwray.groupie.kotlinandroidextensions.Item
import com.xwray.groupie.kotlinandroidextensions.ViewHolder
import kotlinx.android.synthetic.main.item_playlist_header.*
class PlaylistHeaderItem(
private val playlistDetail: PlaylistDetail,
private val onClickEditPlaylistListener: (playlistId: PlaylistId) -> Unit
) : Item() {
override fun getLayout(): Int = R.layout.item_playlist_header
override fun bind(viewHolder: ViewHolder, position: Int) {
viewHolder.titleTextView.text = playlistDetail.title
viewHolder.editPlayListButton.setOnClickListener {
onClickEditPlaylistListener(playlistDetail.id)
}
}
} | 35.208333 | 81 | 0.772781 |
295f4d79f3bd66989f8261c17bc879a087f97930 | 554 | swift | Swift | LeetCode/Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/main.swift | ShubhamJagtap2000/competitive-programming-1 | 3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84 | [
"MIT"
] | 1 | 2021-07-22T07:37:31.000Z | 2021-07-22T07:37:31.000Z | LeetCode/Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/main.swift | ShubhamJagtap2000/competitive-programming-1 | 3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84 | [
"MIT"
] | null | null | null | LeetCode/Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/main.swift | ShubhamJagtap2000/competitive-programming-1 | 3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84 | [
"MIT"
] | null | null | null |
class Solution {
func maxArea(_ h: Int, _ w: Int, _ H: [Int], _ V: [Int]) -> Int {
var (horizontal, vertical) = (H, V)
horizontal += [0, h]
vertical += [0, w]
horizontal.sort()
vertical.sort()
var (maxHorizontalDiff, maxVerticalDiff) = (0, 0)
for i in 1 ..< horizontal.count {
maxHorizontalDiff = max(maxHorizontalDiff, horizontal[i] - horizontal[i - 1])
}
for i in 1 ..< vertical.count {
maxVerticalDiff = max(maxVerticalDiff, vertical[i] - vertical[i - 1])
}
return (maxHorizontalDiff * maxVerticalDiff) % 1000000007
}
}
| 29.157895 | 80 | 0.644404 |
5f5d17dd0f7a88514680ac9ef209127f1e3b172c | 133 | ts | TypeScript | src/services/apolloServer/createContext.ts | lffg/graphql-auth-boilerplate | 72a1ac6374cd3a6b77a2ce60fc02d21a17bb6bd8 | [
"MIT"
] | null | null | null | src/services/apolloServer/createContext.ts | lffg/graphql-auth-boilerplate | 72a1ac6374cd3a6b77a2ce60fc02d21a17bb6bd8 | [
"MIT"
] | null | null | null | src/services/apolloServer/createContext.ts | lffg/graphql-auth-boilerplate | 72a1ac6374cd3a6b77a2ce60fc02d21a17bb6bd8 | [
"MIT"
] | null | null | null | import { MyContext } from '../../types/MyContext'
export function createContext({ req }: any): MyContext {
return {
req
}
}
| 16.625 | 56 | 0.631579 |
a05c76d009d243bf428f6bd515f205eed89dc3d9 | 110 | sql | SQL | db/update4.0.1.sql | rwj42/MANYI-PMS | a01a76cd03d15bbcff3e55b271b2807d30eb7c39 | [
"MIT"
] | null | null | null | db/update4.0.1.sql | rwj42/MANYI-PMS | a01a76cd03d15bbcff3e55b271b2807d30eb7c39 | [
"MIT"
] | null | null | null | db/update4.0.1.sql | rwj42/MANYI-PMS | a01a76cd03d15bbcff3e55b271b2807d30eb7c39 | [
"MIT"
] | 1 | 2019-01-29T06:38:48.000Z | 2019-01-29T06:38:48.000Z | ALTER TABLE `zt_user` CHANGE `msn` `skype` CHAR( 90 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;
| 55 | 109 | 0.745455 |
beea137ba12e80d98254e74daa42e7d7c22bea55 | 1,924 | html | HTML | messengerext/templates/groups/links.html | groupsome/groupsome | 4edcf30d66ff458c4df37d3198ef187219a768d7 | [
"MIT"
] | 6 | 2016-10-07T13:43:17.000Z | 2017-10-07T22:34:44.000Z | messengerext/templates/groups/links.html | groupsome/groupsome | 4edcf30d66ff458c4df37d3198ef187219a768d7 | [
"MIT"
] | null | null | null | messengerext/templates/groups/links.html | groupsome/groupsome | 4edcf30d66ff458c4df37d3198ef187219a768d7 | [
"MIT"
] | 1 | 2020-07-15T04:29:31.000Z | 2020-07-15T04:29:31.000Z | {% extends "groups/_base.html" %}
{% load i18n staticfiles compress ifrole %}
{% block title %}{% trans "Links" %} - {{ block.super }}{% endblock %}
{% block group_content %}
<div class="section group-links">
<div class="page-header">
<h2>{% trans "Links" %}</h2>
</div>
{% if links %}
<table class="table link-table">
<thead>
<tr>
<th class="column-name" colspan="2">{% trans "Title" %}</th>
<th class="column-uploaded">{% trans "Posted" %}</th>
<th class="column-actions"></th>
</tr>
</thead>
<tbody>
{% for link in links %}
<tr class="link" data-link-id="{{ link.id }}">
<td class="column-icon">
<a href="{{ link.url }}">
{% if link.file %}
<img src="{{link.link_preview_media_url}}" class="column-icon">
{% else %}
<i class="fa fa-external-link" aria-hidden="true"></i>
{% endif %}
</a>
</td>
<td class="column-name">
<a href="{{ link.url }}"> {{link.title}}</a>
</td>
<td class="column-uploaded">
<span data-livestamp="{{ link.timestamp|date:"c" }}"></span> {% trans "by" %}
{% if link.user.first_name %}
{{link.user.first_name}}{% else %}{{link.user.username}}{% endif %}</td>
</td>
<td class="column-actions">
{% ifrole "admin" %}
<i class="fa fa-trash delete-button link-delete-btn" data-group-id="{{ group.id }}" data-link-id="{{ link.id }}"></i>
{% endifrole %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
<br/>
<br/>
{% else %}
<div class="feed-placeholder">
<div class="alert alert-info">
<p>
{% trans "It looks so empty here =(" %}
</p>
<p>
{% trans "Post something in this group" %}
</p>
</div>
</div>
{% endif %}
</div>
{% endblock %}
{% block javascript %}
{{ block.super }}
<script src="{% static "js/links.js" %}"></script>
{% endblock %} | 26.722222 | 125 | 0.516632 |
9b8bd045fcd738c612a566c5f09be103720a3d3b | 5,907 | js | JavaScript | JS-Advanced/20-Exam-Prep-2/02-PizzUni/test/tests.js | DenislavVelichkov/JS-Core-January-2020 | 8503a2de75ac3e67aad043b818a7cd95d607c8c2 | [
"MIT"
] | null | null | null | JS-Advanced/20-Exam-Prep-2/02-PizzUni/test/tests.js | DenislavVelichkov/JS-Core-January-2020 | 8503a2de75ac3e67aad043b818a7cd95d607c8c2 | [
"MIT"
] | null | null | null | JS-Advanced/20-Exam-Prep-2/02-PizzUni/test/tests.js | DenislavVelichkov/JS-Core-January-2020 | 8503a2de75ac3e67aad043b818a7cd95d607c8c2 | [
"MIT"
] | null | null | null | const { expect } = require("chai");
const { beforeEach } = require("mocha");
const PizzUni = require('../PizzUni');
describe('Tests', function () {
let user1;
let user2;
let user3;
let fakePizza;
beforeEach(function () {
pizzUni = new PizzUni();
user1 = {
email: "pako@aa.aa",
orderHistory: []
};
user2 = {
email: "will@aa.aa",
orderHistory: []
};
user3 = {
email: "smith@aa.aa",
orderHistory: []
};
fakePizza = "Pizza Mente";
fakeDrink = "Mytenica";
});
describe('Test Constructor', () => {
it('Test class properties', () => {
expect(pizzUni.registeredUsers).deep.equal([]);
expect(pizzUni.availableProducts).deep.equal({
pizzas: ['Italian Style', 'Barbeque Classic', 'Classic Margherita'],
drinks: ['Coca-Cola', 'Fanta', 'Water']
});
expect(pizzUni.orders).deep.equal([]);
});
});
describe('Test registerUser()', () => {
it('Should return error when email is duplicated', () => {
pizzUni.registerUser(user1.email);
pizzUni.registerUser(user2.email);
pizzUni.registerUser(user3.email);
const result = () => pizzUni.registerUser(user1.email);
expect(result).to.throw(Error, `This email address (${user1.email}) is already being used!`)
expect(pizzUni.registeredUsers.length).deep.equal(3);
});
it('It should register user correctly', () => {
let user4 = {
email: "test@aa.aa",
orderHistory: []
}
let result = pizzUni.registerUser("test@aa.aa");
expect(result).deep.equal(user4);
expect(pizzUni.registeredUsers.length).deep.equal(1);
expect(pizzUni.registeredUsers[0]).deep.equal(user4);
});
});
describe('Test makeAnOrder()', () => {
it('Must throw error if user is not registered', () => {
let result = () => pizzUni.makeAnOrder(user1.email, 'Italian Style', 'Coca-Cola');
expect(result).to.throw(Error, "You must be registered to make orders!");
});
it('Must throw error if no pizza is ordered and/or ordered pizza must match available ones', () => {
pizzUni.registerUser(user1.email);
let result = () => pizzUni.makeAnOrder(user1.email, fakePizza, "Fanta");
expect(result).to.throw(Error, "You must order at least 1 Pizza to finish the order.");
});
it('Must return order with a drink', () => {
pizzUni.registerUser(user1.email);
let result = pizzUni.makeAnOrder(user1.email, 'Italian Style', 'Coca-Cola');
let userOrder = {
orderedPizza: 'Italian Style',
orderedDrink: 'Coca-Cola'
};
expect(pizzUni.orders[result]).deep.equal({
...userOrder,
email: user1.email,
status: 'pending'
});
expect(pizzUni.orders.length).deep.equal(1);
expect(pizzUni.orders[0].orderedDrink).to.equal('Coca-Cola');
expect(pizzUni.registeredUsers[0].orderHistory).to.deep.equal([{
orderedDrink: 'Coca-Cola',
orderedPizza: 'Italian Style'
}]);
});
it('Must return order index', () => {
pizzUni.registerUser(user1.email);
let result = pizzUni.makeAnOrder(user1.email, 'Italian Style', 'Coca-Cola');
expect(result).deep.equal(0);
});
it('Must return correct user order', () => {
pizzUni.registerUser(user1.email);
let user = pizzUni.doesTheUserExist(user1.email);
pizzUni.makeAnOrder(user1.email, 'Italian Style', 'Coca-Cola');
let userOrder = {
orderedPizza: 'Italian Style',
orderedDrink: 'Coca-Cola'
};
expect(user.orderHistory[0]).deep.equal(userOrder);
expect(user.orderHistory.length).deep.equal(1);
});
});
describe('Test detailsAboutMyOrder()', () => {
it('Shoud return correct status of an order', () => {
pizzUni.registerUser(user1.email);
pizzUni.makeAnOrder(user1.email, 'Italian Style', 'Coca-Cola');
pizzUni.completeOrder();
pizzUni.makeAnOrder(user1.email, 'Barbeque Classic', 'Water');
pizzUni.completeOrder();
pizzUni.makeAnOrder(user1.email, 'Italian Style', 'Fanta');
let compl = pizzUni.detailsAboutMyOrder(1);
let pend = pizzUni.detailsAboutMyOrder(2);
expect(compl).deep.equal("Status of your order: completed")
expect(pend).deep.equal("Status of your order: pending")
});
it('Test completed functionality', () => {
const result = pizzUni.detailsAboutMyOrder(0);
expect(result).to.equal(undefined);
});
});
describe('Test doesTheUserExist()', () => {
it('The method should return correct user', () => {
pizzUni.registerUser(user1.email);
pizzUni.registerUser(user2.email);
pizzUni.registerUser(user3.email);
let result = pizzUni.doesTheUserExist(user1.email);
expect(result).deep.equal(pizzUni.registeredUsers[0]);
});
it('The method should return undefined', () => {
pizzUni.registerUser(user1.email);
pizzUni.registerUser(user2.email);
pizzUni.registerUser(user3.email);
let result = pizzUni.doesTheUserExist("test@aa.aa");
expect(result).equal(undefined);
});
});
describe('Test completeOrder()', () => {
it('Should change orders status correctly', () => {
pizzUni.registerUser(user1.email);
let userOrder = {
orderedPizza: 'Barbeque Classic',
orderedDrink: 'Water'
};
let order = {
...userOrder,
email: user1.email,
status: 'completed'
};
pizzUni.makeAnOrder(user1.email, 'Italian Style', 'Coca-Cola');
pizzUni.makeAnOrder(user1.email, 'Barbeque Classic', 'Water');
pizzUni.makeAnOrder(user1.email, 'Italian Style', 'Fanta');
pizzUni.completeOrder();
let completedOrder = pizzUni.completeOrder();
expect(completedOrder).deep.equal(order);
});
});
}); | 28.536232 | 104 | 0.613171 |
0ec4af9cbf3c7a1a8413c5378c0629d9f19dd2a8 | 693 | sql | SQL | migrations/frontend/1528395943/up.sql | bobheadlabs/sourcegraph | 9699b27c150ea30b64abe06e4dfbf6eddc8b71b0 | [
"Apache-2.0"
] | 4 | 2022-03-25T13:46:37.000Z | 2022-03-31T15:30:47.000Z | migrations/frontend/1528395943/up.sql | bobheadlabs/sourcegraph | 9699b27c150ea30b64abe06e4dfbf6eddc8b71b0 | [
"Apache-2.0"
] | 1 | 2022-03-23T19:54:55.000Z | 2022-03-23T19:54:55.000Z | migrations/frontend/1528395943/up.sql | bobheadlabs/sourcegraph | 9699b27c150ea30b64abe06e4dfbf6eddc8b71b0 | [
"Apache-2.0"
] | 2 | 2022-03-25T13:47:23.000Z | 2022-03-25T13:51:12.000Z | CREATE EXTENSION IF NOT EXISTS citext;
COMMENT ON EXTENSION citext IS 'data type for case-insensitive character strings';
CREATE EXTENSION IF NOT EXISTS hstore;
COMMENT ON EXTENSION hstore IS 'data type for storing sets of (key, value) pairs';
CREATE EXTENSION IF NOT EXISTS intarray;
COMMENT ON EXTENSION intarray IS 'functions, operators, and index support for 1-D arrays of integers';
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
COMMENT ON EXTENSION pg_stat_statements IS 'track execution statistics of all SQL statements executed';
CREATE EXTENSION IF NOT EXISTS pg_trgm;
COMMENT ON EXTENSION pg_trgm IS 'text similarity measurement and index searching based on trigrams';
| 34.65 | 103 | 0.808081 |
3b614e6e05afb35c0abc36823a3792de8981289a | 12,218 | c | C | dlls/hnetcfg/tests/policy.c | castaneai/wine | 842452d4e79b20c42d2b7e279063b2feabeb31de | [
"MIT"
] | null | null | null | dlls/hnetcfg/tests/policy.c | castaneai/wine | 842452d4e79b20c42d2b7e279063b2feabeb31de | [
"MIT"
] | null | null | null | dlls/hnetcfg/tests/policy.c | castaneai/wine | 842452d4e79b20c42d2b7e279063b2feabeb31de | [
"MIT"
] | null | null | null | /*
* Copyright 2016 Alistair Leslie-Hughes
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#define COBJMACROS
#include <stdio.h>
#include "windows.h"
#include "ole2.h"
#include "oleauto.h"
#include "olectl.h"
#include "dispex.h"
#include "wine/test.h"
#include "netfw.h"
#include "natupnp.h"
static ULONG get_refcount(IUnknown *unk)
{
IUnknown_AddRef(unk);
return IUnknown_Release(unk);
}
static void test_policy2_rules(INetFwPolicy2 *policy2)
{
HRESULT hr;
INetFwRules *rules, *rules2;
INetFwServiceRestriction *restriction;
hr = INetFwPolicy2_QueryInterface(policy2, &IID_INetFwRules, (void**)&rules);
ok(hr == E_NOINTERFACE, "got 0x%08x\n", hr);
hr = INetFwPolicy2_get_Rules(policy2, &rules);
ok(hr == S_OK, "got %08x\n", hr);
hr = INetFwPolicy2_get_Rules(policy2, &rules2);
ok(hr == S_OK, "got %08x\n", hr);
ok(rules == rules2, "Different pointers\n");
hr = INetFwPolicy2_get_ServiceRestriction(policy2, &restriction);
todo_wine ok(hr == S_OK, "got %08x\n", hr);
if(hr == S_OK)
{
INetFwRules *rules3;
hr = INetFwServiceRestriction_get_Rules(restriction, &rules3);
ok(hr == S_OK, "got %08x\n", hr);
ok(rules != rules3, "same pointers\n");
if(rules3)
INetFwRules_Release(rules3);
INetFwServiceRestriction_Release(restriction);
}
hr = INetFwRules_get__NewEnum(rules, NULL);
ok(hr == E_POINTER, "got %08x\n", hr);
INetFwRules_Release(rules);
INetFwRules_Release(rules2);
}
static void test_interfaces(void)
{
INetFwMgr *manager;
INetFwPolicy *policy;
INetFwPolicy2 *policy2;
HRESULT hr;
hr = CoCreateInstance(&CLSID_NetFwMgr, NULL, CLSCTX_INPROC_SERVER|CLSCTX_INPROC_HANDLER,
&IID_INetFwMgr, (void**)&manager);
ok(hr == S_OK, "NetFwMgr create failed: %08x\n", hr);
hr = INetFwMgr_QueryInterface(manager, &IID_INetFwPolicy, (void**)&policy);
ok(hr == E_NOINTERFACE, "got 0x%08x\n", hr);
hr = INetFwMgr_QueryInterface(manager, &IID_INetFwPolicy2, (void**)&policy2);
ok(hr == E_NOINTERFACE, "got 0x%08x\n", hr);
hr = INetFwMgr_get_LocalPolicy(manager, &policy);
ok(hr == S_OK, "got 0x%08x\n", hr);
hr = INetFwPolicy_QueryInterface(policy, &IID_INetFwPolicy2, (void**)&policy2);
ok(hr == E_NOINTERFACE, "got 0x%08x\n", hr);
INetFwPolicy_Release(policy);
hr = CoCreateInstance(&CLSID_NetFwPolicy2, NULL, CLSCTX_INPROC_SERVER|CLSCTX_INPROC_HANDLER,
&IID_INetFwPolicy2, (void**)&policy2);
if(hr == S_OK)
{
test_policy2_rules(policy2);
INetFwPolicy2_Release(policy2);
}
else
win_skip("NetFwPolicy2 object is not supported: %08x\n", hr);
INetFwMgr_Release(manager);
}
static void test_NetFwAuthorizedApplication(void)
{
INetFwAuthorizedApplication *app;
static WCHAR empty[] = L"";
UNIVERSAL_NAME_INFOW *info;
WCHAR fullpath[MAX_PATH];
WCHAR netpath[MAX_PATH];
WCHAR image[MAX_PATH];
HRESULT hr;
BSTR bstr;
DWORD sz;
hr = CoCreateInstance(&CLSID_NetFwAuthorizedApplication, NULL, CLSCTX_INPROC_SERVER|CLSCTX_INPROC_HANDLER,
&IID_INetFwAuthorizedApplication, (void**)&app);
ok(hr == S_OK, "got: %08x\n", hr);
hr = GetModuleFileNameW(NULL, image, ARRAY_SIZE(image));
ok(hr, "GetModuleFileName failed: %u\n", GetLastError());
hr = INetFwAuthorizedApplication_get_ProcessImageFileName(app, NULL);
ok(hr == E_POINTER, "got: %08x\n", hr);
hr = INetFwAuthorizedApplication_get_ProcessImageFileName(app, &bstr);
ok(hr == S_OK || hr == HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY), "got: %08x\n", hr);
ok(!bstr, "got: %s\n", wine_dbgstr_w(bstr));
hr = INetFwAuthorizedApplication_put_ProcessImageFileName(app, NULL);
ok(hr == E_INVALIDARG || hr == HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND), "got: %08x\n", hr);
hr = INetFwAuthorizedApplication_put_ProcessImageFileName(app, empty);
ok(hr == E_INVALIDARG || hr == HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND), "got: %08x\n", hr);
bstr = SysAllocString(image);
hr = INetFwAuthorizedApplication_put_ProcessImageFileName(app, bstr);
ok(hr == S_OK, "got: %08x\n", hr);
SysFreeString(bstr);
GetFullPathNameW(image, ARRAY_SIZE(fullpath), fullpath, NULL);
GetLongPathNameW(fullpath, fullpath, ARRAY_SIZE(fullpath));
info = (UNIVERSAL_NAME_INFOW *)&netpath;
sz = sizeof(netpath);
hr = WNetGetUniversalNameW(image, UNIVERSAL_NAME_INFO_LEVEL, info, &sz);
if (hr != NO_ERROR)
{
info->lpUniversalName = netpath + sizeof(*info)/sizeof(WCHAR);
lstrcpyW(info->lpUniversalName, fullpath);
}
hr = INetFwAuthorizedApplication_get_ProcessImageFileName(app, &bstr);
ok(hr == S_OK, "got: %08x\n", hr);
ok(!lstrcmpW(bstr,info->lpUniversalName), "expected %s, got %s\n",
wine_dbgstr_w(info->lpUniversalName), wine_dbgstr_w(bstr));
SysFreeString(bstr);
INetFwAuthorizedApplication_Release(app);
}
static void test_static_port_mapping_collection( IStaticPortMappingCollection *ports )
{
LONG i, count, count2, expected_count, external_port;
IStaticPortMapping *pm, *pm2;
ULONG refcount, refcount2;
IEnumVARIANT *enum_ports;
IUnknown *unk;
ULONG fetched;
BSTR protocol;
VARIANT var;
HRESULT hr;
refcount = get_refcount((IUnknown *)ports);
hr = IStaticPortMappingCollection_get__NewEnum(ports, &unk);
ok(hr == S_OK, "Got unexpected hr %#x.\n", hr);
hr = IUnknown_QueryInterface(unk, &IID_IEnumVARIANT, (void **)&enum_ports);
ok(hr == S_OK, "Got unexpected hr %#x.\n", hr);
IUnknown_Release( unk );
refcount2 = get_refcount((IUnknown *)ports);
ok(refcount2 == refcount, "Got unexpected refcount %u, refcount2 %u.\n", refcount, refcount2);
hr = IEnumVARIANT_Reset(enum_ports);
ok(hr == S_OK, "Got unexpected hr %#x.\n", hr);
count = 0xdeadbeef;
hr = IStaticPortMappingCollection_get_Count(ports, &count);
ok(hr == S_OK, "Got unexpected hr %#x.\n", hr);
hr = IStaticPortMappingCollection_get_Item(ports, 12345, (BSTR)L"UDP", &pm);
if (SUCCEEDED(hr))
{
expected_count = count;
IStaticPortMapping_Release(pm);
}
else
{
expected_count = count + 1;
}
hr = IStaticPortMappingCollection_Add(ports, 12345, (BSTR)L"udp", 12345, (BSTR)L"1.2.3.4",
VARIANT_TRUE, (BSTR)L"wine_test", &pm);
ok(hr == E_INVALIDARG, "Got unexpected hr %#x.\n", hr);
hr = IStaticPortMappingCollection_Add(ports, 12345, (BSTR)L"UDP", 12345, (BSTR)L"1.2.3.4",
VARIANT_TRUE, (BSTR)L"wine_test", &pm);
ok(hr == S_OK, "Got unexpected hr %#x.\n", hr);
hr = IStaticPortMappingCollection_get_Count(ports, &count2);
ok(hr == S_OK, "Got unexpected hr %#x.\n", hr);
ok(count2 == expected_count, "Got unexpected count2 %u, expected %u.\n", count2, expected_count);
hr = IStaticPortMappingCollection_get_Item(ports, 12345, NULL, &pm);
ok(hr == E_INVALIDARG, "Got unexpected hr %#x.\n", hr);
hr = IStaticPortMappingCollection_get_Item(ports, 12345, (BSTR)L"UDP", NULL);
ok(hr == E_POINTER, "Got unexpected hr %#x.\n", hr);
hr = IStaticPortMappingCollection_get_Item(ports, 12345, (BSTR)L"udp", &pm);
ok(hr == E_INVALIDARG, "Got unexpected hr %#x.\n", hr);
hr = IStaticPortMappingCollection_get_Item(ports, -1, (BSTR)L"UDP", &pm);
ok(hr == E_INVALIDARG, "Got unexpected hr %#x.\n", hr);
hr = IStaticPortMappingCollection_get_Item(ports, 65536, (BSTR)L"UDP", &pm);
ok(hr == E_INVALIDARG, "Got unexpected hr %#x.\n", hr);
hr = IStaticPortMappingCollection_get_Item(ports, 12346, (BSTR)L"UDP", &pm);
ok(hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND), "Got unexpected hr %#x.\n", hr);
hr = IEnumVARIANT_Reset(enum_ports);
ok(hr == S_OK, "Got unexpected hr %#x.\n", hr);
for (i = 0; i < count2; ++i)
{
VariantInit(&var);
fetched = 0xdeadbeef;
hr = IEnumVARIANT_Next(enum_ports, 1, &var, &fetched);
ok(hr == S_OK, "Got unexpected hr %#x.\n", hr);
ok(fetched == 1, "Got unexpected fetched %u.\n", fetched);
ok(V_VT(&var) == VT_DISPATCH, "Got unexpected variant type %u.\n", V_VT(&var));
hr = IDispatch_QueryInterface(V_DISPATCH(&var), &IID_IStaticPortMapping, (void **)&pm);
ok(hr == S_OK, "Got unexpected hr %#x.\n", hr);
hr = IStaticPortMapping_get_Protocol(pm, &protocol);
ok(hr == S_OK, "Got unexpected hr %#x.\n", hr);
external_port = 0xdeadbeef;
hr = IStaticPortMapping_get_ExternalPort(pm, &external_port);
ok(hr == S_OK, "Got unexpected hr %#x.\n", hr);
ok(!wcscmp(protocol, L"UDP") || !wcscmp(protocol, L"TCP"), "Got unexpected protocol %s.\n",
debugstr_w(protocol));
hr = IStaticPortMappingCollection_get_Item(ports, external_port, protocol, &pm2);
ok(hr == S_OK, "Got unexpected hr %#x.\n", hr);
ok(pm2 != pm, "Got same interface.\n");
IStaticPortMapping_Release(pm);
IStaticPortMapping_Release(pm2);
SysFreeString(protocol);
VariantClear(&var);
}
hr = IEnumVARIANT_Next(enum_ports, 1, &var, &fetched);
ok(hr == S_FALSE, "Got unexpected hr %#x.\n", hr);
hr = IStaticPortMappingCollection_Remove(ports, 12345, (BSTR)L"UDP");
ok(hr == S_OK, "Got unexpected hr %#x.\n", hr);
IEnumVARIANT_Release(enum_ports);
}
static void test_IUPnPNAT(void)
{
IUPnPNAT *nat;
IStaticPortMappingCollection *static_ports;
IDynamicPortMappingCollection *dync_ports;
INATEventManager *manager;
IProvideClassInfo *provider;
ULONG refcount, refcount2;
HRESULT hr;
hr = CoCreateInstance(&CLSID_UPnPNAT, NULL, CLSCTX_INPROC_SERVER|CLSCTX_INPROC_HANDLER, &IID_IUPnPNAT, (void**)&nat);
ok(hr == S_OK, "got: %08x\n", hr);
hr = IUPnPNAT_QueryInterface(nat, &IID_IProvideClassInfo, (void**)&provider);
ok(hr == E_NOINTERFACE, "got: %08x\n", hr);
refcount = get_refcount((IUnknown *)nat);
hr = IUPnPNAT_get_StaticPortMappingCollection(nat, &static_ports);
ok(hr == S_OK, "got: %08x\n", hr);
if(hr == S_OK && static_ports)
{
refcount2 = get_refcount((IUnknown *)nat);
ok(refcount2 == refcount, "Got unexpected refcount %u, refcount2 %u.\n", refcount, refcount2);
test_static_port_mapping_collection( static_ports );
IStaticPortMappingCollection_Release(static_ports);
}
else if (hr == S_OK)
{
skip( "UPNP gateway not found.\n" );
}
hr = IUPnPNAT_get_DynamicPortMappingCollection(nat, &dync_ports);
ok(hr == S_OK || hr == E_NOTIMPL /* Windows 8.1 */, "got: %08x\n", hr);
if(hr == S_OK && dync_ports)
IDynamicPortMappingCollection_Release(dync_ports);
hr = IUPnPNAT_get_NATEventManager(nat, &manager);
todo_wine ok(hr == S_OK, "got: %08x\n", hr);
if(hr == S_OK && manager)
INATEventManager_Release(manager);
IUPnPNAT_Release(nat);
}
START_TEST(policy)
{
INetFwMgr *manager;
HRESULT hr;
CoInitialize(NULL);
hr = CoCreateInstance(&CLSID_NetFwMgr, NULL, CLSCTX_INPROC_SERVER|CLSCTX_INPROC_HANDLER,
&IID_INetFwMgr, (void**)&manager);
if(FAILED(hr))
{
win_skip("NetFwMgr object is not supported: %08x\n", hr);
CoUninitialize();
return;
}
INetFwMgr_Release(manager);
test_interfaces();
test_NetFwAuthorizedApplication();
test_IUPnPNAT();
CoUninitialize();
}
| 34.416901 | 121 | 0.665248 |
16c4d2d24372c599ec03cdb4b86346137448ff3b | 3,426 | asm | Assembly | B2G/external/libvpx/vp8/common/arm/neon/shortidct4x4llm_neon.asm | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-08-31T15:24:31.000Z | 2020-04-24T20:31:29.000Z | third_party/libvpx/source/libvpx/vp8/common/arm/neon/shortidct4x4llm_neon.asm | roisagiv/webrtc-ios | 953395a7d7a0922c825edb2304d2e458f3392686 | [
"BSD-3-Clause"
] | null | null | null | third_party/libvpx/source/libvpx/vp8/common/arm/neon/shortidct4x4llm_neon.asm | roisagiv/webrtc-ios | 953395a7d7a0922c825edb2304d2e458f3392686 | [
"BSD-3-Clause"
] | 4 | 2015-09-16T11:40:39.000Z | 2019-06-10T01:08:46.000Z | ;
; Copyright (c) 2010 The WebM project authors. All Rights Reserved.
;
; Use of this source code is governed by a BSD-style license
; that can be found in the LICENSE file in the root of the source
; tree. An additional intellectual property rights grant can be found
; in the file PATENTS. All contributing project authors may
; be found in the AUTHORS file in the root of the source tree.
;
EXPORT |vp8_short_idct4x4llm_neon|
ARM
REQUIRE8
PRESERVE8
AREA ||.text||, CODE, READONLY, ALIGN=2
;*************************************************************
;void vp8_short_idct4x4llm_c(short *input, short *output, int pitch)
;r0 short * input
;r1 short * output
;r2 int pitch
;*************************************************************
;static const int cospi8sqrt2minus1=20091;
;static const int sinpi8sqrt2 =35468;
;static const int rounding = 0;
;Optimization note: The resulted data from dequantization are signed 13-bit data that is
;in the range of [-4096, 4095]. This allows to use "vqdmulh"(neon) instruction since
;it won't go out of range (13+16+1=30bits<32bits). This instruction gives the high half
;result of the multiplication that is needed in IDCT.
|vp8_short_idct4x4llm_neon| PROC
ldr r12, _idct_coeff_
vld1.16 {q1, q2}, [r0]
vld1.16 {d0}, [r12]
vswp d3, d4 ;q2(vp[4] vp[12])
vqdmulh.s16 q3, q2, d0[2]
vqdmulh.s16 q4, q2, d0[0]
vqadd.s16 d12, d2, d3 ;a1
vqsub.s16 d13, d2, d3 ;b1
vshr.s16 q3, q3, #1
vshr.s16 q4, q4, #1
vqadd.s16 q3, q3, q2 ;modify since sinpi8sqrt2 > 65536/2 (negtive number)
vqadd.s16 q4, q4, q2
;d6 - c1:temp1
;d7 - d1:temp2
;d8 - d1:temp1
;d9 - c1:temp2
vqsub.s16 d10, d6, d9 ;c1
vqadd.s16 d11, d7, d8 ;d1
vqadd.s16 d2, d12, d11
vqadd.s16 d3, d13, d10
vqsub.s16 d4, d13, d10
vqsub.s16 d5, d12, d11
vtrn.32 d2, d4
vtrn.32 d3, d5
vtrn.16 d2, d3
vtrn.16 d4, d5
vswp d3, d4
vqdmulh.s16 q3, q2, d0[2]
vqdmulh.s16 q4, q2, d0[0]
vqadd.s16 d12, d2, d3 ;a1
vqsub.s16 d13, d2, d3 ;b1
vshr.s16 q3, q3, #1
vshr.s16 q4, q4, #1
vqadd.s16 q3, q3, q2 ;modify since sinpi8sqrt2 > 65536/2 (negtive number)
vqadd.s16 q4, q4, q2
vqsub.s16 d10, d6, d9 ;c1
vqadd.s16 d11, d7, d8 ;d1
vqadd.s16 d2, d12, d11
vqadd.s16 d3, d13, d10
vqsub.s16 d4, d13, d10
vqsub.s16 d5, d12, d11
vrshr.s16 d2, d2, #3
vrshr.s16 d3, d3, #3
vrshr.s16 d4, d4, #3
vrshr.s16 d5, d5, #3
add r3, r1, r2
add r12, r3, r2
add r0, r12, r2
vtrn.32 d2, d4
vtrn.32 d3, d5
vtrn.16 d2, d3
vtrn.16 d4, d5
vst1.16 {d2}, [r1]
vst1.16 {d3}, [r3]
vst1.16 {d4}, [r12]
vst1.16 {d5}, [r0]
bx lr
ENDP
;-----------------
_idct_coeff_
DCD idct_coeff
idct_coeff
DCD 0x4e7b4e7b, 0x8a8c8a8c
;20091, 20091, 35468, 35468
END
| 27.408 | 96 | 0.508173 |
f12b68f665d3e7d39b1138c6c3d2bf10fe8e6dfe | 964 | rb | Ruby | app/controllers/pods_controller.rb | K-Eo/reddhub | 4984c9785cd760ffd891d6033093381be31a9539 | [
"MIT"
] | null | null | null | app/controllers/pods_controller.rb | K-Eo/reddhub | 4984c9785cd760ffd891d6033093381be31a9539 | [
"MIT"
] | null | null | null | app/controllers/pods_controller.rb | K-Eo/reddhub | 4984c9785cd760ffd891d6033093381be31a9539 | [
"MIT"
] | null | null | null | class PodsController < ApplicationController
before_action :authenticate_user!
def create
@pod = current_user.pods.new(pod_params)
respond_to do |format|
if @pod.save
format.html do
redirect_to root_path(current_user.username), notice: t(".notice")
end
format.json { render @pod, status: :ok }
else
format.html do
@user = current_user
@pods = current_user.feed.page(params[:page])
@reactions = current_user.reactions_for(@pods, "Pod")
flash.now[:alert] = t(".alert")
render template: "home/show", layout: "home"
end
format.json { render json: @pod.errors, status: :unprocessable_entity }
end
end
end
def destroy
@pod = current_user.pods.find(params[:id])
@pod.purge
redirect_to root_path, notice: t(".notice")
end
private
def pod_params
params.require(:pod).permit(:content)
end
end
| 25.368421 | 79 | 0.620332 |
41829cee975a16e68331fc5adf5b60f8bbdd9acf | 129 | sql | SQL | src/test/resources/sql/create_table/e60d298e.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 66 | 2018-06-15T11:34:03.000Z | 2022-03-16T09:24:49.000Z | src/test/resources/sql/create_table/e60d298e.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 13 | 2019-03-19T11:56:28.000Z | 2020-08-05T04:20:50.000Z | src/test/resources/sql/create_table/e60d298e.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 28 | 2019-01-05T19:59:02.000Z | 2022-03-24T11:55:50.000Z | -- file:create_index.sql ln:117 expect:true
CREATE TABLE radix_text_tbl AS
SELECT name AS t FROM road WHERE name !~ '^[0-9]'
| 32.25 | 53 | 0.72093 |
f73aff1b7ff6418f32ec8febc176564922651ab7 | 1,674 | h | C | core/display.h | codetiger/GameTiger-Console | c143f6d6d32e077205bf48f08665f63c50467de0 | [
"MIT"
] | 4 | 2022-03-09T13:27:03.000Z | 2022-03-31T01:59:29.000Z | core/display.h | codetiger/GameTiger-Console | c143f6d6d32e077205bf48f08665f63c50467de0 | [
"MIT"
] | null | null | null | core/display.h | codetiger/GameTiger-Console | c143f6d6d32e077205bf48f08665f63c50467de0 | [
"MIT"
] | null | null | null | #include "common.h"
#include "color.h"
#ifndef _GAME_TIGER_DISPLAY_H
#define _GAME_TIGER_DISPLAY_H
class Display {
private:
const uint8_t CS_PIN = 9;
const uint8_t BL_PIN = 13;
const uint8_t DC_PIN = 8;
const uint8_t RST_PIN = 12;
const uint8_t MOSI_PIN = 11;
const uint8_t SCK_PIN = 10;
#ifdef FORMPU
void write_cmd(const uint8_t cmd);
void write_data(const uint8_t data);
void write_data(const uint8_t data[]);
void sendData(const uint8_t cmd, const uint8_t data[]);
void sendData(const uint8_t cmd, const uint8_t data);
void setWindow(const uint16_t x, const uint16_t y, const uint16_t width, const uint16_t height);
void setCursor(const uint16_t x, const uint16_t y);
void initHardware();
void initSequence();
void reset();
#else
SDL_Renderer* renderer;
SDL_Window* window;
#endif
Color *buffer;
#ifdef FORMPU
int dmaSPIChannel = 0;
dma_channel_config dmaSPIConfig;
int dmaMemChannel = 0;
dma_channel_config dmaMemConfig;
int dmaBufferChannel = 0;
dma_channel_config dmaBufferConfig;
#endif
public:
Display();
~Display();
void update();
void clear(Color c);
void setBrightness(uint8_t brightness);
void setPixel(int x, int y, Color &c, uint8_t alpha);
void drawBitmapRow(int x, int y, int width, Color *c);
void fillRect(int x, int y, int width, int height, Color &c, uint8_t alpha = 255);
void hLine(int x, int y, int width, Color &c, uint8_t alpha = 255);
void vLine(int x, int y, int height, Color &c, uint8_t alpha = 255);
void rect(int x, int y, int width, int height, Color &c, uint8_t alpha = 255);
};
#endif | 27.442623 | 100 | 0.688172 |
da0a5880a046664add8a3be13a2bded27835b5aa | 108 | sql | SQL | hasura/migrations/1619821930551_alter_table_job_queues_CombineVideosJob_alter_column_createdByAttendeeId/up.sql | LasseWolter/clowdr | 4777fc8386a7cd4f09b7a366ccd01662608c3e01 | [
"BSD-3-Clause"
] | 49 | 2021-01-09T07:09:08.000Z | 2022-03-27T05:16:46.000Z | hasura/migrations/1619821930551_alter_table_job_queues_CombineVideosJob_alter_column_createdByAttendeeId/up.sql | LasseWolter/clowdr | 4777fc8386a7cd4f09b7a366ccd01662608c3e01 | [
"BSD-3-Clause"
] | 333 | 2021-01-17T14:52:22.000Z | 2022-03-10T02:38:53.000Z | hasura/migrations/1619821930551_alter_table_job_queues_CombineVideosJob_alter_column_createdByAttendeeId/up.sql | LasseWolter/clowdr | 4777fc8386a7cd4f09b7a366ccd01662608c3e01 | [
"BSD-3-Clause"
] | 15 | 2021-01-29T14:17:38.000Z | 2022-02-14T22:13:48.000Z | alter table "job_queues"."CombineVideosJob" rename column "createdByAttendeeId" to "createdByRegistrantId";
| 54 | 107 | 0.833333 |
2163a0a3c3858ad766619eba029dda57b7b32111 | 268 | sql | SQL | tests/test_project/unit_tests/test_incremental_sum/model.sql | yida318/dbt-unit-test | 65c2ee91a78dc004ccd713879c68bff5251a3382 | [
"MIT"
] | 7 | 2021-03-11T09:34:24.000Z | 2022-01-12T07:52:48.000Z | tests/test_project/unit_tests/test_incremental_sum/model.sql | yida318/dbt-unit-test | 65c2ee91a78dc004ccd713879c68bff5251a3382 | [
"MIT"
] | 1 | 2021-12-18T16:57:21.000Z | 2021-12-18T16:57:21.000Z | tests/test_project/unit_tests/test_incremental_sum/model.sql | yida318/dbt-unit-test | 65c2ee91a78dc004ccd713879c68bff5251a3382 | [
"MIT"
] | 5 | 2021-06-13T01:56:20.000Z | 2022-03-08T17:52:59.000Z | {{
config(
materialized='incremental',
unique_key='grp'
)
}}
{{
incremental_sum(
reference = ref('test_incremental_sum_batch'),
metric_field = 'metric',
group_field = 'grp',
load_time_field = 'batch'
)
}} | 19.142857 | 54 | 0.548507 |
81a572c8cfa24d4e56c70a8c96b7e158179dbcf8 | 2,663 | rs | Rust | src/lib.rs | marekm4/dominant_color | 6c21be581bc3d0f168115ab902bd2f2bc399fd06 | [
"MIT"
] | 13 | 2019-08-21T22:31:28.000Z | 2021-09-25T06:23:53.000Z | src/lib.rs | marekm4/dominant_color | 6c21be581bc3d0f168115ab902bd2f2bc399fd06 | [
"MIT"
] | null | null | null | src/lib.rs | marekm4/dominant_color | 6c21be581bc3d0f168115ab902bd2f2bc399fd06 | [
"MIT"
] | 1 | 2021-09-12T21:57:45.000Z | 2021-09-12T21:57:45.000Z | #[derive(Copy, Clone, Debug)]
struct Bucket {
r: f64,
g: f64,
b: f64,
count: f64,
}
pub fn get_colors(pixels: &[u8], has_alpha: bool) -> Vec<u8> {
get_colors_with_config(&pixels, has_alpha, 224.0 * 224.0, 0.01)
}
pub fn get_colors_with_config(
pixels: &[u8],
has_alpha: bool,
down_size_to: f64,
small_bucket: f64,
) -> Vec<u8> {
// calculate bytes per pixel
let bytes_per_pixel = if has_alpha { 4 } else { 3 };
// calculate down size step
let pixel_count = pixels.len() / bytes_per_pixel;
let step = (pixel_count / down_size_to.round() as usize).max(1);
// load pixels to buckets
let mut buckets = [[[Bucket {
r: 0.0,
g: 0.0,
b: 0.0,
count: 0.0,
}; 2]; 2]; 2];
let mut sampled_pixel_count = 0.0;
for n in (0..pixel_count).step_by(step) {
let r = pixels[n * bytes_per_pixel];
let g = pixels[n * bytes_per_pixel + 1];
let b = pixels[n * bytes_per_pixel + 2];
let i = (r >> 7) as usize;
let j = (g >> 7) as usize;
let k = (b >> 7) as usize;
let alpha = if has_alpha {
pixels[n * bytes_per_pixel + 3] as f64 / 255.0
} else {
1.0
};
buckets[i][j][k].r += r as f64 * alpha;
buckets[i][j][k].g += g as f64 * alpha;
buckets[i][j][k].b += b as f64 * alpha;
buckets[i][j][k].count += alpha;
sampled_pixel_count += alpha;
}
// calculate buckets averages
let mut buckets_averages: Vec<Bucket> = Vec::new();
for i in 0..2 {
for j in 0..2 {
for k in 0..2 {
let current_bucket = &buckets[i][j][k];
if current_bucket.count > 0.0 {
buckets_averages.push(Bucket {
r: current_bucket.r / current_bucket.count,
g: current_bucket.g / current_bucket.count,
b: current_bucket.b / current_bucket.count,
count: current_bucket.count,
})
}
}
}
}
// sort buckets averages
buckets_averages.sort_by(|a, b| b.count.partial_cmp(&a.count).unwrap());
// convert buckets to vector, ignore small buckets
let mut colors: Vec<u8> = Vec::new();
for ba in &buckets_averages {
if ba.count / sampled_pixel_count as f64 > small_bucket {
colors.push(ba.r.round() as u8);
colors.push(ba.g.round() as u8);
colors.push(ba.b.round() as u8);
if has_alpha {
colors.push(255 as u8);
}
}
}
colors
}
| 29.588889 | 76 | 0.517837 |
90aa1bf3211f40930af4835f5a69fc125b8d0418 | 5,321 | py | Python | neural_sp/evaluators/wordpiece_bleu.py | SunSki/neural_sp | 4e4aca9b4cda1c7d95a1774d22f4d3298ad4ba4b | [
"Apache-2.0"
] | null | null | null | neural_sp/evaluators/wordpiece_bleu.py | SunSki/neural_sp | 4e4aca9b4cda1c7d95a1774d22f4d3298ad4ba4b | [
"Apache-2.0"
] | null | null | null | neural_sp/evaluators/wordpiece_bleu.py | SunSki/neural_sp | 4e4aca9b4cda1c7d95a1774d22f4d3298ad4ba4b | [
"Apache-2.0"
] | null | null | null | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2020 Kyoto University (Hirofumi Inaguma)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Evaluate the wordpiece-level model by BLEU."""
import codecs
import logging
from tqdm import tqdm
from nltk.translate.bleu_score import corpus_bleu, sentence_bleu
from neural_sp.utils import mkdir_join
logger = logging.getLogger(__name__)
def eval_wordpiece_bleu(models, dataloader, recog_params, epoch,
recog_dir=None, streaming=False, progressbar=False,
fine_grained=False):
"""Evaluate the wordpiece-level model by BLEU.
Args:
models (list): models to evaluate
dataloader (torch.utils.data.DataLoader): evaluation dataloader
recog_params (dict):
epoch (int):
recog_dir (str):
streaming (bool): streaming decoding for the session-level evaluation
progressbar (bool): visualize the progressbar
fine_grained (bool): calculate fine-grained BLEU distributions based on input lengths
Returns:
bleu (float): 4-gram BLEU
"""
if recog_dir is None:
recog_dir = 'decode_' + dataloader.set + '_ep' + str(epoch) + '_beam' + str(recog_params['recog_beam_width'])
recog_dir += '_lp' + str(recog_params['recog_length_penalty'])
recog_dir += '_cp' + str(recog_params['recog_coverage_penalty'])
recog_dir += '_' + str(recog_params['recog_min_len_ratio']) + '_' + str(recog_params['recog_max_len_ratio'])
recog_dir += '_lm' + str(recog_params['recog_lm_weight'])
ref_trn_path = mkdir_join(models[0].save_path, recog_dir, 'ref.trn')
hyp_trn_path = mkdir_join(models[0].save_path, recog_dir, 'hyp.trn')
else:
ref_trn_path = mkdir_join(recog_dir, 'ref.trn')
hyp_trn_path = mkdir_join(recog_dir, 'hyp.trn')
s_bleu = 0
n_sentence = 0
s_bleu_dist = {} # calculate sentence-level BLEU distribution based on input lengths
# Reset data counter
dataloader.reset(recog_params['recog_batch_size'])
if progressbar:
pbar = tqdm(total=len(dataloader))
list_of_references = []
hypotheses = []
with codecs.open(hyp_trn_path, 'w', encoding='utf-8') as f_hyp, \
codecs.open(ref_trn_path, 'w', encoding='utf-8') as f_ref:
while True:
batch, is_new_epoch = dataloader.next(recog_params['recog_batch_size'])
if streaming or recog_params['recog_chunk_sync']:
best_hyps_id, _ = models[0].decode_streaming(
batch['xs'], recog_params, dataloader.idx2token[0],
exclude_eos=True)
else:
best_hyps_id, _ = models[0].decode(
batch['xs'], recog_params,
idx2token=dataloader.idx2token[0] if progressbar else None,
exclude_eos=True,
refs_id=batch['ys'],
utt_ids=batch['utt_ids'],
speakers=batch['sessions' if dataloader.corpus == 'swbd' else 'speakers'],
ensemble_models=models[1:] if len(models) > 1 else [])
for b in range(len(batch['xs'])):
ref = batch['text'][b]
if ref[0] == '<':
ref = ref.split('>')[1]
hyp = dataloader.idx2token[0](best_hyps_id[b])
# Write to trn
# speaker = str(batch['speakers'][b]).replace('-', '_')
if streaming:
utt_id = str(batch['utt_ids'][b]) + '_0000000_0000001'
else:
utt_id = str(batch['utt_ids'][b])
f_ref.write(ref + '\n')
f_hyp.write(hyp + '\n')
logger.debug('utt-id: %s' % utt_id)
logger.debug('Ref: %s' % ref)
logger.debug('Hyp: %s' % hyp)
logger.debug('-' * 150)
if not streaming:
list_of_references += [[ref.split(' ')]]
hypotheses += [hyp.split(' ')]
n_sentence += 1
# Compute sentence-level BLEU
if fine_grained:
s_bleu_b = sentence_bleu([ref.split(' ')], hyp.split(' '))
s_bleu += s_bleu_b * 100
xlen_bin = (batch['xlens'][b] // 200 + 1) * 200
if xlen_bin in s_bleu_dist.keys():
s_bleu_dist[xlen_bin] += [s_bleu_b / 100]
else:
s_bleu_dist[xlen_bin] = [s_bleu_b / 100]
if progressbar:
pbar.update(1)
if is_new_epoch:
break
if progressbar:
pbar.close()
# Reset data counters
dataloader.reset()
c_bleu = corpus_bleu(list_of_references, hypotheses) * 100
if not streaming and fine_grained:
s_bleu /= n_sentence
for len_bin, s_bleus in sorted(s_bleu_dist.items(), key=lambda x: x[0]):
logger.info(' sentence-level BLEU (%s): %.2f %% (%d)' %
(dataloader.set, sum(s_bleus) / len(s_bleus), len_bin))
logger.debug('Corpus-level BLEU (%s): %.2f %%' % (dataloader.set, c_bleu))
return c_bleu
| 38.557971 | 117 | 0.557226 |
d67e3e20cc7fcc07503b5d1aa71ffd0dfaff6089 | 3,491 | swift | Swift | EvaluateDay/Nodes/UpdateNode.swift | bretsko/Evaluate-Day | 3413d97c062bb7a1f8abadc56458449ad9fbec74 | [
"MIT"
] | 6 | 2018-06-30T08:37:26.000Z | 2020-12-14T00:17:01.000Z | EvaluateDay/Nodes/UpdateNode.swift | bretsko/Evaluate-Day | 3413d97c062bb7a1f8abadc56458449ad9fbec74 | [
"MIT"
] | null | null | null | EvaluateDay/Nodes/UpdateNode.swift | bretsko/Evaluate-Day | 3413d97c062bb7a1f8abadc56458449ad9fbec74 | [
"MIT"
] | 2 | 2020-07-04T10:09:53.000Z | 2020-12-14T02:43:54.000Z | //
// UpdateNode.swift
// EvaluateDay
//
// Created by Konstantin Tsistjakov on 26/11/2017.
// Copyright © 2017 Konstantin Tsistjakov. All rights reserved.
//
import UIKit
import AsyncDisplayKit
class UpdateNode: ASCellNode {
// MARK: - UI
var titleNode = ASTextNode()
var subtitleNode = ASTextNode()
var updateButton = ASButtonNode()
var updateButtonCover = ASDisplayNode()
// MARK: - Init
override init() {
super.init()
let center = NSMutableParagraphStyle()
center.alignment = .left
self.titleNode.attributedText = NSAttributedString(string: Localizations.Update.title, attributes: [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .title2), NSAttributedString.Key.foregroundColor: UIColor.main, NSAttributedString.Key.paragraphStyle: center])
self.subtitleNode.attributedText = NSAttributedString(string: Localizations.Update.subtitle, attributes: [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .body), NSAttributedString.Key.foregroundColor: UIColor.main, NSAttributedString.Key.paragraphStyle: center])
self.updateButtonCover.backgroundColor = UIColor.main
self.updateButtonCover.cornerRadius = 10.0
let buttonTitle = NSAttributedString(string: Localizations.Update.button, attributes: [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .body), NSAttributedString.Key.foregroundColor: UIColor.textTint, NSAttributedString.Key.paragraphStyle: center])
self.updateButton.setAttributedTitle(buttonTitle, for: .normal)
self.updateButton.addTarget(self, action: #selector(updateButtonAction(sender:)), forControlEvents: .touchUpInside)
self.automaticallyManagesSubnodes = true
}
// MARK: - Override
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
let text = ASStackLayoutSpec.vertical()
text.spacing = 10.0
text.children = [self.titleNode, self.subtitleNode]
let textInsets = UIEdgeInsets(top: 25.0, left: 0.0, bottom: 0.0, right: 0.0)
let textInset = ASInsetLayoutSpec(insets: textInsets, child: text)
let buttonInsets = UIEdgeInsets(top: 15.0, left: 30.0, bottom: 15.0, right: 30.0)
let buttonInset = ASInsetLayoutSpec(insets: buttonInsets, child: self.updateButton)
let button = ASBackgroundLayoutSpec(child: buttonInset, background: self.updateButtonCover)
let cell = ASStackLayoutSpec.vertical()
cell.spacing = 20.0
cell.children = [textInset, button]
let cellInsets = UIEdgeInsets(top: 0.0, left: 20.0, bottom: 0.0, right: 20.0)
let cellInset = ASInsetLayoutSpec(insets: cellInsets, child: cell)
return cellInset
}
// MARK: - Actions
@objc func updateButtonAction(sender: ASButtonNode) {
let url = URL(string: appURLString)!
UIApplication.shared.open(url, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil)
}
}
// Helper function inserted by Swift 4.2 migrator.
private func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] {
return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)})
}
| 45.337662 | 287 | 0.707534 |
1c594298c4aa2e2fa06fcd8e4f2dbfd4c6d1bb95 | 2,227 | css | CSS | assets/css/lightBlue.css | NarenderManral/AbyowWebsite | 699e18797cf8f86a4eda8be5788139ddc02df530 | [
"MIT"
] | 15 | 2017-10-28T11:23:40.000Z | 2022-03-28T13:44:11.000Z | assets/css/lightBlue.css | NarenderManral/AbyowWebsite | 699e18797cf8f86a4eda8be5788139ddc02df530 | [
"MIT"
] | 1 | 2021-09-20T09:21:11.000Z | 2021-09-20T09:21:11.000Z | assets/css/lightBlue.css | NarenderManral/AbyowWebsite | 699e18797cf8f86a4eda8be5788139ddc02df530 | [
"MIT"
] | 8 | 2018-10-24T19:45:04.000Z | 2022-02-14T15:33:13.000Z | /* ==================================
Main Style
================================== */
body, html {
background-color: #f7f7fd;
font-family: 'Raleway', sans-serif;
}
a:hover {
text-decoration: none;
}
/* ==================================
Container
================================== */
.container {
margin-top: 50px;
margin-bottom: 50px;
}
/* ==================================
Left Column
================================== */
.left-column {
background-color: #ffffff;
box-shadow: 0 0 6px 0 hsla(0, 0%, 0%, 0.2);
/* box-shadow: 0 2px 6px 0 hsla(0, 0%, 0%, 0.2); */
padding: 30px;
}
/* Tittle */
.tittle-container {
margin: 10px auto 30px auto;
}
.tittle {
font-family: 'Raleway', sans-serif;
margin: 0 auto;
color: #38436b;
}
.subtitle {
font-family: 'Raleway', sans-serif;
margin: 0 auto;
color: #c1c5dc;
}
/* Contact Form*/
.contact-form {
padding: 0 10px;
}
.form-control-sm {
border-radius: 0;
}
/* Button */
.btn-submit {
text-align: center;
background-color: #6e91ff;
color: #ffffff;
font-size: 0.9rem;
text-transform: none;
transition: background-color .8s;
border-radius: 25px;
}
.btn-submit:hover {
background-color: #1c50fc;
-webkit-transition: background-color .8s;
-moz-transition: background-color .8s;
-o-transition: background-color .8s;
-ms-transition: background-color .8s;
transition: background-color .8s;
}
/* ==================================
Right Column
================================== */
.right-column {
background-color: #6e91ff;
box-shadow: 0 0 6px 0 hsla(0, 0%, 0%, 0.2);
padding: 20px;
color: #ffffff;
}
/* Contact Info */
.contact-info {
margin-bottom: 50px;
padding-left: 30px;
}
.contact-info h3{
font-family: 'Raleway', sans-serif;
text-align: center;
margin: 50px auto 30px auto;
}
/* Social Icons */
.social {
color: #ffffff;
}
.icon {
color: #ffffff;
margin: auto 10px;
}
/* ==================================
Responsive
================================== */
@media screen and (max-width: 576px) {
.container {
margin-top: 0;
margin-bottom: 0;
}
} | 18.254098 | 55 | 0.498877 |
76dd288da5afd55d2b3005df93731844bef2d28f | 412 | c | C | Userland/Wc/src/wc.c | mbrula/Shell-OS | b40891db466da672129fc9a1747749845a7ddc91 | [
"BSD-3-Clause"
] | null | null | null | Userland/Wc/src/wc.c | mbrula/Shell-OS | b40891db466da672129fc9a1747749845a7ddc91 | [
"BSD-3-Clause"
] | null | null | null | Userland/Wc/src/wc.c | mbrula/Shell-OS | b40891db466da672129fc9a1747749845a7ddc91 | [
"BSD-3-Clause"
] | null | null | null | // This is a personal academic project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
#include <clib.h>
int main(int argc, char const *argv[]) {
int car;
int lines = 0;
putchar('\n');
while ((car = getchar()) >= 0) {
putchar(car);
if (car == '\n')
lines++;
}
printf("\t-- Cantidad de Lineas ingresadas: %d --\n", lines);
return 0;
} | 25.75 | 75 | 0.616505 |
202a6200c4ea3b40e83d1dadb78091b9f5ea3c59 | 139 | css | CSS | typography.css | knagurski/pa55w0rd | 6eaf0514bb4426802be1058a4207313ce6db4163 | [
"MIT"
] | null | null | null | typography.css | knagurski/pa55w0rd | 6eaf0514bb4426802be1058a4207313ce6db4163 | [
"MIT"
] | null | null | null | typography.css | knagurski/pa55w0rd | 6eaf0514bb4426802be1058a4207313ce6db4163 | [
"MIT"
] | null | null | null | @font-face {
font-family: comfortaa;
font-display: swap;
src: url("./Comfortaa.ttf");
}
* {
font-family: comfortaa, sans-serif;
}
| 13.9 | 37 | 0.633094 |
c0866991669b466f6dfb9d242369a4a8cdde1e1a | 656 | kt | Kotlin | src/main/kotlin/com/deflatedpickle/hangerchan/extensions/PolygonShape.kt | DeflatedPickle/Hanger-chan | 60d85fdcc710f99c0bc7d221f8de1c271bf8ab2c | [
"MIT"
] | null | null | null | src/main/kotlin/com/deflatedpickle/hangerchan/extensions/PolygonShape.kt | DeflatedPickle/Hanger-chan | 60d85fdcc710f99c0bc7d221f8de1c271bf8ab2c | [
"MIT"
] | 8 | 2020-03-16T22:58:59.000Z | 2020-05-07T22:06:47.000Z | src/main/kotlin/com/deflatedpickle/hangerchan/extensions/PolygonShape.kt | DeflatedPickle/Hanger-chan | 60d85fdcc710f99c0bc7d221f8de1c271bf8ab2c | [
"MIT"
] | null | null | null | package com.deflatedpickle.hangerchan.extensions
import org.jbox2d.collision.shapes.PolygonShape
fun PolygonShape.getWidth(): Float = this.vertices[0].x + this.vertices[2].x
fun PolygonShape.getHeight(): Float = this.vertices[0].y + this.vertices[2].y
fun PolygonShape.getSize(): Pair<Float, Float> = Pair(this.getWidth(), this.getHeight())
fun PolygonShape.isInside(x: Float, y: Float) =
isInsideX(x) && isInsideY(y)
fun PolygonShape.isInsideX(x: Float) =
x > this.vertices[0].x &&
x < this.vertices[2].x
fun PolygonShape.isInsideY(y: Float) =
y > this.vertices[3].y &&
y < this.vertices[1].y | 32.8 | 88 | 0.669207 |
b9a74a1de58d42cf9ad394c10346f8814541e81c | 3,800 | c | C | src/s1ap/messages/asn1/r10.5/S1ap-CriticalityDiagnostics-IE-Item.c | lionelgo/openair-mme | 75bc0993613f61072342f5ae13dca28574253671 | [
"BSD-3-Clause"
] | 19 | 2020-04-25T15:51:52.000Z | 2021-11-24T04:51:02.000Z | src/s1ap/messages/asn1/r10.5/S1ap-CriticalityDiagnostics-IE-Item.c | lionelgo/openair-mme | 75bc0993613f61072342f5ae13dca28574253671 | [
"BSD-3-Clause"
] | 10 | 2020-09-09T09:54:20.000Z | 2021-04-27T20:47:52.000Z | src/s1ap/messages/asn1/r10.5/S1ap-CriticalityDiagnostics-IE-Item.c | lionelgo/openair-mme | 75bc0993613f61072342f5ae13dca28574253671 | [
"BSD-3-Clause"
] | 24 | 2020-05-31T01:41:12.000Z | 2022-01-16T17:06:35.000Z | /*
* Generated by asn1c-0.9.24 (http://lionet.info/asn1c)
* From ASN.1 module "S1AP-IEs"
* found in "S1AP-IEs.asn"
*/
#include "S1ap-CriticalityDiagnostics-IE-Item.h"
static asn_TYPE_member_t asn_MBR_S1ap_CriticalityDiagnostics_IE_Item_1[] = {
{ATF_NOFLAGS, 0,
offsetof(struct S1ap_CriticalityDiagnostics_IE_Item, iECriticality),
(ASN_TAG_CLASS_CONTEXT | (0 << 2)), -1, /* IMPLICIT tag at current level */
&asn_DEF_S1ap_Criticality,
0, /* Defer constraints checking to the member type */
0, /* PER is not compiled, use -gen-PER */
0, "iECriticality"},
{ATF_NOFLAGS, 0,
offsetof(struct S1ap_CriticalityDiagnostics_IE_Item, iE_ID),
(ASN_TAG_CLASS_CONTEXT | (1 << 2)), -1, /* IMPLICIT tag at current level */
&asn_DEF_S1ap_ProtocolIE_ID,
0, /* Defer constraints checking to the member type */
0, /* PER is not compiled, use -gen-PER */
0, "iE-ID"},
{ATF_NOFLAGS, 0,
offsetof(struct S1ap_CriticalityDiagnostics_IE_Item, typeOfError),
(ASN_TAG_CLASS_CONTEXT | (2 << 2)), -1, /* IMPLICIT tag at current level */
&asn_DEF_S1ap_TypeOfError,
0, /* Defer constraints checking to the member type */
0, /* PER is not compiled, use -gen-PER */
0, "typeOfError"},
{ATF_POINTER, 1,
offsetof(struct S1ap_CriticalityDiagnostics_IE_Item, iE_Extensions),
(ASN_TAG_CLASS_CONTEXT | (3 << 2)), -1, /* IMPLICIT tag at current level */
&asn_DEF_S1ap_IE_Extensions,
0, /* Defer constraints checking to the member type */
0, /* PER is not compiled, use -gen-PER */
0, "iE-Extensions"},
};
static ber_tlv_tag_t asn_DEF_S1ap_CriticalityDiagnostics_IE_Item_tags_1[] = {
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2))};
static asn_TYPE_tag2member_t
asn_MAP_S1ap_CriticalityDiagnostics_IE_Item_tag2el_1[] = {
{(ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0,
0}, /* iECriticality at 363 */
{(ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0}, /* iE-ID at 364 */
{(ASN_TAG_CLASS_CONTEXT | (2 << 2)), 2, 0, 0}, /* typeOfError at 365 */
{(ASN_TAG_CLASS_CONTEXT | (3 << 2)), 3, 0, 0} /* iE-Extensions at 366 */
};
static asn_SEQUENCE_specifics_t
asn_SPC_S1ap_CriticalityDiagnostics_IE_Item_specs_1 = {
sizeof(struct S1ap_CriticalityDiagnostics_IE_Item),
offsetof(struct S1ap_CriticalityDiagnostics_IE_Item, _asn_ctx),
asn_MAP_S1ap_CriticalityDiagnostics_IE_Item_tag2el_1,
4, /* Count of tags in the map */
0,
0,
0, /* Optional elements (not needed) */
3, /* Start extensions */
5 /* Stop extensions */
};
asn_TYPE_descriptor_t asn_DEF_S1ap_CriticalityDiagnostics_IE_Item = {
"S1ap-CriticalityDiagnostics-IE-Item",
"S1ap-CriticalityDiagnostics-IE-Item",
SEQUENCE_free,
SEQUENCE_print,
SEQUENCE_constraint,
SEQUENCE_decode_ber,
SEQUENCE_encode_der,
SEQUENCE_decode_xer,
SEQUENCE_encode_xer,
0,
0, /* No UPER support, use "-gen-PER" to enable */
0,
0, /* No APER support, use "-gen-PER" to enable */
SEQUENCE_compare,
0, /* Use generic outmost tag fetcher */
asn_DEF_S1ap_CriticalityDiagnostics_IE_Item_tags_1,
sizeof(asn_DEF_S1ap_CriticalityDiagnostics_IE_Item_tags_1) /
sizeof(asn_DEF_S1ap_CriticalityDiagnostics_IE_Item_tags_1[0]), /* 1 */
asn_DEF_S1ap_CriticalityDiagnostics_IE_Item_tags_1, /* Same as above */
sizeof(asn_DEF_S1ap_CriticalityDiagnostics_IE_Item_tags_1) /
sizeof(asn_DEF_S1ap_CriticalityDiagnostics_IE_Item_tags_1[0]), /* 1 */
0, /* No PER visible constraints */
asn_MBR_S1ap_CriticalityDiagnostics_IE_Item_1,
4, /* Elements count */
&asn_SPC_S1ap_CriticalityDiagnostics_IE_Item_specs_1 /* Additional specs */
};
| 43.181818 | 80 | 0.677632 |
015283b3a730797b0d509e1bad096e3c311aca3a | 1,100 | lua | Lua | chatcommands.lua | red-001/duel | 9d742f4e518d0f63fdc3ac1c1b1f1e3b5db721e4 | [
"MIT"
] | 1 | 2017-04-06T22:42:22.000Z | 2017-04-06T22:42:22.000Z | chatcommands.lua | red-001/duel | 9d742f4e518d0f63fdc3ac1c1b1f1e3b5db721e4 | [
"MIT"
] | 1 | 2017-04-06T22:43:17.000Z | 2017-04-07T17:15:22.000Z | chatcommands.lua | red-001/duel | 9d742f4e518d0f63fdc3ac1c1b1f1e3b5db721e4 | [
"MIT"
] | null | null | null | minetest.register_chatcommand("duel", {
params = "<player name>",
description = "Challenge a player to a duel",
func = function(caller, param)
if caller == param then
return false, "You can't have a duel with yourself"
end
local player = minetest.get_player_by_name(param)
if not player then
return false, "Player:"..param.." not found."
end
if duel.challenge(caller, param) then
return true, "You have challenged "..param.." to a duel"
else
return false, "Duel already in progres"
end
end,
})
minetest.register_chatcommand("duel_accept", {
description = "Accept a duel",
func = function(caller, param)
if duel.accept(caller) then
return true, "You have accepted the challenge"
else
return false, "No-one has challenged you to a duel"
end
end,
})
minetest.register_chatcommand("duel_abandon", {
description = "Abandon a duel before one of the players dies (causes you to lose)",
func = function(caller, param)
if duel.lose(caller) then
return true, "You have abandon a duel"
else
return false, "You are not in a duel"
end
end,
})
| 25.581395 | 84 | 0.698182 |
3e2f7a4c5b10d1814e363a5fb2b3567f5140f246 | 7,938 | c | C | examples/c/module/example_module.c | CESNET/Nemea-Framework | 49877c3306aa570609b00b990b74633b29e5f331 | [
"BSD-3-Clause"
] | 12 | 2015-10-16T09:22:50.000Z | 2021-11-14T17:08:38.000Z | examples/c/module/example_module.c | krkos/Nemea-Framework | f9c3265724649968cdc260c3c4c4fbd548b304ff | [
"BSD-3-Clause"
] | 160 | 2015-11-27T10:16:44.000Z | 2021-12-29T16:57:37.000Z | examples/c/module/example_module.c | krkos/Nemea-Framework | f9c3265724649968cdc260c3c4c4fbd548b304ff | [
"BSD-3-Clause"
] | 34 | 2015-11-27T14:46:07.000Z | 2020-11-06T19:17:29.000Z | /**
* \file example_module.c
* \brief Example of NEMEA module.
* \author Vaclav Bartos <ibartosv@fit.vutbr.cz>
* \author Marek Svepes <svepemar@fit.cvut.cz>
* \date 2016
*/
/*
* Copyright (C) 2013,2014,2015,2016 CESNET
*
* LICENSE TERMS
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name of the Company nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* ALTERNATIVELY, provided that this notice is retained in full, this
* product may be distributed under the terms of the GNU General Public
* License (GPL) version 2 or later, in which case the provisions
* of the GPL apply INSTEAD OF those given above.
*
* This software is provided ``as is'', and any express or implied
* warranties, including, but not limited to, the implied warranties of
* merchantability and fitness for a particular purpose are disclaimed.
* In no event shall the company or contributors be liable for any
* direct, indirect, incidental, special, exemplary, or consequential
* damages (including, but not limited to, procurement of substitute
* goods or services; loss of use, data, or profits; or business
* interruption) however caused and on any theory of liability, whether
* in contract, strict liability, or tort (including negligence or
* otherwise) arising in any way out of the use of this software, even
* if advised of the possibility of such damage.
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <signal.h>
#include <getopt.h>
#include <libtrap/trap.h>
#include <unirec/unirec.h>
#include "fields.h"
/**
* Definition of fields used in unirec templates (for both input and output interfaces)
*/
UR_FIELDS (
uint32 BAR,
uint32 FOO,
uint32 BAZ
)
trap_module_info_t *module_info = NULL;
/**
* Definition of basic module information - module name, module description, number of input and output interfaces
*/
#define MODULE_BASIC_INFO(BASIC) \
BASIC("Example module", \
"This module serves as an example of module implementation in TRAP platform. It receives UniRec" \
"containing two numbers (FOO and BAR) and sends UniRec containing the same numbers and their sum (BAZ).", 1, 1)
//BASIC(char *, char *, int, int)
/**
* Definition of module parameters - every parameter has short_opt, long_opt, description,
* flag whether an argument is required or it is optional and argument type which is NULL
* in case the parameter does not need argument.
* Module parameter argument types: int8, int16, int32, int64, uint8, uint16, uint32, uint64, float, string
*/
#define MODULE_PARAMS(PARAM) \
PARAM('m', "mult", "Multiplies the sum of received numbers with ARG of the parameter.", required_argument, "int32")
//PARAM(char, char *, char *, no_argument or required_argument, char *)
/**
* To define positional parameter ("param" instead of "-m param" or "--mult param"), use the following definition:
* PARAM('-', "", "Parameter description", required_argument, "string")
* There can by any argument type mentioned few lines before.
* This parameter will be listed in Additional parameters in module help output
*/
static int stop = 0;
/**
* Function to handle SIGTERM and SIGINT signals (used to stop the module)
*/
TRAP_DEFAULT_SIGNAL_HANDLER(stop = 1)
int main(int argc, char **argv)
{
int ret;
signed char opt;
int mult = 1;
/* **** TRAP initialization **** */
/*
* Macro allocates and initializes module_info structure according to MODULE_BASIC_INFO and MODULE_PARAMS
* definitions on the lines 71 and 84 of this file. It also creates a string with short_opt letters for getopt
* function called "module_getopt_string" and long_options field for getopt_long function in variable "long_options"
*/
INIT_MODULE_INFO_STRUCT(MODULE_BASIC_INFO, MODULE_PARAMS)
/*
* Let TRAP library parse program arguments, extract its parameters and initialize module interfaces
*/
TRAP_DEFAULT_INITIALIZATION(argc, argv, *module_info);
/*
* Register signal handler.
*/
TRAP_REGISTER_DEFAULT_SIGNAL_HANDLER();
/*
* Parse program arguments defined by MODULE_PARAMS macro with getopt() function (getopt_long() if available)
* This macro is defined in config.h file generated by configure script
*/
while ((opt = TRAP_GETOPT(argc, argv, module_getopt_string, long_options)) != -1) {
switch (opt) {
case 'm':
mult = atoi(optarg);
break;
default:
fprintf(stderr, "Invalid arguments.\n");
FREE_MODULE_INFO_STRUCT(MODULE_BASIC_INFO, MODULE_PARAMS);
TRAP_DEFAULT_FINALIZATION();
return -1;
}
}
/* **** Create UniRec templates **** */
ur_template_t *in_tmplt = ur_create_input_template(0, "FOO,BAR", NULL);
if (in_tmplt == NULL){
fprintf(stderr, "Error: Input template could not be created.\n");
return -1;
}
ur_template_t *out_tmplt = ur_create_output_template(0, "FOO,BAR,BAZ", NULL);
if (out_tmplt == NULL){
ur_free_template(in_tmplt);
fprintf(stderr, "Error: Output template could not be created.\n");
return -1;
}
// Allocate memory for output record
void *out_rec = ur_create_record(out_tmplt, 0);
if (out_rec == NULL){
ur_free_template(in_tmplt);
ur_free_template(out_tmplt);
fprintf(stderr, "Error: Memory allocation problem (output record).\n");
return -1;
}
/* **** Main processing loop **** */
// Read data from input, process them and write to output
while (!stop) {
const void *in_rec;
uint16_t in_rec_size;
// Receive data from input interface 0.
// Block if data are not available immediately (unless a timeout is set using trap_ifcctl)
ret = TRAP_RECEIVE(0, in_rec, in_rec_size, in_tmplt);
// Handle possible errors
TRAP_DEFAULT_RECV_ERROR_HANDLING(ret, continue, break);
// Check size of received data
if (in_rec_size < ur_rec_fixlen_size(in_tmplt)) {
if (in_rec_size <= 1) {
break; // End of data (used for testing purposes)
} else {
fprintf(stderr, "Error: data with wrong size received (expected size: >= %hu, received size: %hu)\n",
ur_rec_fixlen_size(in_tmplt), in_rec_size);
break;
}
}
// PROCESS THE DATA
// Read FOO and BAR from input record and compute their sum
uint32_t baz = ur_get(in_tmplt, in_rec, F_FOO) +
ur_get(in_tmplt, in_rec, F_BAR);
// Fill output record
ur_copy_fields(out_tmplt, out_rec, in_tmplt, in_rec);
ur_set(out_tmplt, out_rec, F_BAZ, mult * baz);
// Send record to interface 0.
// Block if ifc is not ready (unless a timeout is set using trap_ifcctl)
ret = trap_send(0, out_rec, ur_rec_fixlen_size(out_tmplt));
// Handle possible errors
TRAP_DEFAULT_SEND_ERROR_HANDLING(ret, continue, break);
}
/* **** Cleanup **** */
// Do all necessary cleanup in libtrap before exiting
TRAP_DEFAULT_FINALIZATION();
// Release allocated memory for module_info structure
FREE_MODULE_INFO_STRUCT(MODULE_BASIC_INFO, MODULE_PARAMS)
// Free unirec templates and output record
ur_free_record(out_rec);
ur_free_template(in_tmplt);
ur_free_template(out_tmplt);
ur_finalize();
return 0;
}
| 34.815789 | 119 | 0.696397 |
d01095098075ed279316da31159cde51dbc4986e | 8,161 | swift | Swift | Pod/Classes/RecastAI.swift | abossi/SDK-iOS | fbf45b11d82bdc249201aa1f720b63b53d1e2204 | [
"MIT"
] | null | null | null | Pod/Classes/RecastAI.swift | abossi/SDK-iOS | fbf45b11d82bdc249201aa1f720b63b53d1e2204 | [
"MIT"
] | null | null | null | Pod/Classes/RecastAI.swift | abossi/SDK-iOS | fbf45b11d82bdc249201aa1f720b63b53d1e2204 | [
"MIT"
] | null | null | null | //
// RecastAPI.swift
// Recast.AI Official iOS SDK
//
// Created by Pierre-Edouard LIEB on 24/03/2016.
//
// pierre-edouard.lieb@recast.ai
import Foundation
import Alamofire
import ObjectMapper
/**
RecastAIClient class handling request to the API
*/
public class RecastAIClient
{
static fileprivate let base_url : String = "https://api.recast.ai/v2/"
static fileprivate let base_url_voice : String = "ws://api.recast.ai/v2/"
static fileprivate let textRequest : String = base_url + "request"
static fileprivate let textConverse : String = base_url + "converse"
static fileprivate let voiceRequest : String = base_url_voice + "request"
static fileprivate let voiceConverse : String = base_url_voice + "converse"
fileprivate var token : String
fileprivate let language : String?
/**
Init RecastAIClient Class
- parameter token: your bot token
- parameter language: language of sentenses if needed
- returns: RecastAIClient
*/
public init (token : String, language : String? = nil)
{
self.token = token
self.language = language
}
/**
Make a text converse to Recast API
- parameter request: sentence to send to Recast API
- parameter lang: lang of the sentence if needed
- parameter successHandler: closure called when request succeed
- parameter failureHandler: closure called when request failed
- returns: void
*/
public func converseText(_ request : String, token : String? = nil, converseToken : String? = nil, lang: String? = nil, successHandler: @escaping (ConverseResponse) -> Void, failureHandle: @escaping (Error) -> Void)
{
if let tkn = token
{
self.token = tkn
}
let headers = ["Authorization" : "Token " + self.token]
var param = ["text" : request]
if let ln = lang
{
param["language"] = ln
}
else if let ln = self.language
{
param["language"] = ln
}
if let cnvrstnTkn = converseToken
{
param["conversation_token"] = cnvrstnTkn
}
Alamofire.request(RecastAIClient.textConverse, method: .post, parameters: param, headers: headers)
.validate(statusCode: 200..<300)
.responseJSON {
response in
switch response.result {
case .success(let value):
let recastResponse = (value as! [String : AnyObject])["results"] as! [String : Any]
let converseResponse = Mapper<ConverseResponse>().map(JSON: recastResponse)!
converseResponse.requestToken = self.token
successHandler(converseResponse)
case .failure(let error):
failureHandle(error)
}
}
}
/**
Make a text converse to Recast API
- parameter request: sentence to send to Recast API
- parameter lang: lang of the sentence if needed
- parameter successHandler: closure called when request succeed
- parameter failureHandler: closure called when request failed
- returns: void
*/
public func converseFile(_ audioFileURL: URL, token : String? = nil, converseToken : String? = nil, lang: String? = nil, successHandler: @escaping (ConverseResponse) -> Void, failureHandle: @escaping (Error) -> Void)
{
if let tkn = token
{
self.token = tkn
}
let headers = ["Authorization" : "Token " + self.token]
var ln : String = lang!
let conversationToken : String = converseToken!
if (self.language != nil)
{
ln = self.language!
}
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(audioFileURL, withName: "voice")
multipartFormData.append(ln.data(using: String.Encoding.utf8)!, withName: "language")
multipartFormData.append(conversationToken.data(using: String.Encoding.utf8)!, withName: "conversation_token")
},
to: RecastAIClient.voiceConverse,
method: .post,
headers: headers,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
switch response.result {
case .success(let value):
let recastResponse = (value as! [String : AnyObject])["results"] as! [String : Any]
let converseResponse = Mapper<ConverseResponse>().map(JSON: recastResponse)!
converseResponse.requestToken = self.token
successHandler(converseResponse)
case .failure(let error):
failureHandle(error)
}
}
case .failure(let encodingError):
failureHandle(encodingError)
}
})
}
/**
Make a text request to Recast API
- parameter request: sentence to send to Recast API
- parameter lang: lang of the sentence if needed
- parameter successHandler: closure called when request succeed
- parameter failureHandler: closure called when request failed
- returns: void
*/
public func analyseText(_ request : String, token : String? = nil, lang: String? = nil, successHandler: @escaping (Response) -> Void, failureHandle: @escaping (Error) -> Void)
{
if let tkn = token
{
self.token = tkn
}
let headers = ["Authorization" : "Token " + self.token]
var param = ["text" : request]
if let ln = lang
{
param["language"] = ln
}
else if let ln = self.language
{
param["language"] = ln
}
Alamofire.request(RecastAIClient.textRequest, method: .post, parameters: param, headers: headers)
.validate(statusCode: 200..<300)
.responseJSON {
response in
switch response.result {
case .success(let value):
let recastResponse = (value as! [String : AnyObject])["results"] as! [String : Any]
successHandler(Mapper<Response>().map(JSON: recastResponse)!)
case .failure(let error):
failureHandle(error)
}
}
}
/**
Make a voice request to Recast API
- parameter audioFileURL: audio file URL to send to RecastAI
- parameter lang: lang of the sentence if needed
- parameter successHandler: closure called when request succeed
- parameter failureHandler: closure called when request failed
- returns: void
*/
public func analyseFile(_ audioFileURL: URL, token : String? = nil, lang: String? = nil, successHandler: @escaping (Response) -> Void, failureHandle: @escaping (Error) -> Void) {
if let tkn = token
{
self.token = tkn
}
let headers = ["Authorization": "Token " + self.token]
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(audioFileURL, withName: "voice")
},
to: RecastAIClient.voiceRequest,
method: .post,
headers: headers,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
switch response.result {
case .success(let value):
let recastResponse = (value as! [String : AnyObject])["results"] as! [String : Any]
successHandler(Mapper<Response>().map(JSON: recastResponse)!)
case .failure(let error):
failureHandle(error)
}
}
case .failure(let encodingError):
failureHandle(encodingError)
}
})
}
}
| 37.26484 | 220 | 0.580934 |