language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
1,436
1.53125
2
[]
no_license
package com.dinogroup; import static org.mockito.Mockito.mock; import javax.inject.Singleton; import com.google.gson.Gson; import com.mixpanel.android.mpmetrics.MixpanelAPI; import com.squareup.otto.Bus; import android.content.SharedPreferences; import android.view.inputmethod.InputMethodManager; import dagger.Module; import dagger.Provides; import flow.Parcer; import com.dinogroup.analytics.EventTracker; import com.dinogroup.util.gson.GsonParcer; import com.dinogroup.util.mortar.BaseView; @Module( injects = BaseView.class, library = true ) public class TestApplicationModule { private android.app.Application application; public TestApplicationModule(android.app.Application application) { this.application = application; } @Provides @Singleton android.app.Application provideApplication() { return application; } @Provides SharedPreferences provideSharedPreferences() { return mock(SharedPreferences.class); } @Provides MixpanelAPI provideMixpanelApi() { return mock(MixpanelAPI.class); } @Provides EventTracker provideEventTracker() { return mock(EventTracker.class); } @Provides Parcer<Object> provideParcer() { return new GsonParcer<>(new Gson()); } @Provides Bus provideBus() { return new Bus(); } @Provides InputMethodManager provideInputMethodManager() { return mock(InputMethodManager.class); } }
SQL
UTF-8
2,265
3.265625
3
[]
no_license
-- DIGAE-219: adding CAMP properties to SAMPLES_PROP table -- modify the samples tables alter table SAMPLE_camp modify column ID varchar(100) primary key; -- common table -- add in the rows from the samples tables insert into SAMPLES_common_dv1 (select ID from SAMPLE_camp camp where not exists (select * from SAMPLES_common_dv1 where ID = camp.ID)); -- DATASET -- add in the samples rows insert into SAMPLES_DATASET (ID, EXP, VER, SG, TECH, ANCESTRY, PARENT, TBL, SORT, CASES, CONTROLS, SUBJECTS) values('samples_camp_mdv2', 'ExChip_camp', 'mdv2', 'camp', 'ExChip', 'Mixed', 'Root', 'SAMPLE_camp', 70, 563, 3065, 3662); -- add t2d readable field alter table SAMPLE_camp add column T2D_readable varchar(100); update SAMPLE_camp set T2D_readable = if((T2D = 0), 'No', if((T2D = 1), 'Yes', null)); -- SAMPLES PROP insert into SAMPLES_PROP_ID (ID, PROP) values('samples_camp_mdv2','ID'); insert into SAMPLES_PROP_ID (ID, PROP) values('samples_camp_mdv2','Age'); insert into SAMPLES_PROP_ID (ID, PROP) values('samples_camp_mdv2','SEX'); insert into SAMPLES_PROP_ID (ID, PROP) values('samples_camp_mdv2','t2d'); insert into SAMPLES_PROP_ID (ID, PROP) values('samples_camp_mdv2','T2D_readable'); insert into SAMPLES_PROP_ID (ID, PROP) values('samples_camp_mdv2','BMI'); insert into SAMPLES_PROP_ID (ID, PROP) values('samples_camp_mdv2','FAST_INS'); insert into SAMPLES_PROP_ID (ID, PROP) values('samples_camp_mdv2','FAST_GLU'); insert into SAMPLES_PROP_ID (ID, PROP) values('samples_camp_mdv2','C1'); insert into SAMPLES_PROP_ID (ID, PROP) values('samples_camp_mdv2','C2'); insert into SAMPLES_PROP_ID (ID, PROP) values('samples_camp_mdv2','C3'); insert into SAMPLES_PROP_ID (ID, PROP) values('samples_camp_mdv2','C4'); insert into SAMPLES_PROP_ID (ID, PROP) values('samples_camp_mdv2','C5'); insert into SAMPLES_PROP_ID (ID, PROP) values('samples_camp_mdv2','C6'); insert into SAMPLES_PROP_ID (ID, PROP) values('samples_camp_mdv2','C7'); insert into SAMPLES_PROP_ID (ID, PROP) values('samples_camp_mdv2','C8'); insert into SAMPLES_PROP_ID (ID, PROP) values('samples_camp_mdv2','C9'); insert into SAMPLES_PROP_ID (ID, PROP) values('samples_camp_mdv2','C10'); -- report scratch queries select count(ID), t2d, t2d_readable from SAMPLE_camp group by t2d;
Python
UTF-8
17,298
3.046875
3
[ "BSD-3-Clause" ]
permissive
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import, division, print_function, unicode_literals from collections import OrderedDict import numpy as np import astropy.units as u from astropy.table import Table from astropy.time import Time from ..spectrum.utils import CountsPredictor from ..stats.poisson import excess_error from ..utils.scripts import make_path __all__ = [ 'LightCurve', 'LightCurveEstimator', ] class LightCurve(object): """Lightcurve container. The lightcurve data is stored in ``table``. For now we only support times stored in MJD format! TODO: specification of format is work in progress See https://github.com/open-gamma-ray-astro/gamma-astro-data-formats/pull/61 Usage: :ref:`time-lc` Parameters ---------- table : `~astropy.table.Table` Table with lightcurve data """ def __init__(self, table): self.table = table def __repr__(self): return '{}(len={})'.format(self.__class__.__name__, len(self.table)) @property def time_scale(self): """Time scale (str). Taken from table "TIMESYS" header. Common values: "TT" or "UTC". Assumed default is "UTC". """ return self.table.meta.get('TIMESYS', 'utc') @property def time_format(self): """Time format (str).""" return 'mjd' # @property # def time_ref(self): # """Time reference (`~astropy.time.Time`).""" # return time_ref_from_dict(self.table.meta) def _make_time(self, colname): val = self.table[colname].data scale = self.time_scale format = self.time_format return Time(val, scale=scale, format=format) @property def time(self): """Time (`~astropy.time.Time`).""" return self._make_time('time') @property def time_min(self): """Time bin start (`~astropy.time.Time`).""" return self._make_time('time_min') @property def time_max(self): """Time bin end (`~astropy.time.Time`).""" return self._make_time('time_max') @property def time_mid(self): """Time bin center (`~astropy.time.Time`). :: time_mid = time_min + 0.5 * time_delta """ return self.time_min + 0.5 * self.time_delta @property def time_delta(self): """Time bin width (`~astropy.time.TimeDelta`). :: time_delta = time_max - time_min """ return self.time_max - self.time_min @classmethod def read(cls, filename, **kwargs): """Read from file. Parameters ---------- filename : str Filename kwargs : dict Keyword arguments passed to `astropy.table.Table.read`. """ filename = make_path(filename) table = Table.read(str(filename), **kwargs) return cls(table=table) def write(self, filename, **kwargs): """Write to file. Parameters ---------- filename : str Filename kwargs : dict Keyword arguments passed to `astropy.table.Table.write`. """ filename = make_path(filename) self.table.write(str(filename), **kwargs) def compute_fvar(self): r"""Calculate the fractional excess variance. This method accesses the the ``FLUX`` and ``FLUX_ERR`` columns from the lightcurve data. The fractional excess variance :math:`F_{var}`, an intrinsic variability estimator, is given by .. math:: F_{var} = \sqrt{\frac{S^{2} - \bar{\sigma^{2}}}{\bar{x}^{2}}}. It is the excess variance after accounting for the measurement errors on the light curve :math:`\sigma`. :math:`S` is the variance. Returns ------- fvar, fvar_err : `~numpy.ndarray` Fractional excess variance. References ---------- .. [Vaughan2003] "On characterizing the variability properties of X-ray light curves from active galaxies", Vaughan et al. (2003) http://adsabs.harvard.edu/abs/2003MNRAS.345.1271V """ flux = self.table['flux'].data.astype('float64') flux_err = self.table['flux_err'].data.astype('float64') flux_mean = np.mean(flux) n_points = len(flux) s_square = np.sum((flux - flux_mean) ** 2) / (n_points - 1) sig_square = np.nansum(flux_err ** 2) / n_points fvar = np.sqrt(np.abs(s_square - sig_square)) / flux_mean sigxserr_a = np.sqrt(2 / n_points) * (sig_square / flux_mean) ** 2 sigxserr_b = np.sqrt(sig_square / n_points) * (2 * fvar / flux_mean) sigxserr = np.sqrt(sigxserr_a ** 2 + sigxserr_b ** 2) fvar_err = sigxserr / (2 * fvar) return fvar, fvar_err def compute_chisq(self): """Calculate the chi-square test for `LightCurve`. Chisquare test is a variability estimator. It computes deviations from the expected value here mean value Returns ------- ChiSq, P-value : tuple of float or `~numpy.ndarray` Tuple of Chi-square and P-value """ import scipy.stats as stats flux = self.table['flux'] yexp = np.mean(flux) yobs = flux.data chi2, pval = stats.chisquare(yobs, yexp) return chi2, pval def plot(self, ax=None): """Plot flux versus time. Parameters ---------- ax : `~matplotlib.axes.Axes` or None, optional. The `~matplotlib.axes.Axes` object to be drawn on. If None, uses the current `~matplotlib.axes.Axes`. Returns ------- ax : `~matplotlib.axes.Axes` or None, optional. The `~matplotlib.axes.Axes` object to be drawn on. If None, uses the current `~matplotlib.axes.Axes`. """ import matplotlib.pyplot as plt ax = plt.gca() if ax is None else ax # TODO: Should we plot with normal time axis labels (ISO, not MJD)? x, xerr = self._get_plot_x() y, yerr = self._get_plot_y() ax.errorbar(x=x, y=y, xerr=xerr, yerr=yerr, linestyle="None") ax.scatter(x=x, y=y) ax.set_xlabel("Time (MJD)") ax.set_ylabel("Flux (cm-2 s-1)") return ax def _get_plot_x(self): try: x = self.time.mjd except KeyError: x = self.time_mid.mjd try: xerr = x - self.time_min.mjd, self.time_max.mjd - x except KeyError: xerr = None return x, xerr def _get_plot_y(self): y = self.table['flux'].quantity.to('cm-2 s-1').value if 'flux_errp' in self.table.colnames: yp = self.table['flux_errp'].quantity.to('cm-2 s-1').value yn = self.table['flux_errn'].quantity.to('cm-2 s-1').value yerr = yn, yp elif 'flux_err' in self.table.colnames: yerr = self.table['flux_err'].quantity.to('cm-2 s-1').value else: yerr = None return y, yerr class LightCurveEstimator(object): """Light curve estimator. For a usage example see :gp-extra-notebook:`light_curve`. Parameters ---------- spec_extract : `~gammapy.spectrum.SpectrumExtraction` Contains statistics, IRF and event lists """ def __init__(self, spec_extract): self.obs_list = spec_extract.obs_list self.obs_spec = spec_extract.observations self.off_evt_list = self._get_off_evt_list(spec_extract) self.on_evt_list = self._get_on_evt_list(spec_extract) @staticmethod def _get_off_evt_list(spec_extract): """ Returns list of OFF events for each observations """ off_evt_list = [] for bg in spec_extract.bkg_estimate: off_evt_list.append(bg.off_events) return off_evt_list @staticmethod def _get_on_evt_list(spec_extract): """ Returns list of ON events for each observations """ on_evt_list = [] for obs in spec_extract.bkg_estimate: on_evt_list.append(obs.on_events) return on_evt_list @staticmethod def create_fixed_time_bin(time_step, spectrum_extraction): """Create time intervals of fixed size. Parameters ---------- time_step : float Size of the light curve bins in seconds spectrum_extraction : `~gammapy.spectrum.SpectrumExtraction` Contains statistics, IRF and event lists Returns ------- intervals : list of `~astropy.time.Time` List of time intervals """ intervals = [] time_start = Time(100000, format="mjd") time_end = Time(0, format="mjd") time_step = time_step / (24 * 3600) for obs in spectrum_extraction.obs_list: time_events = obs.events.time if time_start > time_events.min(): time_start = time_events.min() if time_end < time_events.max(): time_end = time_events.max() time = time_start.value while time < time_end.value: time += time_step intervals.append([ Time(time - time_step, format="mjd"), Time(time, format="mjd"), ]) return intervals def light_curve(self, time_intervals, spectral_model, energy_range): """Compute light curve. Implementation follows what is done in: http://adsabs.harvard.edu/abs/2010A%26A...520A..83H. To be discussed: assumption that threshold energy in the same in reco and true energy. Parameters ---------- time_intervals : `list` of `~astropy.time.Time` List of time intervals spectral_model : `~gammapy.spectrum.models.SpectralModel` Spectral model energy_range : `~astropy.units.Quantity` True energy range to evaluate integrated flux (true energy) Returns ------- lc : `~gammapy.time.LightCurve` Light curve """ rows = [] for time_interval in time_intervals: useinterval, row = self.compute_flux_point(time_interval, spectral_model, energy_range) if useinterval: rows.append(row) return self._make_lc_from_row_data(rows) @staticmethod def _make_lc_from_row_data(rows): table = Table() table['time_min'] = [_['time_min'].value for _ in rows] table['time_max'] = [_['time_max'].value for _ in rows] table['flux'] = [_['flux'].value for _ in rows] * u.Unit('1 / (s cm2)') table['flux_err'] = [_['flux_err'].value for _ in rows] * u.Unit('1 / (s cm2)') table['livetime'] = [_['livetime'].value for _ in rows] * u.s table['n_on'] = [_['n_on'] for _ in rows] table['n_off'] = [_['n_off'] for _ in rows] table['alpha'] = [_['alpha'] for _ in rows] table['measured_excess'] = [_['measured_excess'] for _ in rows] table['expected_excess'] = [_['expected_excess'].value for _ in rows] return LightCurve(table) def compute_flux_point(self, time_interval, spectral_model, energy_range): """Compute one flux point for one time interval. Parameters ---------- time_interval : `~astropy.time.Time` Time interval (2-element array, or a tuple of Time objects) spectral_model : `~gammapy.spectrum.models.SpectralModel` Spectral model energy_range : `~astropy.units.Quantity` True energy range to evaluate integrated flux (true energy) Returns ------- useinterval : bool Is True if the time_interval produce a valid flux point measurements : dict Dictionary with flux point measurement in the time interval """ tmin, tmax = time_interval[0], time_interval[1] livetime = 0 alpha_mean = 0. alpha_mean_backup = 0. measured_excess = 0 predicted_excess = 0 n_on = 0 n_off = 0 useinterval = False # Loop on observations for t_index, obs in enumerate(self.obs_list): spec = self.obs_spec[t_index] # discard observations not matching the time interval obs_start = obs.events.time[0] obs_stop = obs.events.time[-1] if (tmin < obs_start and tmax < obs_start) or (tmin > obs_stop): continue useinterval = True # get ON and OFF evt list off_evt = self.off_evt_list[t_index] on_evt = self.on_evt_list[t_index] # introduce the e_reco binning here, since it's also used # in the calculation of predicted counts e_reco = spec.e_reco emin = e_reco[e_reco.searchsorted(max(spec.lo_threshold, energy_range[0]))] emax = e_reco[e_reco.searchsorted(min(spec.hi_threshold, energy_range[1])) - 1] # compute ON events on = on_evt.select_energy([emin, emax]) on = on.select_energy(energy_range) on = on.select_time([tmin, tmax]) n_on_obs = len(on.table) # compute OFF events off = off_evt.select_energy([emin, emax]) off = off.select_energy(energy_range) off = off.select_time([tmin, tmax]) n_off_obs = len(off.table) # compute effective livetime (for the interval) if tmin >= obs_start and tmax <= obs_stop: # interval included in obs livetime_to_add = (tmax - tmin).to('s') elif tmin >= obs_start and tmax >= obs_stop: # interval min above tstart from obs livetime_to_add = (obs_stop - tmin).to('s') elif tmin <= obs_start and tmax <= obs_stop: # interval min below tstart from obs livetime_to_add = (tmax - obs_start).to('s') elif tmin <= obs_start and tmax >= obs_stop: # obs included in interval livetime_to_add = (obs_stop - obs_start).to('s') else: livetime_to_add = 0 * u.sec # Take into account dead time livetime_to_add *= (1. - obs.observation_dead_time_fraction) # Compute excess obs_measured_excess = n_on_obs - spec.alpha * n_off_obs # Compute the expected excess in the range given by the user # but must respect the energy threshold of the observation # (to match the energy range of the measured excess) # We use the effective livetime and the right energy threshold e_idx = np.where(np.logical_and.reduce( (e_reco >= spec.lo_threshold, # threshold e_reco <= spec.hi_threshold, # threshold e_reco >= energy_range[0], # user e_reco <= energy_range[-1]) # user ))[0] counts_predictor = CountsPredictor( livetime=livetime_to_add, aeff=spec.aeff, edisp=spec.edisp, model=spectral_model ) counts_predictor.run() counts_predicted_excess = counts_predictor.npred.data.data[e_idx[:-1]] obs_predicted_excess = np.sum(counts_predicted_excess) # compute effective normalisation between ON/OFF (for the interval) livetime += livetime_to_add alpha_mean += spec.alpha * n_off_obs alpha_mean_backup += spec.alpha * livetime_to_add measured_excess += obs_measured_excess predicted_excess += obs_predicted_excess n_on += n_on_obs n_off += n_off_obs # Fill time interval information if useinterval: int_flux = spectral_model.integral(energy_range[0], energy_range[1]) if n_off > 0.: alpha_mean /= n_off if livetime > 0.: alpha_mean_backup /= livetime if alpha_mean == 0.: # use backup if necessary alpha_mean = alpha_mean_backup flux = measured_excess / predicted_excess.value flux *= int_flux flux_err = int_flux / predicted_excess.value # Gaussian errors, TODO: should be improved flux_err *= excess_error(n_on=n_on, n_off=n_off, alpha=alpha_mean) else: flux = 0 flux_err = 0 # Store measurements in a dict and return that return useinterval, OrderedDict([ ('time_min', Time(tmin, format='mjd')), ('time_max', Time(tmax, format='mjd')), ('flux', flux * u.Unit('1 / (s cm2)')), ('flux_err', flux_err * u.Unit('1 / (s cm2)')), ('livetime', livetime * u.s), ('alpha', alpha_mean), ('n_on', n_on), ('n_off', n_off), ('measured_excess', measured_excess), ('expected_excess', predicted_excess), ])
Markdown
UTF-8
12,071
2.8125
3
[]
no_license
# 购物车系统的设计 学号:2701170227 姓名:张利峰 ## 1、项目准备 - Git建仓库 - 项目同步 - 整体框架 ## 2、解决方案 ##### 连接本地数据库: ```java package Dao; import java.sql.*; import java.security.MessageDigest; public class UserDao2 { final static String url = "jdbc:mysql://localhost:3306/ahstu"; static Connection con = null; static Statement stmt = null; static final String USER = "root"; static final String PASS = "123456"; static { try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(url,USER,PASS); stmt = con.createStatement(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { } ``` ##### 数据库实现增查及MD5加密: ```java public final static String MD5(String s) { char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; try { byte[] btInput = s.getBytes(); // 获得MD5摘要算法的 MessageDigest 对象 MessageDigest mdInst = MessageDigest.getInstance("MD5"); // 使用指定的字节更新摘要 mdInst.update(btInput); // 获得密文 byte[] md = mdInst.digest(); // 把密文转换成十六进制的字符串形式 int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { e.printStackTrace(); return null; } } public static boolean updatePassword(String name, String pass1, String pass2) { if (!login(name, pass1)) { System.err.println("初始密码错误"); return false; } String sql = "update users set password='" + MD5(pass2) + "' where user_id='" + name + "'"; boolean result = executeUpdate(sql); if (result) { System.err.println("修改密码成功"); } else { System.err.println("修改密码失败"); } return result; } public static boolean login(String name, String pass) { String sql = "select 1 from users where user_id='" + name + "' and password='" + MD5(pass) + "' LIMIT 1"; String sql2 = String.format("select 1 from users where user_id='%s' and password='%s' LIMIT 1", name, MD5(pass));// System.err.println(sql); System.err.println(sql2); boolean result = executeQuery(sql); if (result) { System.err.println("登录成功,user=" + name + ",pass=" + pass); } else { System.err.println("登录失败,user=" + name + ",pass=" + pass); } return result; } public static boolean executeQuery(String sql) { try { ResultSet rs = stmt.executeQuery(sql); return rs.next(); } catch (SQLException e) { return false; } } public static boolean register(String name, String pass) { String sql = "select 1 from users where user_id='" + name + "'"; if (executeQuery(sql)) { System.err.println("用户名已经存在,name=" + name); return false; } sql = "insert into users(user_id,password) VALUE('" + name + "','" + MD5(pass) + "')"; System.err.println(sql); boolean result = executeUpdate(sql); if (result) { System.err.println("注册成功,user=" + name + ",pass=" + pass); } else { System.err.println("注册失败,user=" + name + ",pass=" + pass); } return result; } public static boolean executeUpdate(String sql) { try { int affectedRows = stmt.executeUpdate(sql); return affectedRows > 0; } catch (SQLException e) { e.printStackTrace(); return false; } } ``` ##### JavaBean实现价格计算: ```java package Dao; public class TotalPrice { private double num_apple; private double num_orange; private double num_banana; private double num_grapefruit; private double num_peach; private double pri_apple; private double pri_orange; private double pri_banana; private double pri_grapefruit; private double pri_peach; private double total_price; public double getNum_apple() { return num_apple; } public void setNum_apple(double num_apple) { this.num_apple = num_apple; this.setPri_apple(num_apple * 5.0); } public double getNum_orange() { return num_orange; } public void setNum_orange(double num_orange) { this.num_orange = num_orange; this.setPri_orange(num_orange * 3.0); } public double getNum_banana() { return num_banana; } public void setNum_banana(double num_banana) { this.num_banana = num_banana; this.setPri_banana(num_banana * 2.0); } public double getNum_grapefruit() { return num_grapefruit; } public void setNum_grapefruit(double num_grapefruit) { this.num_grapefruit = num_grapefruit; this.setPri_grapefruit(num_grapefruit * 4.5); } public double getNum_peach() { return num_peach; } public void setNum_peach(double num_peach) { this.num_peach = num_peach; this.setPri_peach(num_peach * 5.5); } public double getPri_apple() { return pri_apple; } public void setPri_apple(double pri_apple) { this.pri_apple = pri_apple; } public double getPri_orange() { return pri_orange; } public void setPri_orange(double pri_orange) { this.pri_orange = pri_orange; } public double getPri_banana() { return pri_banana; } public void setPri_banana(double pri_banana) { this.pri_banana = pri_banana; } public double getPri_grapefruit() { return pri_grapefruit; } public void setPri_grapefruit(double pri_grapefruit) { this.pri_grapefruit = pri_grapefruit; } public double getPri_peach() { return pri_peach; } public void setPri_peach(double pri_peach) { this.pri_peach = pri_peach; } public double getTotal_price() { this.total_price = this.getPri_apple() + this.getPri_banana() + this.getPri_grapefruit() + this.getPri_grapefruit() + this.getPri_orange() + this.getPri_peach(); return total_price; } } ``` ##### 使用JS实现商城加减号加减商品功能: ```javascript <script> let num_add=new Array(); let num_dec=new Array(); let num_total=new Array(); for(let i=1;i<6;i++){ let add="num_jia".concat(i.toString()); let dec="num_jian".concat(i.toString()); let total="input_num".concat(i.toString()); num_add[i] = document.getElementById(add); num_dec[i] = document.getElementById(dec); num_total[i] = document.getElementById(total); num_add[i].onclick = function () { if (num_total[i].value <= 0 || num_total[i].value == NaN) num_total[i].value = 0; num_total[i].value = parseInt(num_total[i].value) + 1; } num_dec[i].onclick = function () { if (num_total[i].value <= 0 || num_total[i].value == NaN) { num_total[i].value = 0; } else { num_total[i].value = parseInt(num_total[i].value) - 1; } } } </script> ``` ##### 登陆界面按钮样式设计: ```css <style> body { background-color: #faf5e3; background-image:url('../images/loginbackground.jpg'); width: 300px; height: 400px; background-repeat:no-repeat; background-position:left top; background-attachment:fixed; } .write { position:fixed; right:250px; top:40%; } .fm-button { background-color: #ff9000; background-image: -webkit-gradient(linear,left top,right top,from(#ff9000),to(#ff9000)); background-image: linear-gradient(90deg,#ff9000,#ff9000); border: 1px solid #ff9000; border-radius: 3px; font-size: 20px; height: 42px; line-height: 42px; outline: none; color: #fff; width: 20%; cursor: pointer; position:fixed; } .fm-name { background-color: #faf5e3; background-image: -webkit-gradient(linear,left top,right top,from(#faf5e3),to(#faf5e3)); background-image: linear-gradient(90deg,#faf5e3,#faf5e3); border: 1px solid #faf5e3; border-radius: 3px; font-size: 20px; height: 42px; line-height: 42px; outline: none; color: #000; width: 20%; cursor: pointer; position:fixed; } </style> ``` ##### 调用JavaBean实现查询购物车购买的数量: ```jsp <body> <jsp:useBean id="car" scope="page" class="Dao.TotalPrice"> <jsp:setProperty name="car" property="num_apple" param="apple"/> <jsp:setProperty name="car" property="num_orange" param="orange"/> <jsp:setProperty name="car" property="num_banana" param="banana"/> <jsp:setProperty name="car" property="num_grapefruit" param="grapefruit"/> <jsp:setProperty name="car" property="num_peach" param="peach"/> <h1 align="center" style="color: #ff9000">购 物 车</h1> <p align="center">您选购的订单详情如下:</p> <table cellpadding="0" border="1" align="center"> <thead> <tr><th>编号</th><th>商品名</th><th>单价/Kg</th><th>购买数量</th><th>价格</th></tr> </thead> <tbody> <tr> <td>1</td> <td>苹果</td> <td>¥5.0</td> <td><jsp:getProperty name = "car" property="num_apple" /></td> <td><jsp:getProperty name = "car" property="pri_apple" /></td> </tr> <tr> <td>2</td> <td>橘子</td> <td>¥3.0</td> <td><jsp:getProperty name = "car" property="num_orange" /></td> <td><jsp:getProperty name = "car" property="pri_orange" /></td> </tr> <tr> <td>3</td> <td>香蕉</td> <td>¥2.0</td> <td><jsp:getProperty name = "car" property="num_banana" /></td> <td><jsp:getProperty name = "car" property="pri_banana" /></td> </tr> <tr> <td>4</td> <td>柚子</td> <td>¥4.5</td> <td><jsp:getProperty name = "car" property="num_grapefruit" /></td> <td><jsp:getProperty name = "car" property="pri_grapefruit" /></td> </tr> <tr> <td>5</td> <td>桃子</td> <td>¥5.5</td> <td><jsp:getProperty name = "car" property="num_peach" /></td> <td><jsp:getProperty name = "car" property="pri_peach" /></td> </tr> </tbody> </table> <div align="center"> <div >总价为:💴¥<jsp:getProperty name="car" property="total_price"/></div> <a href="pay.html"><button><b>立即支付</b></button></a> <a href="index.jsp"><button><b>取消订单</b></button></a> </div> </jsp:useBean> </body> ``` ## 3、总结 1. Tomcat、Mysql、Git应用技术 2. Java核心技术 3. Jsp开发基础 4. Web前端优化(html、css、js)
C++
UTF-8
824
3.1875
3
[]
no_license
#include <tuple> namespace { template <size_t... n> struct ct_integers_list { template <size_t m> struct push_back { using type = ct_integers_list<n..., m>; }; }; template <size_t max> struct ct_iota_1 { using type = typename ct_iota_1<max-1>::type::template push_back<max>::type; }; template <> struct ct_iota_1<0> { using type = ct_integers_list<>; }; } // namespace anonymous template <size_t... indices, typename Tuple> auto subset(const Tuple& tpl, ct_integers_list<indices...>) -> decltype(std::make_tuple(std::get<indices>(tpl)...)) { return std::make_tuple(std::get<indices>(tpl)...); } template <typename Head, typename... Tail> std::tuple<Tail...> tail(const std::tuple<Head, Tail...>& tpl) { return subset(tpl, typename ct_iota_1<sizeof...(Tail)>::type()); }
Python
UTF-8
1,455
2.890625
3
[]
no_license
import numpy as np import matplotlib.pyplot as plt import scipy.stats as ss import random import bisect import math from math import e #Number of Arms arm_no = [3,10,20,30,40,50] trials = 100 k = 0 T = 0 error = 0 for arms in arm_no: for i in range(0,trials): epsilon = 0.01 t = 1 delta = 0.1 lbd = 9 beta = 1 sigma = 0.5 mu = np.random.uniform(0.0, 1.0, arms) cont = True emp_mean = np.random.binomial(1,mu).astype(float) N = np.full(arms,1.0) t = 0 while(cont): ubounds = (emp_mean + (1+beta)*(1+np.sqrt(epsilon))*np.sqrt(2*sigma*sigma*(1+epsilon)*np.log(np.log((1+epsilon)*N)/delta)/N)) It = np.argmax(ubounds) N[It] = N[It] + 1 draw = np.random.binomial(1,mu[It]) emp_mean[It] = (emp_mean[It]*(N[It]-1.0) + 1.0*draw)/N[It] print(arms,i,t) t = t+1 for k in range(0,arms): if(N[k] <1 + lbd*np.sum(N) - lbd*N[k] ): cont = True else: cont = False break T= t + T k = k+1 if(np.argmax(emp_mean)!= np.argmax(mu)): error = error+1 f = open("output2.txt", "a") print("Average Time or sample complexity for %d number of arms is" %arms, T/trials, file=f) print("Error rate in this case is", error/trials,file=f)
Markdown
UTF-8
2,628
2.703125
3
[ "MIT" ]
permissive
# Generative Adversarial Nets Example ![](https://img.shields.io/badge/Python-3.6.5-brightgreen.svg) ![](https://img.shields.io/badge/Tensorflow-1.8.0-yellowgreen.svg) The original codes are derived from [aymericdamien/TensorFlow-Examples](https://github.com/aymericdamien/TensorFlow-Examples), modifications and adjustments of the codes are made for easily understandable and more flexible. ### Generative Adversarial Network (GAN) Overview ![gan_model](assets/gan_model.png) [aymericdamien/TensorFlow-Examples/notebooks/3_NeuralNetworks/gan.ipynb](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/notebooks/3_NeuralNetworks/gan.ipynb) ### Deep Convolutional Generative Adversarial Network (DCGAN) Overview ![dcgan_model](assets/dcgan_model.png) [aymericdamien/TensorFlow-Examples/notebooks/3_NeuralNetworks/dcgan.ipynb](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/notebooks/3_NeuralNetworks/dcgan.ipynb) ### Results **GAN Generated Results**: ![gan](assets/gan.png) **DCGAN Generated Results**: ![dcgan](assets/dcgan.png) **DCGAN with Batch Normalization Generated Results**: ![dcgan_batch](assets/dcgan_batch.png) **Note**: The trained models of _GAN_, _DCGAN_ as well as _DCGAN with Batch Normalization_ are available at the `data/ckpt` directory. ### Reference - [Generative Adversarial Nets](https://arxiv.org/pdf/1406.2661.pdf) - [Unsupervised representation learning with deep convolutional generative adversarial networks](https://arxiv.org/pdf/1511.06434) - [Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift](https://arxiv.org/abs/1502.03167) - [Understanding the difficulty of training deep feedforward neural networks](http://proceedings.mlr.press/v9/glorot10a.html) - [Generative Adversarial Networks Explained](http://kvfrans.com/generative-adversial-networks-explained/) - [aymericdamien/TensorFlow-Examples/notebooks/3_NeuralNetworks/gan.ipynb](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/notebooks/3_NeuralNetworks/gan.ipynb) - [aymericdamien/TensorFlow-Examples/notebooks/3_NeuralNetworks/dcgan.ipynb](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/notebooks/3_NeuralNetworks/dcgan.ipynb) - [nlintz/TensorFlow-Tutorials](https://github.com/nlintz/TensorFlow-Tutorials) - [nlintz/TensorFlow-Tutorials: 11_gan.py](https://github.com/nlintz/TensorFlow-Tutorials/blob/master/11_gan.py) - [MNIST Dataset](http://yann.lecun.com/exdb/mnist/) - [andy's blog: An Explanation of Xavier Initialization](http://andyljones.tumblr.com/post/110998971763/an-explanation-of-xavier-initialization)
JavaScript
UTF-8
1,110
4.125
4
[]
no_license
/** * Every & Some */ // Every const students = [ { name: "Joao", grade: 4 }, { name: "Pedro", grade: 6 }, { name: "Manuel", grade: 2 }, ]; // let allStudentsPassedTheCourse = false; // for (let i = 0; i < students.length; i++) { // let student = students[i]; // if (student.grade < 6) { // allStudentsPassedTheCourse = false; // break; // } else { // allStudentsPassedTheCourse = true; // } // } // console.log(allStudentsPassedTheCourse); // let allStudentsPassedTheCourse = students.every(function (student) { // return student.grade >= 6; // }); // console.log(allStudentsPassedTheCourse); // Some // let allStudentsPassedTheCourse = true; // for (let i = 0; i < students.length; i++) { // let student = students[i]; // if (student.grade >= 6) { // allStudentsPassedTheCourse = true; // break; // } else { // allStudentsPassedTheCourse = false; // } // } // console.log(allStudentsPassedTheCourse); let allStudentsPassedTheCourse = students.some(function (student) { return student.grade >= 6; }); console.log(allStudentsPassedTheCourse);
Markdown
UTF-8
1,138
2.953125
3
[]
no_license
What is in the package? - CliInterative is a class to interact with user in PHP_CLI environment - MediaSorter is a class to get datetimes and to move files - cli_sort_analyse to analyse files and retrieve dates - cli_sort_execute to execute MediaSorter What it does? Analyse a file and extract different dates : - Date in the filename IMG_20160506_203000.jpg - Modified Date of the file - Exif - Directory 2016/05/06/example.jpg How to use? >php cli_sort_analyse.php Options "input" : this is the directory you want to analyse Options "output" : this is way the script outputs result (print => print, file => create csv file) >Input? /home/josselin/Images/Dossier >Output? (print, file) [print] file Or you can do >php cli_sort_analyse.php /home/josselin/Images/Dossier file >php cli_sort_execute.php Options "input" : this is the csv file previously generated Options "output" : this is the output directory (where files will be moved) >Input? /home/josselin/Images/Dossier/analyse.csv >Output? /home/josselin/Images/Sorted Or you can do >php cli_sort_execute.php /home/josselin/Images/Dossier/analyse.csv /home/josselin/Images/Sorted
Java
UTF-8
479
2.96875
3
[]
no_license
/* boolean regionMatches(int startIndex,String s2,int str2StartIndex,int numChars) boolean regionMatches(boolean ignoreCase,int startIndex,String s2, int str2StartIndex,int numChars) */ class StringTest9 { public static void main(String [] args) { String s1="Taj Mahal is one of the 7 wonders"; String s2="Agra is known as Taj Mahal City"; System.out.println("Result of comparision :"+ s1.regionMatches(true,0,s2,17,9)); } }
JavaScript
UTF-8
411
3.796875
4
[]
no_license
// String-3 -- sameEnds // https://codingjs.wmcicompsci.ca/exercise.html?name=sameEnds&title=String-3 // Given a string, return the longest substring that appears at both the beginning // and end of the string without overlapping. For example, sameEnds("abXab") is "ab". // Examples // sameEnds('abXYab') → true // sameEnds('xx') → true // sameEnds('xxx') → true function sameEnds(nums, len) { }
JavaScript
UTF-8
5,137
2.796875
3
[]
no_license
import {VisitCardiologist, VisitDentist, VisitTherapist} from './visit.js'; import {DragDrop} from "./DragDrop.js"; export class Card { constructor(kard) { this.id = kard.id; this.kard = kard; this.elements = { cardContainer: document.createElement("div"), editBtn: document.createElement('button'), detailsBtn: document.createElement('button'), deleteBtn: document.createElement('button'), doctorDetailsFields: document.createElement('div'), editCardContainer: document.createElement("div") } } render() { this.elements.cardContainer.classList.add('card'); this.elements.editBtn.classList.add('edit-btn'); this.elements.detailsBtn.classList.add('details-btn'); this.elements.deleteBtn.classList.add('delete-btn'); this.elements.doctorDetailsFields.classList.add('doctorDetails'); this.elements.editCardContainer.classList.add('editCardContainer'); this.elements.editBtn.innerText = 'Edit'; this.elements.detailsBtn.innerText = 'Details'; this.elements.deleteBtn.innerText = 'X'; /* loop to fill cards fields */ const cardContentInfo = Object.entries(this.kard); cardContentInfo.forEach(([key, value]) => { if (key.toLowerCase() === "age" || key.toLowerCase() === "bodyindex" || key.toLowerCase() === "illnesses" || key.toLowerCase() === "pressure" || key.toLowerCase() === "lastvisit" || key.toLowerCase() === "id") { let detailsCardField = document.createElement("p"); detailsCardField.classList.add("card-fields"); detailsCardField.innerText = `${key.toUpperCase()}: ${value}`; this.elements.doctorDetailsFields.append(detailsCardField); } else { let mainCardField = document.createElement("p"); mainCardField.classList.add("card-fields"); mainCardField.innerText = `${key.toUpperCase()}: ${value}`; this.elements.cardContainer.append(mainCardField); } }) this.elements.cardContainer.append(this.elements.editBtn, this.elements.deleteBtn); this.elements.cardContainer.insertAdjacentElement('beforeend', this.elements.detailsBtn); document.querySelector('.task-container').append(this.elements.cardContainer); /* Card Btn Listeners */ this.elements.deleteBtn.addEventListener('click', () => this.deleteCardRequest()); this.elements.detailsBtn.addEventListener('click', () => { if (!document.querySelector('.doctorDetails')) { this.elements.cardContainer.append(this.elements.doctorDetailsFields); this.elements.detailsBtn.innerText = 'Hide'; } else { this.elements.detailsBtn.innerText = 'Details'; document.querySelector('.doctorDetails').remove(); } }) this.elements.editBtn.addEventListener('click', () => this.editCard()); DragDrop('.card'); } deleteCardRequest() { fetch(`https://cards.danit.com.ua/cards/${this.id}`, { method: 'DELETE', headers: { 'Authorization': `Bearer ${sessionStorage.getItem('token')}` }, }).then((res) => { if (res.status >= 200 && res.status < 300) { return res; } else { let error = new Error(res.statusText); error.response = res; throw error } }) .then((res) => res.json()) .then(res => { if (res.status === 'Success') { this.elements.cardContainer.remove(); this.elements.deleteBtn.removeEventListener('click', () => this.deleteCardRequest()); } }) } editCard() { const removeBtn = document.querySelectorAll(".edit-btn"); removeBtn.forEach(e => e.classList.add("remove")); if (this.kard.title.toLowerCase() === "cardiologist") { document.querySelector('.task-container').append(this.elements.editCardContainer); const editFormCardiologist = new VisitCardiologist(this.kard); editFormCardiologist.render(this.elements.editCardContainer); } if (this.kard.title.toLowerCase() === "therapist") { document.querySelector('.task-container').append(this.elements.editCardContainer); const editFormVisitTherapist = new VisitTherapist(this.kard); editFormVisitTherapist.render(this.elements.editCardContainer); } else if (this.kard.title.toLowerCase() === "dentist") { document.querySelector('.task-container').append(this.elements.editCardContainer); const editFormVisitDentist = new VisitDentist(this.kard); editFormVisitDentist.render(this.elements.editCardContainer); } } }
Markdown
UTF-8
3,850
2.671875
3
[]
no_license
# Git 服务器搭建 上一章节中我们远程仓库使用了 Github,Github 公开的项目是免费的,但是如果你不想让其他人看到你的项目就需要收费。 这时我们就需要自己搭建一台Git服务器作为私有仓库使用。 接下来我们将以 Centos 为例搭建 Git 服务器。 ### 安装Git ```bash $ yum install curl-devel expat-devel gettext-devel openssl-devel zlib-devel perl-devel $ yum install git ``` 接下来我们 创建一个git用户组和用户,用来运行git服务: ```bash $ groupadd git $ useradd git -g git ``` ### 创建证书登录 收集所有需要登录的用户的公钥,公钥位于id_rsa.pub文件中,把我们的公钥导入到/home/git/.ssh/authorized_keys文件里,一行一个。 如果没有该文件创建它: ```bash $ cd /home/git/ $ mkdir .ssh $ chmod 755 .ssh $ touch .ssh/authorized_keys $ chmod 644 .ssh/authorized_keys ``` ### 初始化Git仓库 * 首先我们选定一个目录作为Git仓库,假定是/home/gitrepo/runoob.git,在/home/gitrepo目录下输入命令: ```bash $ cd /home $ mkdir gitrepo $ chown git:git gitrepo/ $ cd gitrepo $ git init --bare runoob.git Initialized empty Git repository in /home/gitrepo/runoob.git/ ``` 以上命令Git创建一个空仓库,服务器上的Git仓库通常都以.git结尾。 * 然后把仓库所属用户改为git: ```bash $ chown -R git:git runoob.git ``` ### 克隆仓库 ```bash $ git clone git@192.168.45.4:/home/gitrepo/runoob.git Cloning into 'runoob'... warning: You appear to have cloned an empty repository. Checking connectivity... done. ``` 192.168.45.4 为 Git 所在服务器 ip ,你需要将其修改为你自己的 Git 服务 ip。 这样我们的 Git 服务器安装就完成。 * 1. * 2 Procs(进程)参数| 含义| 说明 ------------|------|---------- r |等待执行的任务数|展示了正在执行和等待cpu资源的任务个数。当这个值超过了cpu个数,就会出现cpu瓶颈。 b | 等待IO的进程数量 Memory(内存)参数| 含义| 说明 ------------|------|---------- swpd |正在使用虚拟的内存大小,单位k| free | 空闲内存大小 buff | 已用的buff大小,对块设备的读写进行缓冲 cache | 已用的cache大小,文件系统的cache inact | 非活跃内存大小,即被标明可回收的内存,区别于free和active active |活跃的内存大小 Swap参数| 含义| 说明 ------------|------|---------- si |每秒从交换区写入内存的大小(单位:kb/s) so | 每秒从内存写到交换区的大小 IO参数| 含义| 说明 ------------|------|---------- bi |每秒读取的块数(读磁盘) bo | 每秒写入的块数(写磁盘) system参数| 含义| 说明 ------------|------|---------- in |每秒中断数,包括时钟中断|值越大,会看到由内核消耗的cpu时间会越多 cs |每秒上下文切换数|这两个值越大,会看到由内核消耗的cpu时间会越多 CPU(以百分比表示)参数| 含义| 说明 ------------|------|---------- Us |用户进程执行消耗cpu时间(user time)|us的值比较高时,说明用户进程消耗的cpu时间多,但是如果长期超过50%的使用,那么我们就该考虑优化程序算法或其他措施了 Sy |系统进程消耗cpu时间(system time)|sys的值过高时,说明系统内核消耗的cpu资源多,这个不是良性的表现,我们应该检查原因。 Id |空闲时间(包括IO等待时间) wa |等待IO时间|Wa过高时,说明io等待比较严重,这可能是由于磁盘大量随机访问造成的,也有可能是磁盘的带宽出现瓶颈。
Python
UTF-8
916
3.96875
4
[]
no_license
# Without duplicates lists, list overlap. # Practice: 5 def two_list(list_1, list_2): list_3 = [] for i in list_1: if i in list_2: if i not in list_3: list_3.append(i) return list_3 a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] print(two_list(a,b)) # Randomly generate two lists to test this. import random as rd def rndm_list(): list_1 = rd.sample(range(1, 100), rd.randint(5, 20)) list_2 = rd.sample(range(50, 100), rd.randint(10, 15)) list_3 = [] for i in list_1: if i in list_2: if i not in list_3: list_3.append(i) return list_3 in_list = rndm_list() print(in_list) #List overlap using sets def ovrlp_st(list1, list2): nwst1 = set(list1) nwst2 = set(list2) nwst3 = nwst1.intersection(nwst2) return list(nwst3) a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] print(ovrlp_st(a, b))
Python
UTF-8
1,572
3.359375
3
[]
no_license
import numpy as np points = [] for x in range(2): for y in range(2): for z in range(2): points.append([x, y, z]) points = np.array(points) class Node: def __init__(self, indices): node_points = np.array([points[i] for i in indices]) self.indices = indices self.minimum = node_points.min(axis=0) self.maximum = node_points.max(axis=0) self.means = node_points.mean(axis=0) self.children = [] def construct_tree(points, indices, depth=0, max_depth=3): if len(indices) == 0: return None node = Node(indices) if len(indices) == 1 or depth == max_depth: return node child_indices = [[], [], [], [], [], [], [], []] for i in indices: if points[i, 0] < node.means[0]: if points[i, 1] < node.means[1]: index = 0 else: index = 2 if points[i, 2] < node.means[2]: child_indices[index].append(i) else: child_indices[index + 1].append(i) else: if points[i, 1] < node.means[1]: index = 0 else: index = 2 if points[i, 2] < node.means[2]: child_indices[index + 4].append(i) else: child_indices[index + 5].append(i) for i in range(8): node.children.append(construct_tree(points, child_indices[i], depth + 1)) return node root = construct_tree(points, [i for i in range(len(points))])
Java
UTF-8
1,469
3.453125
3
[]
no_license
package com.alibaba.concurrent.chapter4; import java.util.concurrent.atomic.AtomicLong; /** * @Author shenmeng * @Date 2019/12/5 **/ public class TestAtomic { //创建Long型原子计数器 private static AtomicLong atomicLong = new AtomicLong(); //创建数据源 private static Integer[] arrayOne=new Integer[]{0,1,2,3,0,5,6,0,56,0}; private static Integer[] arrayTwo=new Integer[]{10,2,3,4,0,5,6,0,56,0}; public static void main(String[] args) throws InterruptedException { //线程t1统计数组arrayOne中0的个数 Thread t1 = new Thread(new Runnable() { @Override public void run() { int size=arrayOne.length; for(int i=0;i<size;i++){ if(arrayOne[i].intValue()==0){ atomicLong.incrementAndGet(); } } } }); //线程t2统计数组arrayOne中0的个数 Thread t2 = new Thread(new Runnable() { @Override public void run() { int size=arrayTwo.length; for(int i=0;i<size;i++){ if(arrayTwo[i].intValue()==0){ atomicLong.incrementAndGet(); } } } }); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("count:"+atomicLong.get()); } }
Java
UTF-8
3,877
2.21875
2
[]
no_license
package cdst_be_marche.adapder.integrazioni.suap; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import cdst_be_marche.model.RegistroDocumento; import cdst_be_marche.protocollo.DTO.IntegProtocolloDTO; import cdst_be_marche.protocollo.adapter.IntegRestClientAdapter; import cdst_be_marche.protocollo.model.ObserverRegistryListener; import cdst_be_marche.service.RegistroDocumentoService; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @Lazy @Service public class IntegSuapAdapter { private static final Logger logger = LogManager.getLogger(IntegSuapAdapter.class.getName()); @Autowired IntegRestClientAdapter restClientAdapter; @Autowired IntegSuapFrontieraConfigurator integConfigurator; @Autowired RegistroDocumentoService registroDocumentoService; /** * TODO: USARE COME TEST!!!! * @return * @throws IOException */ public ResponseEntity<String> uploadSingleFileSincronous(IntegProtocolloDTO integDTO,String access_token) throws IOException { ResponseEntity<String> response =null; String serverUrl = integConfigurator.getUrlProtocollo(); response=restClientAdapter.uploadSingleFileSincronous(serverUrl, getDocumentFile(),integDTO,access_token); logger.info("Response code: " + response.getStatusCode()); return response; } /** * Submit in asincronous mode * @param registroDocumento * @param integDTO * @return * @throws IOException */ public ResponseEntity<String> uploadSingleFile(RegistroDocumento registroDocumento,IntegProtocolloDTO integDTO) throws IOException { ResponseEntity<String> response =null; String serverUrl = integConfigurator.getUrlProtocollo(); response=restClientAdapter.uploadSingleFileASincronous(serverUrl, getDocumentFile(registroDocumento),integDTO); logger.info("Response code: " + response.getStatusCode()); return response; } /** * @param registroDocumento * @return * @throws IOException */ public Resource getDocumentFile(RegistroDocumento registroDocumento) throws IOException { return registroDocumentoService.loadFileAsResource(registroDocumento); } /* private static void uploadMultipleFile() throws IOException { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); MultiValueMap<String, Object> body = new LinkedMultiValueMap<>(); body.add("files", getTestFile()); body.add("files", getTestFile()); body.add("files", getTestFile()); HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers); String serverUrl = "http://localhost:8082/spring-rest/fileserver/multiplefileupload/"; RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.postForEntity(serverUrl, requestEntity, String.class); System.out.println("Response code: " + response.getStatusCode()); } */ /** * TODO Get File * @return * @throws IOException */ public static Resource getDocumentFile() throws IOException { Path testFile = Files.createTempFile("test-file", ".txt"); System.out.println("Creating and Uploading Test File: " + testFile); Files.write(testFile, "Hello World !!, This is a test file.".getBytes()); return new FileSystemResource(testFile.toFile()); } }
Java
UTF-8
469
1.851563
2
[]
no_license
package com.agoldberg.hercules.dao; import com.agoldberg.hercules.domain.EnteredRevenueDomain; import com.agoldberg.hercules.store.StoreDomain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Date; @Repository public interface EnteredRevenueDAO extends JpaRepository<EnteredRevenueDomain, Long>{ EnteredRevenueDomain findByLocationAndDate(StoreDomain locationDomain, Date date); }
Markdown
UTF-8
1,776
3.5625
4
[ "MIT" ]
permissive
# Imágenes - Inserción de imágenes. - Sintaxis igual que los enlaces, pero anteponiendo el carácter \! al principio. ```markdown ![texto alt imagen](url "etiqueta") ``` - Parámetros: - texto alt imagen: texto alternativo de la imagen si no se encuentra. - url: dirección de la imagen (absoluta o relativa). - "etiqueta": es opcional y muestra tooltip con información sobre la imagen. ## Ejemplo inserción imágenes ```markdown ![Imagen Batman existe](/images/batman.png "Batman") ![Imagen Batman no existe](/images/batman0.png "Batman") ``` ![Imagen Batman existe](/images/batman.png "Batman") ![Imagen Batman no existe](/images/batman0.png "Batman") ## Imágenes con referencia o marcador - Si existen varias imágenes se puede colocar entre corchetes una numeración a modo de marcador para vincular la imagen al final del contenido del documento. ```markdown ![texto alt imagen][referencia] ... ... ... Al final del documento: [referencia]: url "etiqueta" ``` - Parámetros: - texto alt imagen: texto alternativo de la imagen si no se encuentra. - referencia: marcador utilizado como referencia en la imagen - url: dirección de la imagen (absoluta o relativa). - "etiqueta": es opcional y muestra tooltip con información sobre la imagen. ### Ejemplo imágenes con referencia ```markdown ![Imagen Capitán América][imagen capitan america] ![Imagen Superman][imagen superman] ... ... ... Al final del documento: [imagen capitan america]: /images/capitan-america.png "Capitán América" [imagen superman]: /images/superman.png "Superman" ``` ![Imagen Capitán América][imgcapitanamerica] ![Imagen Superman][imgsuperman] [imgcapitanamerica]: /images/capitan-america.png "Capitán América" [imgsuperman]: /images/superman.png "Superman"
Java
UTF-8
2,379
2.15625
2
[]
no_license
package com.yrdce.ipo.modules.sys.service; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import com.yrdce.ipo.common.constant.ChargeConstant; import com.yrdce.ipo.common.utils.PageUtil; import com.yrdce.ipo.modules.sys.dao.IpoDebitFlowMapper; import com.yrdce.ipo.modules.sys.entity.IpoDebitFlow; import com.yrdce.ipo.modules.sys.vo.DebitFlow; /** * 扣款流水 * @author wq 2016-1-26 * */ public class DebitFlowServiceImpl implements DebitFlowService { @Autowired private IpoDebitFlowMapper debitFlowMapper; /** * 分页查询扣款流水 * @param pageNo * @param pageSize * @param debitFlow * @return */ public List<DebitFlow> queryForPage(String pageNo, String pageSize, DebitFlow debitFlow) { int startIndex = PageUtil.getStartIndex(pageNo, pageSize); int endIndex = PageUtil.getEndIndex(pageNo, pageSize); List<IpoDebitFlow> dbList = debitFlowMapper.queryForPage(startIndex, endIndex, debitFlow); List<DebitFlow> dataList = new ArrayList<DebitFlow>(); for(IpoDebitFlow item :dbList){ DebitFlow entity=new DebitFlow(); BeanUtils.copyProperties(item, entity); entity.setBusinessTypeName(ChargeConstant.BusinessType.getName(item.getBusinessType())); entity.setChargeTypeName(ChargeConstant.ChargeType.getName(item.getChargeType())); entity.setDebitStateName(ChargeConstant.DebitState.getName(item.getDebitState())); entity.setDebitModeName(ChargeConstant.DebitMode.getName(item.getDebitMode())); dataList.add(entity); }; return dataList; } /** * 查询扣款流水数量 * @param debitFlow * @return */ public long queryForCount(DebitFlow debitFlow) { return debitFlowMapper.queryForCount(debitFlow); } /** * 保存扣款流水 * @param debitFlow */ public void save(DebitFlow debitFlow) { debitFlow.setCreateDate(new Date()); debitFlowMapper.insert(debitFlow); } /** * 保存线下扣款流水 * @param debitFlow */ public void saveOffline(DebitFlow debitFlow) { debitFlow.setDebitMode(ChargeConstant.DebitMode.OFFLINE.getCode()); debitFlow.setDebitState(ChargeConstant.DebitState.PAY_SUCCESS.getCode()); save(debitFlow); } }
Java
UTF-8
1,393
2.109375
2
[]
no_license
package com.webdev.app.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.webdev.app.entity.ScienceTopic; import com.webdev.app.service.ScienceTopicService; @RequestMapping(path="/api/scienceTopic") @RestController public class ScienceTopicController { @Autowired ScienceTopicService scienceTopicService; @RequestMapping("/getScienceTopic/{Id}") public ScienceTopic getScienceTopicById(@PathVariable Long Id) { return scienceTopicService.getScienceTopicById(Id); } @RequestMapping("/getAllScienceTopics") public List<ScienceTopic> getAllScienceTopics() { return scienceTopicService.getAllScienceTopics(); } @RequestMapping(value= "/saveScienceTopic", method= RequestMethod.POST) public void saveScienceTopic(@RequestBody ScienceTopic scienceTopic) { scienceTopicService.saveScienceTopic(scienceTopic); } @RequestMapping(value= "/deleteScienceTopic/{Id}", method= RequestMethod.DELETE) public void ScienceTopic(@PathVariable Long Id) { scienceTopicService.deleteScienceTopic(Id); } }
Python
UTF-8
2,386
3.0625
3
[]
no_license
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler import matplotlib.pyplot as plt df_wine = pd.read_csv( 'https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data', header=None) df_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash', 'Alcalinity of ash', 'Magnesium', 'Total phenols', 'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins', 'Color intensity', 'Hue', 'OD280/OD315 of diluted wines', 'Proline'] x, y = df_wine.iloc[:, 1:].values, df_wine.iloc[:, 0].values x_train, x_test, y_train, y_test = train_test_split( x, y, test_size=0.3, random_state=0) # standardScaler---the first PCA step. stdsc = StandardScaler() x_train_std = stdsc.fit_transform(x_train) x_test_std = stdsc.transform(x_test) # 我们将使用NumPy中的linalg.eig函数来计算葡萄酒数据集协方差矩阵的特征对:--the second PCA step. cov_mat = np.cov(x_train_std.T) eigen_vals,eigen_vecs = np.linalg.eig(cov_mat) print('\nEigenvalues \n%s' %eigen_vals) # 非PCA步骤,但是为了方便观看 # 使用NumPy的cumsum函数,我们可以计算出累计方差,其图像可通过matplotlib的step函数绘制: # tot = sum(eigen_vals) # var_exp = [(i/tot) for i in sorted(eigen_vals,reverse=True)] # cum_var_exp = np.cumsum(var_exp) # plt.bar(range(1,14),var_exp,alpha=0.5,align='center',label='individual explained variance') # plt.step(range(1,14),cum_var_exp,where='mid',label='cumulative explained variance') # plt.ylabel('Explained variance ratio') # plt.xlabel('Principal components') # plt.legend(loc='best') # plt.show() # Descending oder---the third PCA Step eigen_pairs = [(np.abs(eigen_vals[i]),eigen_vecs[:,i]) for i in range(len(eigen_vals))] eigen_pairs.sort(reverse=True) # 选择新的特性 w = np.hstack((eigen_pairs[0][1][:,np.newaxis], eigen_pairs[1][1][:,np.newaxis])) print('Matrix W:\n',w) # 映射到新的特征空间中 # x_train_std[0].dot(w) x_train_pca = x_train_std.dot(w) # visualization colors = ['r','b','g'] markers = ['s','x','o'] for l,c,m in zip(np.unique(y_train),colors,markers): plt.scatter(x_train_pca[y_train==l,0], x_train_pca[y_train==l,1], c=c,label=l,marker=m) plt.xlabel('PC 1') plt.ylabel('PC 2') plt.legend(loc='lower left') plt.show()
Swift
UTF-8
2,247
4.1875
4
[ "MIT" ]
permissive
import UIKit // 集合 // Swift 语言提供 Arrays、Sets 和 Dictionaries 三种基本的集合类型用来存储集合数据。数组(Arrays)是有序数据的集。集合(Sets)是无序无重复数据的集。字典(Dictionaries)是无序的键值对的集。 // 数组 var someInts = [Int]() print("\(someInts.count)") someInts.append(1) someInts = [] // 默认值的数组 var threeDoubles = Array(repeating: 1.0, count: 3) var anotherA = Array(repeating: 2.2, count: 3) var sixS = threeDoubles + anotherA var shopplis = ["sd","dasd"] if someInts.isEmpty { print("kong") }else{ print("cunzai") } shopplis += ["edfcv","bhji"] shopplis.insert("sda", at: 1) shopplis.remove(at: 0) shopplis.removeLast() // 数组的遍历 for item in shopplis { print(item) } for (idnex,value) in shopplis.enumerated() { print("\(String(idnex + 1)) \(value)") } // 集合 // 集合(Set)用来存储相同类型并且没有确定顺序的值。当集合元素顺序不重要时或者希望确保每个元素只出现一次时可以使用集合不是数组。 var letters = Set<Character>() letters.insert("a") var favori: Set = ["ser","sdad"] // 集合操作 let oddDigits: Set = [1, 3, 5, 7, 9] let evenDigits: Set = [0, 2, 4, 6, 8] let singleDigitPrimeNumbers: Set = [2, 3, 5, 7] oddDigits.union(evenDigits).sorted() // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] oddDigits.intersection(evenDigits).sorted() // [] oddDigits.subtracting(singleDigitPrimeNumbers).sorted() // [1, 9] oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted() // [1, 2, 9] // 集合成员关系和相等 let houseAnimals: Set = ["🐶", "🐱"] let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"] let cityAnimals: Set = ["🐦", "🐭"] houseAnimals.isSubset(of: farmAnimals) // true farmAnimals.isSuperset(of: houseAnimals) // true farmAnimals.isDisjoint(with: cityAnimals) // true // 字典 var nameOfInteger = [Int: String]() nameOfInteger[11] = "sdasd" var airports: [String : String] = ["YYZ": "rererer","Dub": "dasda"] airports.count airports["asda"] = "wefgwef" airports.updateValue("asda", forKey: "asda") airports["asda"] for airporcode in airports.keys { print("\(airporcode)") }
Markdown
UTF-8
1,675
2.8125
3
[ "MIT" ]
permissive
# saratoga-rounded-corners CSS add-on to create rounded corners in Saratoga weather templates (http://saratoga-weather.org/template/) By: Steve Jenkins My personal site: http://www.stevejenkins.com/ My weather sites: http://weather.lakewebster.com/ & http://weather.sanfordshores.com/ ##INSTRUCTIONS## 1) GitHub users, clone this repo into the root directory of your weather site with: `https://github.com/stevejenkins/saratoga-rounded-corners.git` Or download the zip file into your weather site's root directory and extract the contents into a new directory named `/saratoga-rounded-corners/`. 2) Edit `top.php` in the root directory of your weather site and find the following lines: <link rel="stylesheet" type="text/css" href="<?php echo $SITE['CSSscreen']; ?>" media="screen" title="screen" /> <link rel="stylesheet" type="text/css" href="<?php echo $SITE['CSSprint']; ?>" media="print" /> Add the following line immediately **BELOW** those two lines: <link rel="stylesheet" type="text/css" href="/saratoga-rounded-corners/rounded.css" media="screen" title="screen" /> Et... *VOILA!* You should now have rounded corners for the default Saratoga Templates! Of course, if you've previously modified your CSS, this may or may not work for you. There's not really much damage this file can do, but I'll include a standard disclaimer anyway: **USE THIS FILE AT YOUR OWN RISK! If it:** - blows up your computer - causes heart disease - gives you flatulence or bad dreams - makes your ex-wife come back and ask you for more alimony ...you're on your own. :) Discussion of this CSS file is here: http://www.wxforum.net/index.php?topic=25124.0 Enjoy!
C
UTF-8
270
3.375
3
[]
no_license
#include<stdio.h> int main() { int n, i, p; int a[100]={0}; scanf("%d",&n); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("Enter the position whose element you want to print: "); scanf("%d",&p); printf("%d", *(a+p-1)); return 0; }
Markdown
UTF-8
2,474
2.65625
3
[ "CC-BY-4.0", "CC-BY-SA-4.0", "CC-BY-NC-SA-4.0" ]
permissive
--- description: 'sites that let you tip people, places, or things' --- # Tipping Sites In the earlier years of blockchain, Bitcoin gained a reputation as "magic internet money" in part because it was simple and cheap to send small-dollar tips to random people on the internet. For most of Bitcoin's first decade, transactions that paid no transaction fee would still be mined into the mostly-empty Bitcoin blocks in a reasonable amount of time. This is no longer the case! The Lightning Network brings back the world of simple, free, anonymous tipping and makes it instantaneous—the tip recipient can spend that money immediately, they don't need to wait for a tip to be mined into a block. Many sites will likely spring up to make use of this tipping functionality in interesting ways. Here is a selection that we've discovered! ### Bitcoin Graveyard Links to articles, with the then-current price of Bitcoin, about the hundreds of times that Bitcoin has "died". Place flowers on these graves with Lightning payments. {% embed url="https://niffler.co/bitcoin-graveyard/" %} ### Michael1011's Tip Widget LightningTip connects to LND and allows you to receive tips on your site. While it works great, the example on Michael1011's website does not change to "thanks for your tip!" when the tip is received. {% embed url="https://michael1011.at/lightning.html" %} {% embed url="https://github.com/michael1011/lightningtip" %} ### p2sh.info Tipbox [https://p2sh.info/](https://p2sh.info/) is a fantastic site with lots of transaction statistics gleaned from the Bitcoin blockchain. You can tip the author with Lightning on their tip page. {% embed url="https://tip.p2sh.info/" %} ### Bitcotools.com {% embed url="https://bitcotools.com/donate/" %} ### Jochen Hoenicke Jochen has done some really cool [hacking on the Trezor](https://jochen-hoenicke.de/crypto/trezor-power-analysis/), written guides to [self-custody OMNI assets](https://jochen-hoenicke.de/crypto/omni/) \(such as Tether\), and created this awesome [mempool monitoring tool](https://jochen-hoenicke.de/queue/#0,24h). {% embed url="https://jochen-hoenicke.de/lightning/" %} ### Sergio, Tippin.me [Sergio](https://twitter.com/eiprol) created an easy-to-use Bitcoin Mainnet custodial tipping wallet with Twitter login. {% embed url="https://tippin.me/help-tippin" %} ### LNroute.com Tip the maintainers of the LNroute Lightning resources site. {% embed url="https://tippin.me/@lnroute" %}
Java
UTF-8
3,042
1.921875
2
[ "OGL-UK-3.0" ]
permissive
package uk.nhs.digital.common.forms; import com.onehippo.cms7.eforms.hst.beans.FormBean; import com.onehippo.cms7.eforms.hst.components.AutoDetectFormComponent; import com.onehippo.cms7.eforms.hst.components.info.AutoDetectFormComponentInfo; import org.apache.commons.lang3.ArrayUtils; import org.hippoecm.hst.content.beans.standard.HippoBean; import org.hippoecm.hst.core.component.HstRequest; import org.hippoecm.hst.core.parameters.ParametersInfo; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.nhs.digital.common.forms.behavior.SubscriptionBehavior; import uk.nhs.digital.website.beans.Signup; @SuppressWarnings("rawtypes") @ParametersInfo(type = AutoDetectFormComponentInfo.class) public class CustomAutoDetectFormComponent extends AutoDetectFormComponent { private static Logger log = LoggerFactory.getLogger(CustomAutoDetectFormComponent.class); private static final Class[] ADDITIONAL_AUTO_DETECT_BEHAVIORS = new Class[]{ SubscriptionBehavior.class, ReCaptchaValidationPlugin.class }; @Override protected Class[] getAutoDetectBehaviors() { return ArrayUtils.addAll(super.getAutoDetectBehaviors(), ADDITIONAL_AUTO_DETECT_BEHAVIORS); } @Override public FormBean getFormBean(final HstRequest request) { FormBean formBean = getFormBeanFromSignupDocument(request); if (formBean == null) { formBean = getFormBeanFromPicker(request); } return formBean; } private FormBean getFormBeanFromPicker(final HstRequest request) { final AutoDetectFormComponentInfo paramsInfo = getComponentParametersInfo(request); final String formDocPath = paramsInfo.getForm(); FormBean formBean = getFormBeanFromPath(request, formDocPath); if (formBean == null) { formBean = super.getFormBean(request); } return formBean; } @Nullable private FormBean getFormBeanFromSignupDocument(final HstRequest request) { final HippoBean document = request.getRequestContext().getContentBean(); if (document instanceof Signup) { final Signup signupDocument = (Signup) document; return (FormBean) signupDocument.getFormLink().getLink(); } if (document == null || !document.isHippoDocumentBean() || !(document instanceof FormBean)) { if (log.isDebugEnabled()) { log.warn("*** EFORMS ***"); log.warn("Cannot get the form bean, returning null. Reason: the content bean is null or it does not match the FormBean type [eforms:form]."); log.warn("Override the method [BaseEformComponent#getFormBean(HstRequest)] to get the form bean in a different way, e.g. from a linked bean."); log.warn("Will attempt to get the form bean from the component picker."); log.warn("*** EFORMS ***"); } return null; } return (FormBean) document; } }
Markdown
UTF-8
5,269
3.84375
4
[]
no_license
# Introduction In CPU scheduling, it is important to choose the right algorithm, so that it will take a shorter time to execute all the processes in a queue. In this context, choosing the right solution to schedule the classes is essential to save resources. The chosen algorithms are: 1. **First Come First Serve (FCFS) Scheduling** This algorithm executes processes based on which process comes first in the queue. 2. **Shortest Job First (SJF) Scheduling** This algorithm executes processes based on which process in the queue has a shorter burst time. In this case, the duration of the class. 3. **Priority Scheduling** This algorithm executes processes based on which process in the queue has a higher priority (lower integer = higher priority). # Consideration For this analysis, we considered a few scenarios that would provide more clarity for each scheduling algorithm and made our input accordingly. * For FCFS scheduling, it only depends on which class comes first in the array. * For SJF scheduling, we considered classes that have the same duration. * As for priority scheduling, we considered classes that have the same priority. Hence, the input is as follows: | Course Code | Duration | Priority | Arrival time | | :---: | :---: | :---: | :---: | | CSC 2201 | 3 | 2 | 1 | | CSC 2706 | 2 | 2 | 4 | | INFO 2302 | 3 | 2 | 5 | | CSC 4905 | 9 | 4 | 1 | | CSC 1401 | 2 | 1 | 4 | | CSC 1100 | 1 | 1 | 3 | | INFO 3401 | 2 | 3 | 3 | | CSC 3401 | 2 | 3 | 2 | | CSC 1103 | 1 | 1 | 3 | | INFO 4993 | 4 | 4 | 6 | *Do note that the arrival time for the classes are neglected, as the algorithms chosen are non-preemptive.* # Analysis ## FCFS For FCFS scheduling, the data is as follows: | Course Code | Duration | Waiting time | Turnaround time | | :---: | :---: | :---: | :---: | | CSC 2201 | 3 | 0 | 3 | | CSC 2706 | 2 | 3 | 5 | | INFO 2302 | 3 | 5 | 8 | | CSC 4905 | 9 | 8 | 17 | | CSC 1401 | 2 | 17 | 19 | | CSC 1100 | 1 | 19 | 20 | | INFO 3401 | 2 | 20 | 22 | | CSC 3401 | 2 | 22 | 24 | | CSC 1103 | 1 | 24 | 25 | | INFO 4993 | 4 | 25 | 29 | **Average waiting time = 14.3** **Average turnaround time = 17.2** From the averages provided, FCFS is the least efficient algorithm as some processes had to wait a long time to execute, despite having shorter duration than others. It only executes processes according to their order in the queue, hence if longer classes come earlier in the queue, it will be time consuming. Hence, it is why FCFS is slower than SJF and Priority Scheduling. ## SJF For SJF scheduling, the data is as follows: | Course Code | Duration | Waiting time | Turnaround time | | :---: | :---: | :---: | :---: | | CSC 1100 | 1 | 0 | 1 | | CSC 1103 | 1 | 1 | 2 | | CSC 2706 | 2 | 2 | 4 | | CSC 1401 | 2 | 4 | 6 | | INFO 3401 | 2 | 6 | 8 | | CSC 3401 | 2 | 8 | 10 | | CSC 2201 | 3 | 10 | 13 | | INFO 2302 | 3 | 13 | 16 | | INFO 4993 | 4 | 16 | 20 | | CSC 4905 | 9 | 29 | 29 | **Average waiting time = 8** **Average turnaround time = 10.9** From the averages provided, SJF is the most efficient algorithm as the waiting times for the processes are the shortest overall, compared to FCFS and Priority Scheduling. It executes processes according to their duration, hence it is the most efficient. However, the duration of each classes must be known prior for this algorithm to be usable. ## Priority Scheduling For priority scheduling, the data is as follows: | Course Code | Priority | Duration | Waiting time | Turnaround time | | :---: | :---: | :---: | :---: | :---: | | CSC 1401 | 1 | 2 | 0 | 2 | | CSC 1100 | 1 | 1 | 2 | 3 | | CSC 1103 | 1 | 1 | 3 | 4 | | CSC 2201 | 2 | 3 | 4 | 7 | | CSC 2706 | 2 | 2 | 7 | 9 | | INFO 2302 | 2 | 3 | 9 | 12 | | INFO 3401 | 3 | 2 | 12 | 14 | | CSC 3401 | 3 | 2 | 14 | 16 | | CSC 4905 | 4 | 9 | 16 | 25 | | INFO 4993 | 4 | 4 | 25 | 29 | **Average waiting time = 9.2** **Average turnaround time = 12.1** From the averages provided, Priority Scheduling is faster than FCFS, albeit slower than SJF. It executes processes according to their priorities, hence providing advantages for classes that are more important. However, for classes having the same priority, the algorithm only executes them according to which classes come first, hence it will be less efficient if classes with longer durations come first. If the input is sorted such that the classes with shorter durations come first, this is how the averages would look like: **Average waiting time = 8.4** **Average turnaround time = 11.3** The averages are definitely lower than if the first input is used, however it still takes longer to execute as compared to SJF. # Conclusion From the analysis, it is shown that **Shortest Job First (SJF)** algorithm is the best non-preemptive algorithm to implement class scheduling. It is the most efficient algorithm time-wise, based on the constraints given. Arrival time is neglected as it will only be considered in preemptive scheduling algorithms, as mentioned. However, it is important to note again that the durations for the classes must be known beforehand, so that the algorithm can be used. # Group Members * Muhammad Nur Haikal bin Mohd Rosli (1813779) * Siti Aminah binti Mohd Izazi (1817580) * Nur Nabihah binti Kassim (1819516) * Muhammad Syahmi Aiman bin Mohd Shahrin (1811893)
C#
UTF-8
5,927
2.84375
3
[ "MIT" ]
permissive
using Extendable.Domain; namespace Extendable.Abstraction { public interface IFieldProvider { #region Public Methods /// <summary> /// Add or Update dynamic field process which includes updating cache entry, raise event ..etc /// </summary> /// <typeparam name="TValue">The value type</typeparam> /// <param name="holderType">The type name that contains this dynamic field</param> /// <param name="holderId">The type isntance that contains this dynamic field</param> /// <param name="fieldName">The dynamic field name</param> /// <param name="fieldValue">the dynaic field's value</param> /// <param name="language">in-case of your system in multi-language, this parameter represents language code</param> void AddOrUpdateField<TValue>(string holderType, string holderId, string fieldName, TValue fieldValue, string language = "en"); /// <summary> /// Add new dynamic field process which includes updating cache entry, raise event ..etc /// </summary> /// <param name="holderType">The type name that contains this dynamic field</param> /// <param name="holderId">The type isntance that contains this dynamic field</param> /// <param name="fieldName">The dynamic field name</param> /// <param name="serializedFieldValue">the serialized dynamic field value as string</param> /// <param name="language">in-case of your system in multi-language, this parameter represents language code</param> void AddField(string holderType, string holderId, string fieldName, string serializedFieldValue, string language = "en"); /// <summary> /// Update field process, which includes cache update, database update ..etc /// </summary> /// <param name="holderType">The type name that contains this dynamic field</param> /// <param name="holderId">The type isntance that contains this dynamic field</param> /// <param name="fieldName">The dynamic field name</param> /// <param name="serializedFieldValue">the serialized dynamic field value as string</param> /// <param name="language">in-case of your system in multi-language, this parameter represents language code</param> void UpdateField(string holderType, string holderId, string fieldName, string serializedFieldValue, string language = "en"); /// <summary> /// Get Dynamic field, it will tries to get the value from cache first. /// </summary> /// <param name="holderType">The type name that contains this dynamic field</param> /// <param name="holderId">The type isntance that contains this dynamic field</param> /// <param name="fieldName">The dynamic field name</param> /// <param name="language">in-case of your system in multi-language, this parameter represents language code</param> /// <returns></returns> Field GetField(string holderType, string holderId, string fieldName, string language = "en"); /// <summary> /// Check whether the dynamic field that matches the specified parameter is existed or not /// </summary> /// <param name="holderType">The type name that contains this dynamic field</param> /// <param name="holderId">The type isntance that contains this dynamic field</param> /// <param name="fieldName">The dynamic field name</param> /// <param name="language">in-case of your system in multi-language, this parameter represents language code</param> /// <returns></returns> bool Exists(string holderType, string holderId, string fieldName, string language = "en"); /// <summary> /// Get Dynamic field value, it will tries to get the value from cache first. /// </summary> /// <param name="holderType">The type name that contains this dynamic field</param> /// <param name="holderId">The type isntance that contains this dynamic field</param> /// <param name="fieldName">The dynamic field name</param> /// <param name="defaultValue">The value returned if no existing value there</param> /// <param name="language">in-case of your system in multi-language, this parameter represents language code</param> /// <returns></returns> TValue GetFieldValue<TValue>(string holderType, string holderId, string fieldName, TValue defaultValue = default(TValue), string language = "en"); /// <summary> /// Clear any cached fields /// </summary> void ClearCachedFields(); ///// <summary> ///// Get Saved Fields as IQueryable, It's not mandatory to implement if you won't use it ///// </summary> //IQueryable<Field> QueryAllFields(); #endregion #region Abstract Methods /// <summary> /// Add new field record to the database or any permanent store /// </summary> /// <param name="field">field object</param> void AddFieldValueToDb(Field field); /// <summary> /// Update field record in the database or any permanent store /// </summary> /// <param name="field">field object</param> void UpdateFieldInDb(Field field); /// <summary> /// Update field frmo the database or any permanent store /// </summary> /// <param name="holderType">The type name that contains this dynamic field</param> /// <param name="holderId">The type isntance that contains this dynamic field</param> /// <param name="fieldName">The dynamic field name</param> /// <param name="language">in-case of your system in multi-language, this parameter represents language code</param> Field GetFieldFromDb(string holderType, string holderId, string fieldName, string language = "en"); #endregion } }
Java
UTF-8
648
1.5625
2
[]
no_license
package com.tencent.mm.plugin.fts.a; import android.database.Cursor; import com.tencent.mm.storage.x; public abstract interface h { public abstract Cursor g(String paramString, String[] paramArrayOfString); public abstract Cursor rawQuery(String paramString, String[] paramArrayOfString); public abstract x yM(String paramString); public abstract boolean yN(String paramString); public abstract long yO(String paramString); } /* Location: D:\tools\apktool\weixin6519android1140\jar\classes-dex2jar.jar!\com\tencent\mm\plugin\fts\a\h.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
Markdown
UTF-8
3,824
2.609375
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: <workflowInstanceQueries> ms.date: 03/30/2017 ms.topic: reference ms.assetid: 4fe7ce85-cf9a-4dbf-a8f7-bc9b1fc2fe35 ms.openlocfilehash: 11e301de1ab3dbd4c97f236bfd07c5de4a632272 ms.sourcegitcommit: 093571de904fc7979e85ef3c048547d0accb1d8a ms.translationtype: MT ms.contentlocale: it-IT ms.lasthandoff: 09/06/2019 ms.locfileid: "70398583" --- # <a name="workflowinstancequeries"></a>\<workflowInstanceQueries> Rappresenta una raccolta di elementi di configurazione che rilevano modifiche del ciclo di vita dell'istanza del flusso di lavoro, come l'avvio o il completamento di un evento. Per ulteriori informazioni sulle query del profilo di rilevamento, vedere [profili di rilevamento](../../../windows-workflow-foundation/tracking-profiles.md) [ **\<configuration>** ](../configuration-element.md)\ &nbsp;&nbsp;[ **\<sistema. > ServiceModel**](system-servicemodel-of-workflow.md)\ &nbsp;&nbsp;&nbsp;&nbsp;[ **\<rilevamento >** ](tracking.md)\ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[ **\<> di trackingProfile**](trackingprofile.md)\ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[ **\<> flusso di lavoro**](workflow.md)\ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; **\<> workflowInstanceQueries** ## <a name="syntax"></a>Sintassi ```xml <tracking> <trackingProfile name="Name"> <workflow> <workflowInstanceQueries> <workflowInstanceQuery> <states> <state name="Name"/> </states> </workflowInstanceQuery> </workflowInstanceQueries> </workflow> </trackingProfile> </tracking> ``` ## <a name="attributes-and-elements"></a>Attributi ed elementi Nelle sezioni seguenti vengono descritti gli attributi, gli elementi figlio e gli elementi padre. ### <a name="attributes"></a>Attributi Nessuno. ### <a name="child-elements"></a>Elementi figlio |Elemento|DESCRIZIONE| |-------------|-----------------| |[\<workflowInstanceQuery>](workflowinstancequery.md)|Query usata per rilevare modifiche del ciclo di vita dell'istanza del flusso di lavoro.| ### <a name="parent-elements"></a>Elementi padre |Elemento|Descrizione| |-------------|-----------------| |[\<workflow>](workflow.md)|Elemento di configurazione contenente tutte le query per un flusso di lavoro specifico identificato dalla proprietà **ActivityDefinitionId** .| ## <a name="remarks"></a>Note L'oggetto <xref:System.Activities.Tracking.WorkflowInstanceQuery> viene usato per sottoscrivere gli oggetti <xref:System.Activities.Tracking.TrackingRecord> seguenti: - <xref:System.Activities.Tracking.WorkflowInstanceRecord> - <xref:System.Activities.Tracking.WorkflowInstanceAbortedRecord> - <xref:System.Activities.Tracking.WorkflowInstanceUnhandledExceptionRecord> - <xref:System.Activities.Tracking.WorkflowInstanceTerminatedRecord> - <xref:System.Activities.Tracking.WorkflowInstanceSuspendedRecord> ## <a name="example"></a>Esempio La configurazione seguente sottoscrive i record di rilevamento a livello di istanza del flusso di lavoro per lo stato dell'istanza `Started` usando questa query. ```xml <workflowInstanceQueries> <workflowInstanceQuery> <states> <state name="Started"/> </states> </workflowInstanceQuery> </workflowInstanceQueries> ``` ## <a name="see-also"></a>Vedere anche - <xref:System.ServiceModel.Activities.Tracking.Configuration.WorkflowInstanceQueryElementCollection?displayProperty=nameWithType> - <xref:System.Activities.Tracking.WorkflowInstanceQuery?displayProperty=nameWithType> - [Rilevamento e analisi del flusso di lavoro](../../../windows-workflow-foundation/workflow-tracking-and-tracing.md) - [Profili di rilevamento](../../../windows-workflow-foundation/tracking-profiles.md)
PHP
UTF-8
470
2.65625
3
[]
no_license
<?php declare(strict_types=1); namespace App\Common\Iterator\Exception; use Throwable; final class WorkerNotFound extends \Exception implements Throwable { private const MESSAGE = 'Iterator worker not found for class'; private const CODE = 500; public function __construct(string $message, $code = self::CODE, Throwable $previous = null) { $message = self::MESSAGE . $message; parent::__construct($message, $code, $previous); } }
Markdown
UTF-8
984
2.703125
3
[]
no_license
Install the App: 1. Download the app - git clone https://github.com/AleksandraHlukhova/car_import.git 2. Installs dependencies, download vendor folder - composer install 3. Create .env file - copy .env.example .env 4. Generate key in .env file - php artisan key:generate 5. Make symlink - php artisan storage:link 6. Create tables and make its seeding - php artisan migrate:fresh --seed 7. Start the server - php artisan serve !!!!!!! Registration and logination usual users and admin make from general forms. Change value from 1 to 0 role column the users table to make admin. !!!!!!! App has: 1. Factories and Seeders 2. Customer registration and auth 3. Customer profile: 1. Manager propositions for customer`s apply 2. Products bookmarks 3. Cart for oders 4. Admin: 1. Auth 2. Customer list 3. Customer oders 4. Products (add, update, delete) 5. Add new propositions for customer`s apply Link project on youtube: https://youtu.be/CsHja933nnE
Java
UTF-8
1,366
2.015625
2
[]
no_license
package com.ncr.gratuity.ValueObjects; import java.sql.Date; import javax.persistence.Column; public class NomineeVo { private String n_name; private String n_address; private String n_relation; private Date n_dob; private String n_amount; private byte[] employerSign; public byte[] getEmployerSign() { return employerSign; } public void setEmployerSign(byte[] employerSign) { this.employerSign = employerSign; } public byte[] getSubscriberSign() { return subscriberSign; } public void setSubscriberSign(byte[] subscriberSign) { this.subscriberSign = subscriberSign; } private byte[] subscriberSign; public String getN_amount() { return n_amount; } public void setN_amount(String n_amount) { this.n_amount = n_amount; } public Date getN_dob() { return n_dob; } public void setN_dob(Date n_dob) { this.n_dob = n_dob; } public String getN_relation() { return n_relation; } public void setN_relation(String n_relation) { this.n_relation = n_relation; } public String getN_address() { return n_address; } public void setN_address(String n_address) { this.n_address = n_address; } public String getN_name() { return n_name; } public void setN_name(String n_name) { this.n_name = n_name; } }
JavaScript
UTF-8
1,638
2.59375
3
[]
no_license
var express = require('express'); var authClass = require('./../auth'); var auth = authClass(); class ProductRoutes { constructor(cartService) { this.cartService = cartService; } router() { let router = express.Router(); router.get('/', auth.authenticate(), this.get.bind(this)); router.post('/', auth.authenticate(), this.post.bind(this)); router.put('/:userId', auth.authenticate(), this.put.bind(this)); router.delete('/:id', auth.authenticate(), this.delete.bind(this)); router.delete('/', auth.authenticate(), this.empty.bind(this)); return router; } get(req, res) { return this.cartService.get(req.user) .then((items) => res.json(items)) .catch((err) => res.status(500).json(err)) } post(req, res) { return this.cartService.post(req.user, req.body) .then((cart) => { // console.log("cart: ", cart ) res.json(cart); }) .catch((err) => { // console.log(err); res.status(500).json(err); }) } put(req, res) { //req.body format {"productId": XX, "quantity": [{"old":XX,"new":XX}]} return this.cartService.put(req.params.id, req.body) .then((items) => res.json(items)) .catch((err) => res.status(500).json(err)) } delete(req, res) { return this.cartService.delete(req.params.id) .then((cart) => res.status(200).end()) .catch((err) => res.status(500).json(err)) } empty(req,res) { return this.cartService.empty(req.user.id) .then((items) => res.status(200).end()) .catch((err) => res.status(500).json(err)) } } module.exports = ProductRoutes;
JavaScript
UTF-8
670
3.75
4
[]
no_license
/** * { function_description } * * @param {string} str The string * @param {string} searchString The search string * @return {boolean} { description_of_the_return_value } */ const includes = (str, searchString) => { let searchlen = searchString.length; let strlen = str.length - searchlen + 1; for (let i = 0; i < strlen; i++) { if (str.charAt(i) === searchString.charAt(0)) { let buf = ''; for (let j = 0; j < searchlen; j++) { buf += str.charAt(i + j); } if (buf === searchString) { return true; } } } return false; }; console.assert(includes('abc', 'b') === true);
Java
UTF-8
4,716
1.875
2
[]
no_license
package com.huihuan.eme.domain.db; // Generated 2016-5-4 11:02:30 by Hibernate Tools 3.2.2.GA import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; /** * DetectStation generated by hbm2java */ @Entity @Table(name="detect_station" ,catalog="eme" ) public class DetectStation implements java.io.Serializable { private Long id; private AdministrativeDivision administrativeDivision; private Epb epb; private String detectStationName; private String lat; private String lng; private Set<DataCollectionDevice> dataCollectionDevices = new HashSet<DataCollectionDevice>(0); private Set<DetectAirReport> detectAirReports = new HashSet<DetectAirReport>(0); private Set<DetectAir> detectAirs = new HashSet<DetectAir>(0); private Set<DetectStationContent> detectStationContents = new HashSet<DetectStationContent>(0); public DetectStation() { } public DetectStation(AdministrativeDivision administrativeDivision, Epb epb, String detectStationName, String lat, String lng, Set<DataCollectionDevice> dataCollectionDevices, Set<DetectAirReport> detectAirReports, Set<DetectAir> detectAirs, Set<DetectStationContent> detectStationContents) { this.administrativeDivision = administrativeDivision; this.epb = epb; this.detectStationName = detectStationName; this.lat = lat; this.lng = lng; this.dataCollectionDevices = dataCollectionDevices; this.detectAirReports = detectAirReports; this.detectAirs = detectAirs; this.detectStationContents = detectStationContents; } @Id @GeneratedValue(strategy=IDENTITY) @Column(name="id", unique=true, nullable=false) public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="id_divsion") public AdministrativeDivision getAdministrativeDivision() { return this.administrativeDivision; } public void setAdministrativeDivision(AdministrativeDivision administrativeDivision) { this.administrativeDivision = administrativeDivision; } @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="id_epb") public Epb getEpb() { return this.epb; } public void setEpb(Epb epb) { this.epb = epb; } @Column(name="detect_station_name", length=64) public String getDetectStationName() { return this.detectStationName; } public void setDetectStationName(String detectStationName) { this.detectStationName = detectStationName; } @Column(name="lat", length=20) public String getLat() { return this.lat; } public void setLat(String lat) { this.lat = lat; } @Column(name="lng", length=20) public String getLng() { return this.lng; } public void setLng(String lng) { this.lng = lng; } @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="detectStation") public Set<DataCollectionDevice> getDataCollectionDevices() { return this.dataCollectionDevices; } public void setDataCollectionDevices(Set<DataCollectionDevice> dataCollectionDevices) { this.dataCollectionDevices = dataCollectionDevices; } @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="detectStation") public Set<DetectAirReport> getDetectAirReports() { return this.detectAirReports; } public void setDetectAirReports(Set<DetectAirReport> detectAirReports) { this.detectAirReports = detectAirReports; } @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="detectStation") public Set<DetectAir> getDetectAirs() { return this.detectAirs; } public void setDetectAirs(Set<DetectAir> detectAirs) { this.detectAirs = detectAirs; } @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="detectStation") public Set<DetectStationContent> getDetectStationContents() { return this.detectStationContents; } public void setDetectStationContents(Set<DetectStationContent> detectStationContents) { this.detectStationContents = detectStationContents; } }
Java
UTF-8
971
1.851563
2
[ "Apache-2.0" ]
permissive
package io.github.tesla.ops.common; public class Constant { /** * 部门根节点ID */ public static final Long DEPT_ROOT_ID = 0L; /** * 过滤器类型:入口 */ public static final String FILTER_TYPE_IN = "IN"; /** * 过滤器类型:出口 */ public static final String FILTER_TYPE_OUT = "OUT"; /** * 用户状态:正常 */ public static final Integer USER_STATUS_NORMAL = 1; /** * 用户状态:禁用 */ public static final Integer USER_STATUS_DISABLE = 0; /** * 灰度规则模板类型:freemarker */ public static final String GRAY_RULE_TEMPLATE_FTL = "FTL"; public static final String GRAY_TEMPLATE_PARAM_KEY_CONDITIONS = "conditions"; public static final String GRAY_TEMPLATE_PARAM_KEY_NODES = "nodes"; public static final String GATEWAY_APP_NAME = "TESLA-GATEWAY"; public static final String PLUGIN_TYPE_ENDPOINT = "endpoint"; }
Java
UTF-8
1,478
1.945313
2
[]
no_license
package sc.ql.ast; import sc.ql.ast.Expression.Add; import sc.ql.ast.Expression.And; import sc.ql.ast.Expression.Divide; import sc.ql.ast.Expression.Equal; import sc.ql.ast.Expression.GreaterThan; import sc.ql.ast.Expression.GreaterThanOrEqual; import sc.ql.ast.Expression.LessThan; import sc.ql.ast.Expression.LessThanOrEqual; import sc.ql.ast.Expression.LiteralExpr; import sc.ql.ast.Expression.Multiply; import sc.ql.ast.Expression.Negative; import sc.ql.ast.Expression.Not; import sc.ql.ast.Expression.NotEqual; import sc.ql.ast.Expression.Or; import sc.ql.ast.Expression.Positive; import sc.ql.ast.Expression.Subtract; import sc.ql.ast.Expression.VariableExpr; public interface ExpressionVisitor<T, U> { public T visit(Add node, U context); public T visit(Subtract node, U context); public T visit(Divide node, U context); public T visit(Multiply node, U context); public T visit(Equal node, U context); public T visit(GreaterThanOrEqual node, U context); public T visit(GreaterThan node, U context); public T visit(LessThanOrEqual node, U context); public T visit(LessThan node, U context); public T visit(NotEqual node, U context); public T visit(Or node, U context); public T visit(And node, U context); public T visit(Negative node, U context); public T visit(Not node, U context); public T visit(Positive node, U context); public T visit(VariableExpr node, U context); public T visit(LiteralExpr node, U context); }
Java
UTF-8
1,272
2.359375
2
[]
no_license
package com.airbnb.model; import java.time.LocalDate; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.springframework.format.annotation.DateTimeFormat; @Entity @Table(name = "tbl_available_dates") public class AvailableDates { @Id @GeneratedValue private Long id; @Column @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) private LocalDate startDate; @Column @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) private LocalDate endDate; @ManyToOne(fetch = FetchType.EAGER) private Apartment apartment; public AvailableDates() { super(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public LocalDate getStartDate() { return startDate; } public void setStartDate(LocalDate startDate) { this.startDate = startDate; } public LocalDate getEndDate() { return endDate; } public void setEndDate(LocalDate endDate) { this.endDate = endDate; } public Apartment getApartment() { return apartment; } public void setApartment(Apartment apartment) { this.apartment = apartment; } }
Python
UTF-8
1,609
3.90625
4
[]
no_license
""" You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. Example 1: Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] Output: true Example 2: Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] Output: false Constraints: 2 <= coordinates.length <= 1000 coordinates[i].length == 2 -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4 coordinates contains no duplicate point. """ class Solution(object): def checkStraightLine(self, coordinates): """ :type coordinates: List[List[int]] :rtype: bool """ x1, y1 = coordinates[0] x2, y2 = coordinates[1] for x, y in coordinates[2:]: if (y2 - y1) * (x - x2) != (y - y2) * (x2 - x1): return False return True examples = [ { "input": { "coordinates": [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]], }, "output": True }, { "input": { "coordinates": [[1, 1], [2, 2], [3, 4], [4, 5], [5, 6], [7, 7]], }, "output": False } ] import time if __name__ == '__main__': solution = Solution() for n in dir(solution): if not n.startswith('__'): func = getattr(solution, n) print(func) for example in examples: print '----------' start = time.time() v = func(**example['input']) end = time.time() print v, v == example['output'], end - start
Python
UTF-8
290
2.671875
3
[]
no_license
def get_tree_ids(db, where=''): '''Gets a tuple of tree IDs that are in db.''' query = "select tid from trees" if where != '': query += f' where {where}' c = db.db.cursor() c.execute(query) all_rows = c.fetchall() return list(list(zip(*all_rows))[0])
Java
UTF-8
2,889
2.171875
2
[ "Apache-2.0" ]
permissive
package org.uniprot.api.rest.respository; import static java.util.Arrays.asList; import java.util.Optional; import org.apache.http.client.HttpClient; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.impl.CloudSolrClient; import org.apache.solr.client.solrj.impl.HttpClientUtil; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.common.params.ModifiableSolrParams; import org.springframework.beans.factory.BeanCreationException; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.uniprot.api.common.repository.search.SolrRequestConverter; /** * Configure solr repository beans, that are used to retrieve data from a solr instance. * * @author lgonzales */ @Configuration public class RepositoryConfig { @Bean public RepositoryConfigProperties repositoryConfigProperties() { return new RepositoryConfigProperties(); } @Bean @Profile("live") public HttpClient httpClient(RepositoryConfigProperties config) { // I am creating HttpClient exactly in the same way it is created inside // CloudSolrClient.Builder, // but here I am just adding Credentials ModifiableSolrParams param = null; if (!config.getUsername().isEmpty() && !config.getPassword().isEmpty()) { param = new ModifiableSolrParams(); param.add(HttpClientUtil.PROP_BASIC_AUTH_USER, config.getUsername()); param.add(HttpClientUtil.PROP_BASIC_AUTH_PASS, config.getPassword()); } return HttpClientUtil.createClient(param); } @Bean @Profile("live") public SolrClient solrClient(HttpClient httpClient, RepositoryConfigProperties config) { String zookeeperhost = config.getZkHost(); if (zookeeperhost != null && !zookeeperhost.isEmpty()) { String[] zookeeperHosts = zookeeperhost.split(","); return new CloudSolrClient.Builder(asList(zookeeperHosts), Optional.empty()) .withHttpClient(httpClient) .withConnectionTimeout(config.getConnectionTimeout()) .withSocketTimeout(config.getSocketTimeout()) .build(); } else if (!config.getHttphost().isEmpty()) { return new HttpSolrClient.Builder() .withHttpClient(httpClient) .withBaseSolrUrl(config.getHttphost()) .build(); } else { throw new BeanCreationException( "make sure your application.properties has eight solr zookeeperhost or httphost properties"); } } @Bean @Profile("live") public SolrRequestConverter requestConverter() { return new SolrRequestConverter(); } }
Markdown
UTF-8
4,176
2.515625
3
[]
no_license
--- description: "Recipe of Ultimate Skillet Pizza with Crab for one" title: "Recipe of Ultimate Skillet Pizza with Crab for one" slug: 609-recipe-of-ultimate-skillet-pizza-with-crab-for-one date: 2020-10-14T05:21:26.102Z image: https://img-global.cpcdn.com/recipes/d509806caaf1f3e0/751x532cq70/skillet-pizza-with-crab-for-one-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/d509806caaf1f3e0/751x532cq70/skillet-pizza-with-crab-for-one-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/d509806caaf1f3e0/751x532cq70/skillet-pizza-with-crab-for-one-recipe-main-photo.jpg author: Nathan Allison ratingvalue: 3.5 reviewcount: 7 recipeingredient: - "1/2 cup Kodiak power cake mix" - "1/4 cup water" - "3 oz lump crab meat" - "2 tbsp soft low fat cream cheese" - "1/2 handful fresh spinach leaves" - "1/2 ounce marinated red bell pepper" - "1/2 tbsp bacon bits" - " Shredded low fat Colby jack cheese" - " Crushed red bell pepper and parsley for seasoning" recipeinstructions: - "Combine pancake mix and water to drop biscuit consistency" - "Place in a sprayed 5 inch cast iron skillet" - "Combine your low fat cream cheese, crab meat, and spinach together" - "Be careful not to break up the crab meat too much" - "Place over pizza dough and spread out, some of it will sink in to your dough." - "Low fat Colby jack I used a scale and used 21g a serving is 28g" - "Bacon bits" - "Marinated red bell pepper" - "For seasoning crushed red bell pepper and parsley" - "Bake in a 375 degree oven for 25-27 minutes" - "Here is your MFP info for tracking" categories: - Recipe tags: - skillet - pizza - with katakunci: skillet pizza with nutrition: 196 calories recipecuisine: American preptime: "PT30M" cooktime: "PT33M" recipeyield: "4" recipecategory: Dinner --- ![Skillet Pizza with Crab for one](https://img-global.cpcdn.com/recipes/d509806caaf1f3e0/751x532cq70/skillet-pizza-with-crab-for-one-recipe-main-photo.jpg) Hello everybody, it is Jim, welcome to our recipe page. Today, I'm gonna show you how to prepare a special dish, skillet pizza with crab for one. It is one of my favorites food recipes. This time, I'm gonna make it a little bit unique. This will be really delicious. Skillet Pizza with Crab for one is one of the most well liked of recent trending foods in the world. It's enjoyed by millions every day. It's simple, it's fast, it tastes delicious. They're nice and they look fantastic. Skillet Pizza with Crab for one is something which I've loved my entire life. To begin with this recipe, we must prepare a few components. You can cook skillet pizza with crab for one using 9 ingredients and 11 steps. Here is how you cook it. <!--inarticleads1--> ##### The ingredients needed to make Skillet Pizza with Crab for one: 1. Take 1/2 cup Kodiak power cake mix 1. Prepare 1/4 cup water 1. Take 3 oz lump crab meat 1. Prepare 2 tbsp soft low fat cream cheese 1. Prepare 1/2 handful fresh spinach leaves 1. Prepare 1/2 ounce marinated red bell pepper 1. Take 1/2 tbsp bacon bits 1. Make ready Shredded low fat Colby jack cheese 1. Prepare Crushed red bell pepper and parsley for seasoning <!--inarticleads2--> ##### Instructions to make Skillet Pizza with Crab for one: 1. Combine pancake mix and water to drop biscuit consistency 1. Place in a sprayed 5 inch cast iron skillet 1. Combine your low fat cream cheese, crab meat, and spinach together 1. Be careful not to break up the crab meat too much 1. Place over pizza dough and spread out, some of it will sink in to your dough. 1. Low fat Colby jack I used a scale and used 21g a serving is 28g 1. Bacon bits 1. Marinated red bell pepper 1. For seasoning crushed red bell pepper and parsley 1. Bake in a 375 degree oven for 25-27 minutes 1. Here is your MFP info for tracking So that is going to wrap it up for this exceptional food skillet pizza with crab for one recipe. Thanks so much for your time. I am confident you will make this at home. There is gonna be more interesting food in home recipes coming up. Don't forget to bookmark this page on your browser, and share it to your family, colleague and friends. Thanks again for reading. Go on get cooking!
C#
UTF-8
633
3.46875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Csharp_Basics { class TypeConversionEg { static void Main() { int salary = 2000; float f = salary; double d = f; Console.WriteLine("SALARAY IN int= {0}, SALARAY IN float= {1}, SALARAY IN double= {2} ", salary, f, d); float sal = 2500.89f; int sal2 = Convert.ToInt32(sal); Console.WriteLine("SALARAY IN float= {0}, SALARAY IN int= {1}", sal, sal2); Console.Read(); } } }
Java
UTF-8
8,004
2.0625
2
[]
no_license
package com.example.runtimepermission; import android.Manifest; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private static final int REQUST_CAMERA = 123; private static final int REQUST_CONTACTS = 456; private static final int REQUST_STORAGE = 789; private static final int PERMISSSION_CAMERA = 56; private static final int PERMISSSION_CONTACTS = 78; private static final int PERMISSSION_STORAGE = 90; PermissionUtil permissionUtil; //Check Permission... private int checkPermission(int permission) { int status = PackageManager.PERMISSION_DENIED; switch (permission) { case PERMISSSION_CAMERA: status = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA); break; case PERMISSSION_CONTACTS: status = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS); break; case PERMISSSION_STORAGE: status = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE); break; } return status; } //Request New Permission..... private void requestPermission(int permission) { switch (permission) { case PERMISSSION_CAMERA: ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUST_CAMERA); break; case PERMISSSION_CONTACTS: ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, REQUST_CONTACTS); break; case PERMISSSION_STORAGE: ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUST_STORAGE); break; } } private void permissionExplanation(final int permission) { AlertDialog.Builder builder = new AlertDialog.Builder(this); if (permission == PERMISSSION_CAMERA) { builder.setMessage("This app must need Camera permission.."); builder.setTitle("Camera permission Needed.."); } if (permission == PERMISSSION_CONTACTS) { builder.setMessage("This app must need Contact permission.."); builder.setTitle("Contacts permission Needed.."); } if (permission == PERMISSSION_STORAGE) { builder.setMessage("This app must need Storage permission.."); builder.setTitle("Storage permission Needed"); } builder.setPositiveButton("Allow", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (permission == PERMISSSION_CAMERA) requestPermission(PERMISSSION_CAMERA); else if (permission == PERMISSSION_CONTACTS) requestPermission(PERMISSSION_CONTACTS); else if (permission == PERMISSSION_STORAGE) requestPermission(PERMISSSION_STORAGE); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); permissionUtil = new PermissionUtil(this); } //********************************************** public void cameraAccess(View view) { if (checkPermission(PERMISSSION_CAMERA) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { permissionExplanation(PERMISSSION_CAMERA); } else if (!permissionUtil.checkPermission("camera")) { requestPermission(PERMISSSION_CAMERA); permissionUtil.updatePermission("camera"); } else { Toast.makeText(this, "Please allow camera permission in your app setting ", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(); intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", this.getPackageName(), null); intent.setData(uri); this.startActivity(intent); } } else { Toast.makeText(this, "You have Camera Permission..", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(this, Main2Activity.class); intent.putExtra("message", "You can now take photos and pictures.."); startActivity(intent); } } public void storageWrite(View view) { if (checkPermission(PERMISSSION_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) { permissionExplanation(PERMISSSION_STORAGE); } else if (!permissionUtil.checkPermission("storage")) { requestPermission(PERMISSSION_STORAGE); permissionUtil.updatePermission("storage"); } else { Toast.makeText(this, "Please allow storage permission in your app setting ", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(); intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", this.getPackageName(), null); intent.setData(uri); this.startActivity(intent); } } else { Toast.makeText(this, "You have Storage Permission..", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(this, Main2Activity.class); intent.putExtra("message", "You can now access your storage.."); startActivity(intent); } } public void contactsAccess(View view) { if (checkPermission(PERMISSSION_CONTACTS) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CONTACTS)) { permissionExplanation(PERMISSSION_CONTACTS); } else if (!permissionUtil.checkPermission("contacts")) { requestPermission(PERMISSSION_CONTACTS); permissionUtil.updatePermission("contacts"); } else { Toast.makeText(this, "Please allow contact permission in your app setting ", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(); intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", this.getPackageName(), null); intent.setData(uri); this.startActivity(intent); } } else { Toast.makeText(this, "You have Contact Permission..", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(this, Main2Activity.class); intent.putExtra("message", "You can now read your contacts.."); startActivity(intent); } } //********************************************** }
C#
UTF-8
949
2.6875
3
[]
no_license
using System.Collections.Generic; using System.Linq; using AutoMapper; using NoQ.Framework.Extensions; namespace NoQ.Framework.Mapping { public abstract class AutoObjectMapper<TSource, TDestination> : IObjectMapper<TSource, TDestination> { protected readonly IMapper _mapper; public AutoObjectMapper() { IConfigurationProvider config = ConfigureMap(); config.AssertConfigurationIsValid(); _mapper = config.CreateMapper(); } public TDestination Map(TSource source) => _mapper.Map<TDestination>(source); public TDestination[] Map(IEnumerable<TSource> source) { source.VerifyNotNull(nameof(source)); return source.Select(Map) .ToArray(); } protected virtual IConfigurationProvider ConfigureMap() => new MapperConfiguration(cfg => cfg.CreateMap<TSource, TDestination>()); } }
Java
UTF-8
804
2.53125
3
[]
no_license
package com.schimidtsolutions.interceptor; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.Priority; import javax.interceptor.Interceptor; import javax.interceptor.InvocationContext; import com.schimidtsolutions.interceptor.annotations.ObjectObservable; @Interceptor @ObjectObservable @Priority( Interceptor.Priority.APPLICATION ) public class ObjectInterceptor { @PostConstruct private Object init(InvocationContext ic) throws Exception { System.out.println( String.format( "Creating object... %s", ic.getTarget() ) ); return ic.proceed(); } @PreDestroy private Object finalize( InvocationContext ic ) throws Exception{ System.out.println( String.format( "Destroing object... %s", ic.getTarget() ) ); return ic.proceed(); } }
Python
UTF-8
637
2.53125
3
[ "MIT" ]
permissive
import urllib from lxml import html from subprocess import * url = "http://www.rtve.es/infantil/series/peppa-pig/" try: page = html.fromstring(urllib.urlopen(url).read()) for link in page.xpath("//a[@class='link']"): url2 = "http://www.rtve.es" + link.get("href") print "URL ", link.get("href") page2 = html.fromstring(urllib.urlopen(url2).read()) for link2 in page2.xpath("//a"): url3 = link2.get("href") if ("http://" in url3) and ("video" in url3) and ("ingles" not in url3): print "URL2 " + url3 call(["/usr/local/bin/youtube-dl", "--prefer-ffmpeg", url3]) except Exception as e: print e
TypeScript
UTF-8
853
3.140625
3
[ "MIT", "Apache-2.0" ]
permissive
/** 性别枚举 */ export enum SexEnum { // 男 male = 1, // 女 female = 2, // 未知 unknown = 3, } /** 用户状态枚举 */ export enum UserStatus { // 禁用 disable = 0, // 启用 enable = 1, } /** 用户类型 */ export enum UserType { /** 普通用户 */ common = 0, /** 超级管理员 */ admin = 1, } /** 用户类型 */ export interface UserProps { _id: string username: string password?: string nickname?: string roles: string[] avatar?: string mobile?: string email?: string sex?: SexEnum type?: UserType remark?: string status?: UserStatus } export interface UserQueryParams { /** 用户名 */ username?: string /** 昵称 */ nickname?: string /** 部门id */ deptId?: number | string /** 当前页 */ pageNumber?: number /** 分页数目 */ pageSize?: number }
Java
UTF-8
515
2.640625
3
[]
no_license
public String toStringInternal() { if (charset == null) { charset = DEFAULT_CHARSET; } // new String(byte[], int, int, Charset) takes a defensive copy of the // entire byte array. This is expensive if only a small subset of the // bytes will be used. The code below is from Apache Harmony. CharBuffer cb; cb = charset.decode(ByteBuffer.wrap(buff, start, end-start)); return new String(cb.array(), cb.arrayOffset(), cb.length()); }
PHP
UTF-8
2,282
2.546875
3
[]
no_license
<?php /** * Created by PhpStorm. * User: gusta */ //So funciona se desativar os erros! ini_set('display_errors', 0); require_once "../vendor/autoload.php"; //include("../libs/mpdf/mpdf.php"); //require_once "../lib/mpdf/mpdf.php"; require_once "../dao/relatorioDAO.php"; $dao = new relatorioDAO(); $listObjs = $dao->relatorio02(); $dia = $dao ->dataAtual(); $hr = $dao ->horaAtual(); $html = " <h1 style='text-align: center; font-family: Arial, sans-serif'>RELATÓRIO DE BENEFICIÁRIOS E CIDADES</h1> <table border='1' cellspacing='3' cellpadding='3' >"; $html .= "<tr> <th style='text-align: center'>ID BENEFICIARIES</th> <th style='text-align: center'>NOME DO BENEFICIARIES</th> <th style='text-align: center'>CODIGO NIS</th> <th style='text-align: center'>ID CIDADE</th> <th style='text-align: center'>NOME CIDADE</th> <th style='text-align: center'>CODIGO SIAFI</th> <th style='text-align: center'>ID ESTADO</th> </tr>"; foreach ($listObjs as $var): $html.= "<tr> <td style='text-align: center'>$var->id_beneficiaries</td> <td style='text-align: center'>$var->str_name_person</td> <td style='text-align: center'>$var->str_nis</td> <td style='text-align: center'>$var->id_city</td> <td style='text-align: center'>$var->str_name_city</td> <td style='text-align: center'>$var->str_cod_siafi_city</td> <td style='text-align: center'>$var->tb_state_id_state</td> </tr>"; endforeach; $html .= "</table>"; $html .= "<p>Relatório gerado no dia $dia às $hr</p>"; $mpdf=new \Mpdf\Mpdf(); //$mpdf=new mPDF(); $mpdf->SetCreator(PDF_CREATOR); $mpdf->SetAuthor('Gustavo Rodrigues Lima Soares'); $mpdf->SetTitle('Relatório PDF com a lista de todos os beneficiários e a cidade a qual pertencem, com todos os dados do benefiário e da cidada, ordenados por cidade e posteriormente por nome do beneficário'); $mpdf->SetSubject('Sistema EconomiC Analyzer'); $mpdf->SetKeywords('TCPDF, PDF, trabalho PHP'); $mpdf->SetDisplayMode('fullpage'); $mpdf->nbpgPrefix = ' de '; $mpdf->setFooter('Página {PAGENO}{nbpg}'); $mpdf->WriteHTML($html); $mpdf->Output('economicAnalyzer.pdf','I'); exit;
Java
UTF-8
173
1.789063
2
[]
no_license
package br.ucb.achei.empresas.model.interfaces; import java.io.Serializable; public interface AbstractEntity extends Serializable { public Integer getId(); }
PHP
UTF-8
810
2.609375
3
[]
no_license
<?php function insertUsuarios($id, $nombre, $contrasenia, $edad, $altura, $peso, $genero) { $sql = "INSERT INTO usuarios VALUES ($id, '$nombre', '$contrasenia', $edad, $altura, $peso, '$genero')"; $dwes = abrir_conexion(); $resultado = $dwes->query($sql); if ($resultado) { echo "Se han insertado los valores correctamente en la tabla<br>"; } else { echo "Lo sentimos, no se han podido insertar los valores."; } cerrar_conexion($dwes); } function insertActividades($id_Usuarios, $id_Actividades) { $sql = "INSERT INTO usuarios_actividades VALUES ($id_Usuarios, $id_Actividades)"; $dwes = abrir_conexion(); $resultado = $dwes->query($sql); if ($resultado) { header("Location: ../php/actividades.php"); } cerrar_conexion($dwes); } ?>
TypeScript
UTF-8
3,230
2.796875
3
[ "MIT" ]
permissive
export interface ShipInformation { /** einkenni - Einkennisnúmer skips */ id: string /** skipaskrarnumber - Skipaskrárnúmer */ shipNumber?: number /** heitiSkips - Heiti skips */ name: string /** timabil - Fiskveiðiár */ timePeriod: string } export interface CatchQuotaCategory { /** kvotategund - Auðkenni fisktegundar */ id?: number /** kvotategundHeiti - Heiti fisktegundar */ name: string /** uthlutun - Magn sem skip fékk úthlutað af fisktegund á timabilinu */ allocation?: number /** serstokUthlutun - Magn sem skip fékk úthlutað sérstaklega af fisktegund á tímabilinu */ specialAlloction?: number /** milliAra - Magn sem skip setti á milli fiskveiðiára af fisktegund*/ betweenYears?: number /** milliSkipa - Magn sem skip setti á milli skipa af fisktegund*/ betweenShips?: number /** aflamark - Magn aflamarks skips fyrir fisktegund (uthlutun, serstok_uthlutun, milli_ara, milli_skipa lagt saman) */ catchQuota?: number /** afli - Magn af fisktegund sem skipið hefur raunverulega veitt á tímabilinu */ catch?: number /** stada - Staða skips á tímabilinu (afli dreginn frá aflamarki) */ status?: number /** tilfaersla - Magn sem skip hefur fært til af fisktegund á aðrar fisktegundir á tímabilinu */ displacement?: number /** nyStada - Uppfærð staða skips (tekið tillit af tilfærslu: tilfærsla dregin frá stöðu) */ newStatus?: number /** aNaestaAr - Magn sem skip sendir á næsta ár af fisktegund fyrir tímabilið */ nextYear?: number /** umframafli - Magn umframafla tegundar fyrir skip á tímabilinu */ excessCatch?: number /** onotad - Magn fisktegundar sem er ónotuð eftir útreikninga á tímabilinu */ unused?: number /** heildarAflamark - Magn heildaraflamarks tiltekinnar fisktegundar á tímabilinu */ totalCatchQuota?: number /** hlutdeild - Hlutfall hlutdeildar sem skip á í fisktegund á tímabilinu. (0,5 => 0,5%) */ quotaShare?: number /** ANaestaArKvoti - Magn sem skip setur yfir á næsta ár af fisktegund fyrir tímabil út frá kvóta */ nextYearQuota?: number /** afNaestaAriKvoti - Magn sem skip tekur af næsta ári af fisktegund fyrir tímabil út frá kvóta */ nextYearFromQuota?: number /** prosentaANaestaArKvoti - Föst prósenta sem skip þarf að setja á næsta ár af fisktegund fyrir tímabil út frá kvóta */ percentNextYearQuota?: number /** prosentaAfNaestaArKvoti - Föst prósenta sem skip þarf að setja af næsta ári af fisktegund fyrir tímabil út frá kvóta */ percentNextYearFromQuota?: number /** Úthlutað/Áætlað aflamark */ allocatedCatchQuota?: number /** thorskigildi - Þorskígildi fisktegundar. Stuðull sem segir til um verðmæti fisktegundar út frá þorsk */ codEquivalent?: number } export interface ShipStatus { /** skipUpplysingar */ shipInformation: ShipInformation /** aflamarkstegundir */ catchQuotaCategories: CatchQuotaCategory[] } /** Kvótategund */ export interface QuotaType { /** kvotategund */ id?: number /** kvotategundHeiti */ name: string /** thorskigildi */ codEquivalent?: number /** heildarAflamark */ totalCatchQuota?: number }
Java
UTF-8
454
2.171875
2
[]
no_license
package com.aw.platform.roles; import com.aw.platform.NodeRole; import com.aw.platform.PlatformNode.RoleSetting; /** * Settings for config DB, including defaults for single-node operation */ public enum ConfigDbWorker implements RoleSetting { /** * no real configuration at this point */ WORKER_DB_PORT; public String toString() { return name().toLowerCase(); } @Override public NodeRole getRole() { return NodeRole.CONFIG_DB_WORKER; } }
Markdown
UTF-8
898
2.609375
3
[]
no_license
# Integrating-Databases **Homogeneous Database Integration (Relational)** It involves writing sql queries in such a way that we can achieve the integration without physically combining the databases. Sql queries can be written such that the query divides into individual databases and then result is combined and is presented in the output. Presentation for the project can be found [here](https://drive.google.com/open?id=1GXD2jiHa5ESF8JNsfa2xgb7vPknk567mo0Rd0-wUzjs) **Heterogeneous Database Integration (Relational and Xml)** For heterogeneous integration of databases mediated schema is required using which integration can be achieved. Presentation for the project can be found [here](https://drive.google.com/file/d/1NLwuwIMRnTKPKtDGjzEr7bR6ncKLBE-M/view?usp=sharing) [Complete Project Report](https://drive.google.com/file/d/1K-Kss_al0Dg0YVledWJ1wU2GlZ59DGpF/view?usp=sharing)
C
UTF-8
408
2.6875
3
[]
no_license
/* * main.c * * Created on: Jan 4, 2020 * Author: user */ #include <stdio.h> #include <stdlib.h> #include "assembler.h" int main(int argc, char*argv[]) { int i; if (argc < 2) { fprintf(stderr,"expecting file names\n"); fprintf(stderr,"USAGE: assembler file...\n"); exit(1); } for (i = 1; i < argc; ++i) { assembler(argv[i]); } return 0; }
Java
UTF-8
452
1.890625
2
[]
no_license
package com.my.hu.datalist; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; /** * Created by hu on 9/7/16. */ public class ItemClickListener implements AdapterView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { ListView lView=(ListView)adapterView; Log.i("hook_onItemClick",""+i); } }
C#
UTF-8
15,206
2.640625
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Media; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace MiniMineSweeper { public partial class Form1 : Form { public Form1() { InitializeComponent(); //DetermineGameLevel(); } #region Introduce Objects and variables GameOverForm GameOverForm = new GameOverForm(); GameWon GamewonForm = new GameWon(); MineBox mine = new MineBox(); StatisticsForm statisticF = new StatisticsForm(); List<int> bestRecord = new List<int>(); //MineBox[,] mi = new MineBox[8,8]; List<int> mineNumbers; int _numberofWin = 0; int _numberofGames = -1; int _bestRecord; bool time = false; int _numofFlags; #endregion public string GameLevelCmbBox { get { return GameLevelComboBox1.Text; } set { GameLevelComboBox1.Text = value; } } private void ByeSound() { SoundPlayer snd = new SoundPlayer(Path.Combine(Application.StartupPath, "bye-bye-1.wav")); snd.Play(); } /// <summary> /// This function determine a successfully end game /// </summary> private void SuccessGameEnd() { time = true; if (OpenorFlag()) { SoundPlayer snd = new SoundPlayer(Path.Combine(Application.StartupPath, "gameWin.wav")); snd.Play(); time = false; GamewonForm.TimeLbl = timetoolStripStatusLabel3.Text; _numberofWin += 1; GamewonForm.NumberofGameWon = _numberofWin.ToString(); GamewonForm.NumberofGameplayed = _numberofGames.ToString(); //GamewonForm.BestRecord = GamewonForm.Datetime = DateTime.Now.ToString(); bestRecord.Add(int.Parse(timetoolStripStatusLabel3.Text)); bestRecord.Sort(); _bestRecord = bestRecord[0]; GamewonForm.BestRecord = _bestRecord.ToString(); if (GamewonForm.ShowDialog() == DialogResult.OK) DetermineGameLevel(); else { ByeSound(); Thread.Sleep(800); this.Close(); } } } /// <summary> /// This Function determine that whether all of the states are open/flag, or not /// </summary> /// <returns></returns> private bool OpenorFlag() { bool ok = false; foreach (MineBox ctrl in GamePanel.Controls) { if (ctrl.State == MineState.Open || ctrl.State == MineState.Flag) ok = true; else { ok = false; return false; } } return ok; } //System.Threading.Timer tm = new System.Windows.Forms.Timer(); /// <summary> /// This Function reveals all blank and numbers /// </summary> /// <param name="i"></param> /// <param name="j"></param> private void ClickaNullBox(int i, int j) { _hasnull(i - 1, j - 1); _hasnull(i, j - 1); _hasnull(i + 1, j - 1); _hasnull(i - 1, j); _hasnull(i + 1, j); _hasnull(i - 1, j + 1); _hasnull(i, j + 1); _hasnull(i + 1, j + 1); } private void _hasnull(int i, int j) { int row, column; if (mine.GameLevel == MineGameLevel.Beginner) { row = 9; column = 9; } else if (mine.GameLevel == MineGameLevel.Intermediate) { row = 16; column = 16; } else { row = 25; column = 25; } if (i < 0 || i > row - 1) return; if (j < 0 || j > column - 1) return; int _indexofCurrentPlace = (i * row) + (j + 1); MineBox index = ((MineBox)GamePanel.Controls[((i * row) + (j + 1)) - 1]); //if ((index.State == MineState.Close || index.State == MineState.Question) && (index.MineArround == 1 || index.MineArround == 2 || index.MineArround == 3 || index.MineArround == 4 || // index.MineArround == 5 || index.MineArround == 6 || index.MineArround == 7 || index.MineArround == 8)) if ((index.State == MineState.Close || index.State == MineState.Question) && (index.MineArround != 0)) { ((MineBox)GamePanel.Controls[_indexofCurrentPlace - 1]).State = MineState.Open; //SoundPlayer snd = new SoundPlayer(Path.Combine(Application.StartupPath, "click.wav")); //snd.Play(); return; } else if ((index.State == MineState.Close || index.State == MineState.Question) && !index.HasMine) { ((MineBox)GamePanel.Controls[_indexofCurrentPlace - 1]).State = MineState.Open; ClickaNullBox(i, j); } else return; //((MineBox)GamePanel.Controls[_indexofCurrentPlace - 1]).State = MineState.Open; //int index = ((i * 9) + (j + 1)); //if(((MineBox)GamePanel.Controls[index - 1]).State == MineState.Close ); //return ((MineBox)GamePanel.Controls[index - 1]).HasMine; //return mi[i, j].HasMine; } /// <summary> /// This Function reveals all mines /// </summary> public void GameOver() { time = false; foreach (MineBox ctrl in GamePanel.Controls) { if (ctrl.HasMine) ctrl.State = MineState.Open; //GamePanel.Enabled = false; } this.GameOverForm.TimeLbl = timetoolStripStatusLabel3.Text; GameOverForm.TimeLbl = timetoolStripStatusLabel3.Text; GameOverForm.NumberofGameWon = _numberofWin.ToString(); GameOverForm.NumberofGameplayed = _numberofGames.ToString(); GameOverForm.BestRecord = _bestRecord.ToString(); GameOverForm.Datetime = DateTime.Now.ToString(); //GamewonForm.BestRecord = if (GameOverForm.ShowDialog() == DialogResult.OK) DetermineGameLevel(); else { ByeSound(); Thread.Sleep(800); this.Close(); } } /// <summary> /// Determine game level and their rows and columns (Beginner(9*9), Intermediate(16*16) and Exper(16*30)) /// </summary> /// <returns></returns> private void DetermineGameLevel() { if (GameLevelComboBox1.Text == "Beginner") { this.Height = this.Width = 315; GamePanel.Width = GamePanel.Height = 185; FlagtoolStripStatusLabel3.Text = "10"; _numofFlags = 10; StartGame(9, 9, 10, MineGameLevel.Beginner); } else if (GameLevelComboBox1.Text == "Intermediate") { GameLevelCmbBox = "Intermediate"; this.Height = 460; this.Width = 430; GamePanel.Width = GamePanel.Height = 325; FlagtoolStripStatusLabel3.Text = "32"; _numofFlags = 32; StartGame(16, 16, 32, MineGameLevel.Intermediate); } else if (GameLevelComboBox1.Text == "Expert") { GameLevelCmbBox = "Expert"; this.Height = 630; this.Width = 630; GamePanel.Width = 505; GamePanel.Height = 505; FlagtoolStripStatusLabel3.Text = "75"; _numofFlags = 75; StartGame(25, 25, 75, MineGameLevel.Expert); } } private List<int> GuessMineNumbers(int row, int column, int mine) { List<int> list = new List<int>(); while (list.Count < mine) { Random rnd = new Random(); int number = rnd.Next(1, (row * column) + 1); if (list.IndexOf(number) >= 0) continue; list.Add(number); } return list; } private void StartGame(int row, int column, int mines, MineGameLevel gameLevel) { time1 = 0; time = false; _numberofGames += 1; timetoolStripStatusLabel3.Text = "0"; GamePanel.Controls.Clear(); mineNumbers = GuessMineNumbers(row, column, mines); for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { mine = new MineBox() { //Width = 20, //Height = 20, Left = j * 20, Top = i * 20, Index = (i * row) + (j + 1), State = MineState.Close, GameLevel = (MineGameLevel)gameLevel }; mine.OnGameOver += GameOver; mine.onClickNull += ClickaNullBox; mine.onSuccessEndGame += SuccessGameEnd; mine.OnClickFlagorQuestion += NumberofFlags; mine.HasMine = (mineNumbers.IndexOf(mine.Index) >= 0); GamePanel.Controls.Add(mine); //mi[i, j] = mine; } } for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { int neighbors = 0; if (_hasMine(row, column, i - 1, j - 1)) neighbors++; if (_hasMine(row, column, i, j - 1)) neighbors++; if (_hasMine(row, column, i + 1, j - 1)) neighbors++; if (_hasMine(row, column, i - 1, j)) neighbors++; if (_hasMine(row, column, i + 1, j)) neighbors++; if (_hasMine(row, column, i - 1, j + 1)) neighbors++; if (_hasMine(row, column, i, j + 1)) neighbors++; if (_hasMine(row, column, i + 1, j + 1)) neighbors++; int index = ((i * row) + (j + 1)); ((MineBox)GamePanel.Controls[index - 1]).MineArround = neighbors; //mi[i, j].MineArround = neighbors; } } } private void NumberofFlags(bool numofFlag) { int x = _numofFlags; if (numofFlag == true && _numofFlags > 0) { FlagtoolStripStatusLabel3.Text = (Convert.ToInt32(FlagtoolStripStatusLabel3.Text) - 1).ToString(); _numofFlags -= 1; } else if (numofFlag == false && _numofFlags <= x) { FlagtoolStripStatusLabel3.Text = (Convert.ToInt32(FlagtoolStripStatusLabel3.Text) + 1).ToString(); _numofFlags += 1; } } /// <summary> /// Determine whether a Button is mine or not /// </summary> /// <param name="Index"></param> /// <returns></returns> private bool _hasMine(int row, int column, int i, int j) { if (i < 0 || i > row - 1) return false; if (j < 0 || j > column - 1) return false; int index = ((i * row) + (j + 1)); return ((MineBox)GamePanel.Controls[index - 1]).HasMine; //return mi[i, j].HasMine; } private void newGameToolStripMenuItem_Click(object sender, EventArgs e) { DetermineGameLevel(); } private void Form1_Load(object sender, EventArgs e) { this.StartPosition = FormStartPosition.CenterScreen; this.BackColor = Color.LightSeaGreen; GamePanel.BackColor = Color.LightSeaGreen; //GamePanel.Left = 5; //GamePanel.Top = 5; GameLevelComboBox1.Items.Add("Beginner"); GameLevelComboBox1.Items.Add("Intermediate"); GameLevelComboBox1.Items.Add("Expert"); GameLevelComboBox1.Text = "Beginner"; GameLevelComboBox1.SelectedIndex = 1; DetermineGameLevel(); //SoundPlayer snd = new SoundPlayer(Path.Combine(Application.StartupPath, "Bomb.wav")); //snd.PlayLooping(); } int time1 = 0; private void timer1_Tick(object sender, EventArgs e) { if (time == true) { time1 += 1; timetoolStripStatusLabel3.Text = time1.ToString(); } } private void GameLevelComboBox1_SelectedIndexChanged(object sender, EventArgs e) { int index = GameLevelComboBox1.SelectedIndex; if (index == 0 || index == 1 || index == 2 || index == 3) DetermineGameLevel(); } private void statisticsToolStripMenuItem_Click(object sender, EventArgs e) { if (bestRecord.Count != 0) { if (bestRecord.Count == 1) statisticF.BestTime = $"1: {bestRecord[0]} Second"; else if (bestRecord.Count == 2) statisticF.BestTime = $"1: {bestRecord[0]} Second \n 2: {bestRecord[1]} Second"; else if (bestRecord.Count == 3) statisticF.BestTime = $"1: {bestRecord[0]} Second \n 2: {bestRecord[1]} Second 3: {bestRecord[2]} Second"; else if (bestRecord.Count == 4) statisticF.BestTime = $"1: {bestRecord[0]} Second \n 2: {bestRecord[1]} Second 3: {bestRecord[2]} Second 4: {bestRecord[3]} Second"; } if (mine.GameLevel == MineGameLevel.Beginner) statisticF.Beginnerradiobotton = true; else if (mine.GameLevel == MineGameLevel.Intermediate) statisticF.Intermediateradiobotton = true; else if (mine.GameLevel == MineGameLevel.Expert) statisticF.Expertradiobotton = true; statisticF.NumberofGameplayed = _numberofGames.ToString(); statisticF.NumberofGameWon = _numberofWin.ToString(); statisticF.WinPercentage1 = (_numberofWin / _numberofGames * 100).ToString(); if (statisticF.ShowDialog() == DialogResult.OK) return; } } }
Markdown
UTF-8
7,254
3.9375
4
[]
no_license
# 闭包 函数即是数据。就比方说,函数可以赋值给变量,可以当参数传递给其他函数,还可以从函数里返回等等。这类函数有特殊的名字和结构 **函数式参数(“Funarg”)**: 是指值为函数的参数 例子: ```js function exampleFunc(funArg) { funArg(); } exampleFunc(function () { alert('funArg'); }); ``` **高阶函数(high-order function 简称:HOF)**: 指接受函数式参数的函数。 上述例子中 `exampleFunc` 就是这样的函数 **带函数值的函数**: 以函数作为返回值的函数 **自由变量** 自由变量是指在函数中使用的,但既不是函数参数也不是函数的局部变量的变量 ```js function testFn() { var localVar = 10; function innerFn(innerParam) { alert(innerParam + localVar); } return innerFn; } var someFn = testFn(); someFn(20); // 30 ``` 上述例子中,对于 `innerFn` 函数来说,`localVar` 就属于自由变量 ## 什么是闭包 闭包是代码块和创建该代码块的上下文中数据的结合 让我们来看下面这个例子(伪代码): ```js var x = 20; function foo() { alert(x); // 自由变量"x" == 20 } // 伪代码 foo闭包 fooClosure = { call: foo // 引用到function lexicalEnvironment: {x: 20} // 搜索上下文的上下文 }; ``` 上述例子中,`fooClosure` 部分是伪代码。对应的,在ECMAScript中,`foo` 函数已经有了一个内部属性——创建该函数上下文的作用域链。 `lexical` 通常是省略的。上述例子中是为了强调在闭包创建的同时,上下文的数据就会保存起来。当下次调用该函数的时候,自由变量就可以在保存的(闭包)上下文中找到了,正如上述代码所示,变量 `“z”` 的值总是 `10` ### ECMAScript闭包的实现 首先回顾一下 ECMAScript 的静态(词法)作用域 ```js var z = 10; function foo() { alert(z); } foo(); // 10 – 使用静态和动态作用域的时候 (function () { var z = 20; foo(); // 10 – 使用静态作用域, 20 – 使用动态作用域 })(); // 将foo作为参数的时候是一样的 (function (funArg) { var z = 30; funArg(); // 10 – 静态作用域, 30 – 动态作用域 })(foo); ``` 静态(词法)作用域意味着作用域在函数创建时创建的,且在之后的代码运行过程中不会被改变 回到正题,先来一个例子: ```js var x = 10; function foo() { alert(x); } (function (funArg) { var x = 20; // 变量"x"在(lexical)上下文中静态保存的,在该函数创建的时候就保存了 funArg(); // 10, 而不是20 })(foo); ``` 技术上说,创建该函数的父级上下文的数据是保存在函数的内部属性 `[[Scope]]` 中,回到上文说的什么是闭包:**闭包是代码块和创建该代码块的上下文中数据的结合**,上面的例子上代码是 `foo` ,创建 `foo` 的上下文是全全局上下文, 所以换句话说在 ECMAScript 中,所有的函数都是闭包,因为它们都是在创建的时候就保存了上层上下文的作用域链 ```js var x = 10; function foo() { alert(x); } // foo是闭包 foo: <FunctionObject> = { [[Call]]: <code block of foo>, [[Scope]]: [ global: { x: 10 } ], ... // 其它属性 }; ``` **同一个父上下文中创建的闭包是共用一个 `[[Scope]]` 属性的** 也就是说,某个闭包对其中 `[[Scope]]` 的变量做修改会影响到其他闭包对其变量的读取: ```js var firstClosure; var secondClosure; function foo() { var x = 1; firstClosure = function () { return ++x; }; secondClosure = function () { return --x; }; x = 2; // 影响 AO["x"], 在2个闭包公有的[[Scope]]中 alert(firstClosure()); // 3, 通过第一个闭包的[[Scope]] } foo(); alert(firstClosure()); // 4 alert(secondClosure()); // 3 ``` 这也是如果我们在循环语句里创建函数(内部进行计数)的时候经常得不到预期的结果的原因 ```js var data = []; for (var k = 0; k < 3; k++) { data[k] = function () { alert(k); }; } data[0](); // 3, 而不是0 data[1](); // 3, 而不是1 data[2](); // 3, 而不是2 ``` 上述例子就证明了 —— 同一个上下文中创建的闭包是共用一个 `[[Scope]]` 属性的。因此上层上下文中的变量 `“k”` 是可以很容易就被改变的 ```js activeContext.Scope = [ ... // 其它变量对象 {data: [...], k: 3} // 活动对象 ]; data[0].[[Scope]] === Scope; data[1].[[Scope]] === Scope; data[2].[[Scope]] === Scope; ``` 这样一来,在函数激活的时候,最终使用到的k就已经变成了 `3` 了。如下所示,创建一个闭包就可以解决这个问题了 ```js var data = []; for (var k = 0; k < 3; k++) { data[k] = (function _helper(x) { return function () { alert(x); }; })(k); // 传入"k"值 } // 现在结果是正确的了 data[0](); // 0 data[1](); // 1 data[2](); // 2 ``` 函数 `_helper` 创建出来之后,通过传入参数 `“k”` 激活。其返回值也是个函数,该函数保存在对应的数组元素中。在函数激活时,每次 `_helper` 都会创建一个新的变量对象,其中含有参数 `“x”` , `“x”` 的值就是传递进来的 `“k”` 的值。这样一来,返回的函数的 `[[Scope]]` 就成了如下所示: ```js data[0].[[Scope]] === [ ... // 其它变量对象 父级上下文中的活动对象AO: {data: [...], k: 3}, _helper上下文中的活动对象AO: {x: 0} ]; data[1].[[Scope]] === [ ... // 其它变量对象 父级上下文中的活动对象AO: {data: [...], k: 3}, _helper上下文中的活动对象AO: {x: 1} ]; data[2].[[Scope]] === [ ... // 其它变量对象 父级上下文中的活动对象AO: {data: [...], k: 3}, _helper上下文中的活动对象AO: {x: 2} ]; ``` 我们看到,这时函数的 `[[Scope]]` 属性就有了真正想要的值了,为了达到这样的目的,我们不得不在 `[[Scope]]` 中创建额外的变量对象。要注意的是,在返回的函数中,如果要获取 `“k”` 的值,那么该值还是会是 `3` ```js var data = []; for (var k = 0; k < 3; k++) { (data[k] = function () { alert(arguments.callee.x); }).x = k; // 将k作为函数的一个属性 } // 结果也是对的 data[0](); // 0 data[1](); // 1 data[2](); // 2 ``` 通过其他方式也可以获得正确的 `“k”` 的值,如下所示: ```js var data = []; for (var k = 0; k < 3; k++) { (data[k] = function () { alert(arguments.callee.x); }).x = k; // 将k作为函数的一个属性 } // 结果也是对的 data[0](); // 0 data[1](); // 1 data[2](); // 2 ``` ## 总结 ECMAScript中,闭包指的是: - 从理论角度:所有的函数。因为它们都在创建的时候就将上层上下文的数据保存起来了。哪怕是简单的全局变量也是如此,因为函数中访问全局变量就相当于是在访问自由变量,这个时候使用最外层的作用域。 - 从实践角度:以下函数才算是闭包: - 即使创建它的上下文已经销毁,它仍然存在(比如,内部函数从父函数中返回) - 在代码中引用了自由变量
Python
UTF-8
527
2.515625
3
[]
no_license
# Absolute pressure HSCDANN030PA2A3 (3,3 V) 0-30 psi I2C # With 10k pull-up resistor for SDA and SCL # David THERINCOURT - 2020 from machine import I2C, Pin adr = 40 Pmin = 0 Pmax = 2068 # hPa (30 PSI) Nmin = 1638 # 10% de 2^14 Nmax = 14745 # 90% de 2^14 i2c = I2C(scl=Pin("SCL"), sda=Pin("SDA"), freq=400000) data = bytearray(4) # 32 bit = Status + Data(23:16) + Data(15:8) + Data(7:0) i2c.readfrom_into(adr, data) # Read data N = (data[0] << 8) | data[1] pression = (N-Nmin)*(Pmax-Pmin)/(Nmax-Nmin) + Pmin print(N, pression)
Python
UTF-8
5,596
2.953125
3
[]
no_license
#! /usr/bin/env python # -*- coding: utf-8 -*- import telebot bot = telebot.TeleBot("1485531627:AAEcbWCfQpmUhRyNiImffwKGCHg7xPG48B8") from telebot import types first_recipe = ["Гречка с курицей и морковью. Куриное филе нарежьте небольшими кусочками. Лук измельчите, морковь натрите на мелкой терке. В кастрюлю с толстым дном добавьте растительное масло. Филе, лук и морковь. Перемешайте, посолите (0,5 ч.л. соли), поперчите по вкусу и поджарьте до готовности овощей. Помойте гречневую крупу. Добавьте в кастрюлю к курице и овощам."] second_recipe = ["Гречка с курицей в духовке. Промыть гречку и высыпать в отдельную миску. Вскипятить воду и залить гречку минут на 10 примерно. Туда же добавить соли и приправы. Далее нужно промыть под проточной водой куриное филе, обсушить и на эти 10 минут замариновать в соли, перце и любой любимой приправе. Духовку ставим на 180 градусов и ждем, пока разогреется. Половинку луковицы режем тонкими полукольцами, а чеснок - мелкими кубиками. Берем форму, в нее заливаем растительное масло. Если масло сливочное, то его в последний момент кладем маленькими кусочками сверху всего блюда. Высыпаем в форму лук и чеснок, гречку вместе с водой и перемешиваем, распределяя равномерно ингредиенты. Выкладываем курицу последним слоем. В разогретую духовку ставим нашу форму по центру на 1 час. Минут за 20 до финиша нужно убрать фольгу, чтобы появился вкусный золотистый оттенок."] third_recipe = ["Гречка с курицей в горшочке. Грудку освобождаем от участков жира, кожи и костей, нарезаем не очень крупно. Лук нарезаем максимально мелко, морковку нарезаем покрупнее. В сковороде на огне выше среднего разогреваем растительное масло. Кладем в сковороду кусочки курицы и обжариваем их со всех сторон. Следом отправляем к мясу лук, морковку и чеснок. Обжариваем, помешивая, в течение 7-8 минут. Гречу перебираем, промываем под холодной водой и добавляем в сковороду. Перемешиваем и снимаем посуду с огня. Раскладываем гречу с курицей и овощами по горшочкам. Заливаем в каждый горячую воду так, чтобы она полностью покрывала содержимое. Отправляем горшочки в предварительно разогретую духовку на 40 минут. За 10 минут до конца приготовления кладем в каждый горшочек по чайной ложке сливочного масла."] recipies = [first_recipe, second_recipe, third_recipe] @bot.message_handler(content_types=['text']) def get_text_messages(message): if message.text == "Привет": bot.send_message(message.from_user.id, "Привет! Сейчас мы вместе с тобой приготовим вкусную и полезную еду из продуктов в твоём холодильнике.") keyboard = types.InlineKeyboardMarkup() key_chicken = types.InlineKeyboardButton(text='Курица', callback_data='chicken') keyboard.add(key_chicken) key_buckwheat = types.InlineKeyboardButton(text='Гречка', callback_data='buckwheat') keyboard.add(key_buckwheat) key_carrot = types.InlineKeyboardButton(text='Морковь', callback_data='carrot') keyboard.add(key_carrot) bot.send_message(message.from_user.id, text='Выбери продукты, которые у тебя есть в холодильнике', reply_markup=keyboard) elif message.text == "/help": bot.send_message(message.from_user.id, "Напиши Привет") else: bot.send_message(message.from_user.id, "Давай готовить вместе. Напиши /help.") @bot.callback_query_handler(func=lambda call: True) def callback_worker(call): if call.data == 'chicken': bot.send_message(call.message.chat.id, first_recipe) if call.data == 'buckwheat': bot.send_message(call.message.chat.id, second_recipe) if call.data == 'carrot': bot.send_message(call.message.chat.id, third_recipe) bot.polling(none_stop=True, interval=0)
C++
UTF-8
1,608
3.03125
3
[]
no_license
/* Project name : Counter_using_Seven_Segment_Display_for_Robomart_Arduino_Board // Complied by : www.robomart.com // Designed for : ROBOSAPIENS TECHNOLOGIES PVT. LTD // http://www.robosapiensindia.com /***********************Counter using Arduino Library***********************/ /* Counts the Number Starting from 00 to 99 */ // Seven Segment Data Pins (DP, A - G) are connected to Digital Pins (0 - 7) and // Enable pins are connected to Digital pins 8 & 9 respectively. // Include the SevenSegemnt.h file into the project folder or to the directory // ARDUINO\arduino-1.0.5-windows\arduino-1.0.5\hardware\arduino\variants\standard #include<SevenSegment.h> // the setup routine runs once when you press reset: int num_1,num; // Declare Variable void setup() { // initialize the digital pins as an output using digit_begin function digit_begin(); } void loop() { // the loop routine runs over and over again forever: for(int i=0;i<=99;i++) { num=i; num_1=num/10; digitalWrite(en1, HIGH); // stores the status of en1(HIGH is the voltage level) digitalWrite(en1, LOW); // stores the status of en1(LOW is the voltage level) print_digit(num_1); delay(10); // wait for a 10ms num=(num-(num_1*10)); num_1=num; digitalWrite(en0, HIGH); // stores the status of en0(HIGH is the voltage level) digitalWrite(en0, LOW); // stores the status of en0(LOW is the voltage level) print_digit(num_1); delay(10); // wait for a 10ms } } /*************end of the program*************/
Python
UTF-8
540
2.515625
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
import tensorflow as tf class Decoder(object): def __init__(self, cfg): self.cfg = cfg def __call__(self, input): with tf.varible_scope("decoder"): out = input return(out) class Encoder(object): def __init__(self, cfg): self.cfg = cfg def __call__(self, input): """ Args: input: image Tensors. Returns: out: output. """ with tf.variable_scope("encoder"): out = input return(out)
Python
UTF-8
371
3.890625
4
[]
no_license
x = "There are %d types of people." % 10 binary = "binary" do_not = "don't" y = "Those who know %s and those who %s." % (binary, do_not) print x print y print "I said %r." % y hilarious = False joke_evalutation = "Isn't that joke so funny!?! %r" print joke_evalutation % hilarious w = "This is the left side of..." e = "a string with a right side." print w + e
Python
UTF-8
1,958
2.890625
3
[]
no_license
from Node import Node import time import collections class Network: def __init__(self,l,slot_time,max_time,nodeCount,distanceBetweenNodes): self.slot_time=slot_time self.cur_time=0 self.tt=80 self.max_time=max_time self.collCount=0 self.bandwidth = 100 #Mbps self.vel=2*(10**8) self.nodeCount=nodeCount self.distanceBetweenNodes=distanceBetweenNodes self.distance=collections.defaultdict(int) self.node=[-1] self.lambd=l for i in range(1,self.nodeCount+1): self.node.append(Node(i,float(self.lambd)/self.slot_time)) self.distance[i]=(i-1)*self.distanceBetweenNodes def run(self): for i in range(1,self.nodeCount+1): self.node[i].operation(self) self.coll_detect() print(self.cur_time) for i in range(1,self.nodeCount+1): print("Status of Node {}: {} to {}".format(i,self.node[i].status, self.node[i].curReceiver)) print("-------------------------------------") self.cur_time = self.cur_time + 1 def coll_detect(self): collIndex=[] for i in range(1,self.nodeCount+1): if self.node[i].status=="Transmitting": collIndex.append(i) if len(collIndex)>=2: self.collCount=self.collCount+1 for i in collIndex: self.node[i].stopTransmit("Collision") def print_stat(self): for i in range(1,nodeCount+1): print("Total packets sent from Node {}: {}".format(i,self.node[i].packetCount-1)) print("Average end to end throughput from Node {}: {}".format(i,self.node[i].throughput(self))) print("Number of collisions: ", self.collCount) print("Simulation end time", self.cur_time) if __name__ == "__main__": # slot_time=int(input("Enter the slot time")) slot_time = 50 l = 0.5 distanceBetweenNodes=2000 max_time =int(input("Enter the max time: ")) nodeCount=int(input("Enter the number of nodes: ")) part2=Network(l,slot_time,max_time,nodeCount,distanceBetweenNodes) for _ in range(max_time+1): # while True: part2.run() time.sleep(1) part2.print_stat()
Java
UTF-8
5,054
2.203125
2
[ "Apache-2.0" ]
permissive
package com.ider.mouse.util; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.PixelFormat; import android.graphics.drawable.Drawable; import android.util.Log; import com.ider.mouse.MyApplication; import com.ider.mouse.db.App; import com.ider.mouse.db.MyData; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import static android.R.attr.versionCode; import static android.R.attr.versionName; import static android.content.ContentValues.TAG; public class ApplicationUtil { private static Context context = MyApplication.getContext(); private static PackageManager packageManager = context.getPackageManager(); public static List<App> queryApplication() { List<App> enties = new ArrayList<>(); Intent intent = new Intent(); intent.setAction(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(intent, 0); File dir = new File(MyData.appIconPath); dir.mkdirs(); for (int i = 0; i<resolveInfos.size();i++) { ResolveInfo resolveInfo = resolveInfos.get(i); String packageName = resolveInfo.activityInfo.applicationInfo.packageName; String labelName = resolveInfo.activityInfo.applicationInfo.loadLabel(packageManager).toString(); Drawable drawable = resolveInfo.activityInfo.applicationInfo.loadIcon(packageManager); PackageInfo packageInfo; try { packageInfo = MyApplication.getContext().getPackageManager().getPackageInfo(packageName,0); }catch (PackageManager.NameNotFoundException e){ e.printStackTrace(); packageInfo = null; } String type = "1"; int versionCode; String versionName; if (packageInfo!=null) { if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) { type = "1"; } else { type = "0"; } versionCode = packageInfo.versionCode; versionName = packageInfo.versionName; // Log.i(TAG, "versionCode="+versionCode+"versionName="+versionName); }else { versionCode = 0; versionName = "0"; // Log.i(TAG, "versionCode==null"); } // Log.i(TAG, "labelName ="+labelName+"type ="+type); String picName = packageName + ".jpg"; saveBitmap(drawableToBitmap(drawable),picName); enties.add(new App(packageName,labelName,type,versionCode,versionName)); } HashSet h = new HashSet(enties);//删除重复元素 enties.clear(); enties.addAll(h); return enties; } public static String getRequestedPermission(String packageName){ String[] requestedPermissions = null; String info = ""; try { requestedPermissions = packageManager.getPackageInfo(packageName,PackageManager.GET_PERMISSIONS).requestedPermissions; }catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } if (requestedPermissions!=null){ for (String permission:requestedPermissions){ info = info+permission+"\n"; } } return info; } public static void saveBitmap(Bitmap bm,String picName) { File f = new File("/sdcard/Pictures/icons/", picName); if (f.exists()) { f.delete(); } try { FileOutputStream out = new FileOutputStream(f); bm.compress(Bitmap.CompressFormat.PNG, 50, out); out.flush(); out.close(); // Log.i(TAG, "已经保存"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Bitmap drawableToBitmap(Drawable drawable) { Bitmap bitmap = Bitmap.createBitmap( drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); //canvas.setBitmap(bitmap); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.draw(canvas); return bitmap; } }
C
UTF-8
23,849
2.953125
3
[]
no_license
#include <stdio.h> #include<stdlib.h> #include <malLoc.h> #include<string.h> #include "ELTPRIM.H" #include "LSTPRIM.H" #include "TABPRIM.H" ELEMENT_TAB tabelementcreer() { ELEMENT_TAB L; L=(ELEMENT_TAB)malloc(sizeof(TAB)); int i,j; for (i=1;i<=7;i++) for(j=1;j<=18;j++) L->T[i][j]=listecreer(); return L ;} void tabelementdetruire(ELEMENT_TAB e) {free (e);} void tabelementlire(ELEMENT_TAB *e) {int i; LISTE L1=listecreer(); ELEMENT elt1=elementcreer(); elt1->num_at=1;strcpy(elt1->symbole,"H");elt1->masse_at=1.0079;strcpy(elt1->etat,"gaz");inserer(L1,elt1,1);(*e)->T[1][1]=L1; for (i=2;i<=17;i++) { LISTE L =listecreer(); estvide(L); (*e)->T[1][i]=L; listeafficher(L); } LISTE L2=listecreer(); ELEMENT elt2=elementcreer(); elt2->num_at=2; strcpy(elt2->symbole,"He"); elt2->masse_at=4.0026; strcpy(elt2->etat,"gaz"); inserer(L2,elt2,1); (*e)->T[1][18]=L2; LISTE L3=listecreer(); ELEMENT elt3=elementcreer(); elt3->num_at=3; strcpy(elt3->symbole,"Li"); elt3->masse_at=6.941; strcpy(elt3->etat,"solide"); inserer(L3,elt3,1); (*e)->T[2][1]=L3; LISTE L4=listecreer(); ELEMENT elt4=elementcreer(); elt4->num_at=4; strcpy(elt4->symbole,"Be"); elt4->masse_at=9.0122; strcpy(elt4->etat,"solide"); inserer(L4,elt4,1); (*e)->T[2][2]=L4; for (i=3;i<=12;i++) { LISTE L =listecreer(); estvide(L); (*e)->T[2][i]=L; listeafficher(L); } LISTE L5=listecreer(); ELEMENT elt5=elementcreer(); elt5->num_at=5; strcpy(elt5->symbole,"B"); elt5->masse_at=10.811; strcpy(elt5->etat,"solide"); inserer(L5,elt5,1); (*e)->T[2][13]=L5; LISTE L6=listecreer(); ELEMENT elt6=elementcreer(); elt6->num_at=6; strcpy(elt6->symbole,"C"); elt6->masse_at=12.011; strcpy(elt6->etat,"solide"); inserer(L6,elt6,1); (*e)->T[2][14]=L6; LISTE L7=listecreer(); ELEMENT elt7=elementcreer(); elt7->num_at=7; strcpy(elt7->symbole,"N"); elt7->masse_at=14.007; strcpy(elt7->etat,"gaz"); inserer(L7,elt7,1); (*e)->T[2][15]=L7; LISTE L8=listecreer(); ELEMENT elt8=elementcreer(); elt8->num_at=8; strcpy(elt8->symbole,"O"); elt8->masse_at=15.999; strcpy(elt8->etat,"gaz"); inserer(L8,elt8,1); (*e)->T[2][16]=L8; LISTE L9=listecreer(); ELEMENT elt9=elementcreer(); elt9->num_at=9; strcpy(elt9->symbole,"F"); elt9->masse_at=18.998; strcpy(elt9->etat,"gaz"); inserer(L9,elt9,1); (*e)->T[2][17]=L9; LISTE L10=listecreer(); ELEMENT elt10=elementcreer(); elt10->num_at=10; strcpy(elt10->symbole,"Ne"); elt10->masse_at=20.180; strcpy(elt10->etat,"gaz"); inserer(L10,elt10,1); (*e)->T[2][18]=L10; LISTE L11=listecreer(); ELEMENT elt11=elementcreer(); elt11->num_at=11; strcpy(elt11->symbole,"Na"); elt11->masse_at=22.990; strcpy(elt11->etat,"solide"); inserer(L11,elt11,1); (*e)->T[3][1]=L11; LISTE L12=listecreer(); ELEMENT elt12=elementcreer(); elt12->num_at=12; strcpy(elt12->symbole,"Mg"); elt12->masse_at=24.305; strcpy(elt12->etat,"solide"); inserer(L12,elt12,1); (*e)->T[3][2]=L12; for (i=3;i<=12;i++) { LISTE L =listecreer(); estvide(L); (*e)->T[3][i]=L; } LISTE L13=listecreer(); ELEMENT elt13=elementcreer(); elt13->num_at=13; strcpy(elt13->symbole,"Al"); elt13->masse_at=26.982; strcpy(elt13->etat,"solide"); inserer(L13,elt13,1); (*e)->T[3][13]=L13; LISTE L14=listecreer(); ELEMENT elt14=elementcreer(); elt14->num_at=14; strcpy(elt14->symbole,"Si"); elt14->masse_at=28.086; strcpy(elt14->etat,"solide"); inserer(L14,elt14,1); (*e)->T[3][14]=L14; LISTE L15=listecreer(); ELEMENT elt15=elementcreer(); elt15->num_at=15; strcpy(elt15->symbole,"P"); elt15->masse_at=30.974; strcpy(elt15->etat,"solide"); inserer(L15,elt15,1); (*e)->T[3][15]=L15; LISTE L16=listecreer(); ELEMENT elt16=elementcreer(); elt16->num_at=16; strcpy(elt16->symbole,"S"); elt16->masse_at=32.065; strcpy(elt16->etat,"solide"); inserer(L16,elt16,1); (*e)->T[3][16]=L16; LISTE L17=listecreer(); ELEMENT elt17=elementcreer(); elt17->num_at=17; strcpy(elt17->symbole,"Cl"); elt17->masse_at=35.453; strcpy(elt17->etat,"gaz"); inserer(L17,elt17,1); (*e)->T[3][17]=L17; LISTE L18=listecreer(); ELEMENT elt18=elementcreer(); elt18->num_at=18; strcpy(elt18->symbole,"Ar"); elt18->masse_at=39.948; strcpy(elt18->etat,"gaz"); inserer(L18,elt18,1); (*e)->T[3][18]=L18; LISTE L19=listecreer(); ELEMENT elt19=elementcreer(); elt19->num_at=19; strcpy(elt19->symbole,"K"); elt19->masse_at=39.098; strcpy(elt19->etat,"solide"); inserer(L19,elt19,1); (*e)->T[4][1]=L19; LISTE L20=listecreer(); ELEMENT elt20=elementcreer(); elt20->num_at=20; strcpy(elt20->symbole,"Ca"); elt20->masse_at=40.078; strcpy(elt20->etat,"solide"); inserer(L20,elt20,1); (*e)->T[4][2]=L20; LISTE L21=listecreer(); ELEMENT elt21=elementcreer(); elt21->num_at=21; strcpy(elt21->symbole,"Sc"); elt21->masse_at=44.958; strcpy(elt21->etat,"solide"); inserer(L21,elt21,1); (*e)->T[4][3]=L21; LISTE L22=listecreer(); ELEMENT elt22=elementcreer(); elt22->num_at=22; strcpy(elt22->symbole,"Ti"); elt22->masse_at=47.887; strcpy(elt22->etat,"solide"); inserer(L22,elt22,1); (*e)->T[4][4]=L22; LISTE L23=listecreer(); ELEMENT elt23=elementcreer(); elt23->num_at=23; strcpy(elt23->symbole,"V"); elt23->masse_at=50.942; strcpy(elt23->etat,"solide"); inserer(L23,elt23,1); (*e)->T[4][5]=L23; LISTE L24=listecreer(); ELEMENT elt24=elementcreer(); elt24->num_at=24; strcpy(elt24->symbole,"Cr"); elt24->masse_at=51.996; strcpy(elt24->etat,"solide"); inserer(L24,elt24,1); (*e)->T[4][6]=L24; LISTE L25=listecreer(); ELEMENT elt25=elementcreer(); elt25->num_at=25; strcpy(elt25->symbole,"Mn"); elt25->masse_at=54.938; strcpy(elt25->etat,"solide"); inserer(L25,elt25,1); (*e)->T[4][7]=L25; LISTE L26=listecreer(); ELEMENT elt26=elementcreer(); elt26->num_at=26; strcpy(elt26->symbole,"Fe"); elt26->masse_at=55.845; strcpy(elt26->etat,"solide"); inserer(L26,elt26,1); (*e)->T[4][8]=L26; LISTE L27=listecreer(); ELEMENT elt27=elementcreer(); elt27->num_at=27; strcpy(elt27->symbole,"Co"); elt27->masse_at=58.933; strcpy(elt27->etat,"solide"); inserer(L27,elt27,1); (*e)->T[4][9]=L27; LISTE L28=listecreer(); ELEMENT elt28=elementcreer(); elt28->num_at=28; strcpy(elt28->symbole,"Ni"); elt28->masse_at=58.893; strcpy(elt28->etat,"solide"); inserer(L28,elt28,1); (*e)->T[4][10]=L28; LISTE L29=listecreer(); ELEMENT elt29=elementcreer(); elt29->num_at=29; strcpy(elt29->symbole,"Cu"); elt29->masse_at=63.546; strcpy(elt29->etat,"solide"); inserer(L29,elt29,1); (*e)->T[4][11]=L29; LISTE L30=listecreer(); ELEMENT elt30=elementcreer(); elt30->num_at=30; strcpy(elt30->symbole,"Zn"); elt30->masse_at=65.38; strcpy(elt30->etat,"solide"); inserer(L30,elt30,1); (*e)->T[4][12]=L30; LISTE L31=listecreer(); ELEMENT elt31=elementcreer(); elt31->num_at=31; strcpy(elt30->symbole,"Ga"); elt31->masse_at=69.723; strcpy(elt31->etat,"solide"); inserer(L31,elt31,1); (*e)->T[4][13]=L31; LISTE L32=listecreer(); ELEMENT elt32=elementcreer(); elt32->num_at=32; strcpy(elt32->symbole,"Ge"); elt32->masse_at=72.64; strcpy(elt32->etat,"solide"); inserer(L32,elt32,1); (*e)->T[4][14]=L32; LISTE L33=listecreer(); ELEMENT elt33=elementcreer(); elt33->num_at=33; strcpy(elt33->symbole,"As"); elt33->masse_at=74.922; strcpy(elt33->etat,"solide"); inserer(L33,elt33,1); (*e)->T[4][15]=L33; LISTE L34=listecreer(); ELEMENT elt34=elementcreer(); elt34->num_at=34; strcpy(elt34->symbole,"Se"); elt34->masse_at=78.96; strcpy(elt34->etat,"solide"); inserer(L34,elt34,1); (*e)->T[4][16]=L34; LISTE L35=listecreer(); ELEMENT elt35=elementcreer(); elt35->num_at=35; strcpy(elt35->symbole,"Br"); elt35->masse_at=79.904; strcpy(elt35->etat,"liquide"); inserer(L35,elt35,1); (*e)->T[4][17]=L35; LISTE L36=listecreer(); ELEMENT elt36=elementcreer(); elt36->num_at=36; strcpy(elt36->symbole,"Kr"); elt36->masse_at=83.798; strcpy(elt36->etat,"gaz"); inserer(L36,elt36,1); (*e)->T[4][18]=L36; LISTE L37=listecreer(); ELEMENT elt37=elementcreer(); elt37->num_at=37; strcpy(elt37->symbole,"Rb"); elt37->masse_at=85.468; strcpy(elt37->etat,"solide"); inserer(L37,elt37,1); (*e)->T[5][1]=L37; LISTE L38=listecreer(); ELEMENT elt38=elementcreer(); elt38->num_at=38; strcpy(elt38->symbole,"Sr"); elt38->masse_at=87.82; strcpy(elt38->etat,"solide"); inserer(L38,elt38,1); (*e)->T[5][2]=L38; LISTE L39=listecreer(); ELEMENT elt39=elementcreer(); elt39->num_at=39; strcpy(elt39->symbole,"Y"); elt39->masse_at=88.906; strcpy(elt39->etat,"solide"); inserer(L39,elt39,1); (*e)->T[5][3]=L39; LISTE L40=listecreer(); ELEMENT elt40=elementcreer(); elt40->num_at=40;strcpy(elt40->symbole,"Zr");elt40->masse_at=91.224;strcpy(elt40->etat,"solide");inserer(L40,elt40,1);(*e)->T[5][4]=L40; LISTE L41=listecreer(); ELEMENT elt41=elementcreer(); elt41->num_at=41;strcpy(elt41->symbole,"Nb");elt41->masse_at=92.906;strcpy(elt41->etat,"solide");inserer(L41,elt41,1);(*e)->T[5][5]=L41; LISTE L42=listecreer(); ELEMENT elt42=elementcreer(); elt42->num_at=42;strcpy(elt42->symbole,"Mo");elt42->masse_at=95.96;strcpy(elt42->etat,"solide");inserer(L42,elt42,1);(*e)->T[5][6]=L42; LISTE L43=listecreer(); ELEMENT elt43=elementcreer(); elt43->num_at=43;strcpy(elt43->symbole,"Tc");elt43->masse_at=98;strcpy(elt43->etat,"sythetique");inserer(L43,elt43,1);(*e)->T[5][7]=L43; LISTE L44=listecreer(); ELEMENT elt44=elementcreer(); elt44->num_at=44;strcpy(elt44->symbole,"Ru");elt44->masse_at=101.107;strcpy(elt44->etat,"solide");inserer(L44,elt44,1);(*e)->T[5][8]=L44; LISTE L45=listecreer(); ELEMENT elt45=elementcreer(); elt45->num_at=45;strcpy(elt45->symbole,"Rh");elt45->masse_at=102.91;strcpy(elt45->etat,"solide");inserer(L45,elt45,1);(*e)->T[5][9]=L45; LISTE L46=listecreer(); ELEMENT elt46=elementcreer(); elt46->num_at=46;strcpy(elt46->symbole,"Pd");elt46->masse_at=106.42;strcpy(elt46->etat,"solide");inserer(L46,elt46,1);(*e)->T[5][10]=L46; LISTE L47=listecreer(); ELEMENT elt47=elementcreer(); elt47->num_at=47;strcpy(elt47->symbole,"Ag");elt47->masse_at=107.87;strcpy(elt47->etat,"solide");inserer(L47,elt47,1);(*e)->T[5][11]=L47; LISTE L48=listecreer(); ELEMENT elt48=elementcreer(); elt48->num_at=48;strcpy(elt48->symbole,"Cd");elt48->masse_at=112.41;strcpy(elt48->etat,"solide");inserer(L48,elt48,1);(*e)->T[5][12]=L48; LISTE L49=listecreer(); ELEMENT elt49=elementcreer(); elt49->num_at=49;strcpy(elt49->symbole,"In");elt49->masse_at=114.82;strcpy(elt49->etat,"solide");inserer(L49,elt49,1);(*e)->T[5][13]=L49; LISTE L50=listecreer(); ELEMENT elt50=elementcreer(); elt50->num_at=50;strcpy(elt50->symbole,"Sn");elt50->masse_at=118.71;strcpy(elt50->etat,"solide");inserer(L50,elt50,1);(*e)->T[5][14]=L50; LISTE L51=listecreer(); ELEMENT elt51=elementcreer(); elt51->num_at=51;strcpy(elt51->symbole,"Sb");elt51->masse_at=121.76;strcpy(elt51->etat,"solide");inserer(L51,elt51,1);(*e)->T[5][15]=L51; LISTE L52=listecreer(); ELEMENT elt52=elementcreer(); elt52->num_at=52;strcpy(elt52->symbole,"Te");elt52->masse_at=127.60;strcpy(elt52->etat,"solide");inserer(L52,elt52,1);(*e)->T[5][16]=L52; LISTE L53=listecreer(); ELEMENT elt53=elementcreer(); elt53->num_at=53;strcpy(elt53->symbole,"I");elt53->masse_at=126.90;strcpy(elt53->etat,"solide");inserer(L53,elt53,1);(*e)->T[5][17]=L53; LISTE L54=listecreer(); ELEMENT elt54=elementcreer(); elt54->num_at=54;strcpy(elt54->symbole,"Xe");elt54->masse_at=131.29;strcpy(elt54->etat,"gaz");inserer(L54,elt54,1);(*e)->T[5][18]=L54; LISTE L55=listecreer(); ELEMENT elt55=elementcreer(); elt55->num_at=55;strcpy(elt55->symbole,"Cs");elt55->masse_at=132.91;strcpy(elt55->etat,"solide");inserer(L55,elt55,1);(*e)->T[6][1]=L55; LISTE L56=listecreer(); ELEMENT elt56=elementcreer(); elt56->num_at=56;strcpy(elt56->symbole,"Ba");elt56->masse_at=137.33;strcpy(elt56->etat,"solide");inserer(L56,elt56,1);(*e)->T[6][2]=L56; /**liste 57**/ LISTE L57=listecreer(); ELEMENT elt57=elementcreer(); elt57->num_at=57;strcpy(elt57->symbole,"La");elt57->masse_at=138.91;strcpy(elt57->etat,"solide");inserer(L57,elt57,1); ELEMENT elt58=elementcreer(); elt58->num_at=58;strcpy(elt58->symbole,"Ce");elt58->masse_at=140.12;strcpy(elt58->etat,"solide");inserer(L57,elt58,2); ELEMENT elt59=elementcreer(); elt59->num_at=59;strcpy(elt59->symbole,"Pr");elt59->masse_at=140.91;strcpy(elt59->etat,"solide");inserer(L57,elt59,3); ELEMENT elt60=elementcreer(); elt60->num_at=60;strcpy(elt60->symbole,"Nd");elt60->masse_at=144.24;strcpy(elt60->etat,"solide");inserer(L57,elt60,4); ELEMENT elt61=elementcreer(); elt61->num_at=61;strcpy(elt61->symbole,"Pm");elt61->masse_at=145;strcpy(elt61->etat,"synthetique");inserer(L57,elt61,5); ELEMENT elt62=elementcreer(); elt62->num_at=62;strcpy(elt62->symbole,"Sm");elt62->masse_at=150.38;strcpy(elt62->etat,"solide");inserer(L57,elt62,6); ELEMENT elt63=elementcreer(); elt63->num_at=63;strcpy(elt63->symbole,"Eu");elt63->masse_at=151.95;strcpy(elt63->etat,"solide");inserer(L57,elt63,7); ELEMENT elt64=elementcreer(); elt64->num_at=64;strcpy(elt64->symbole,"Gd");elt64->masse_at=157.25;strcpy(elt64->etat,"solide");inserer(L57,elt64,8); ELEMENT elt65=elementcreer(); elt65->num_at=65;strcpy(elt65->symbole,"Td");elt65->masse_at=158.93;strcpy(elt65->etat,"solide");inserer(L57,elt65,9); ELEMENT elt66=elementcreer(); elt66->num_at=66;strcpy(elt66->symbole,"Dy");elt66->masse_at=162.50;strcpy(elt66->etat,"solide");inserer(L57,elt66,10); ELEMENT elt67=elementcreer(); elt67->num_at=67;strcpy(elt67->symbole,"Ho");elt67->masse_at=164.93 ;strcpy(elt67->etat,"solide");inserer(L57,elt67,11); ELEMENT elt68=elementcreer(); elt68->num_at=68;strcpy(elt68->symbole,"Er");elt68->masse_at=167.28;strcpy(elt68->etat,"solide");inserer(L57,elt68,12); ELEMENT elt69=elementcreer(); elt69->num_at=69;strcpy(elt69->symbole,"Tm");elt69->masse_at=168.93;strcpy(elt69->etat,"solide");inserer(L57,elt69,13); ELEMENT elt70=elementcreer(); elt70->num_at=70;strcpy(elt70->symbole,"Yb");elt70->masse_at=173.05;strcpy(elt70->etat,"solide");inserer(L57,elt70,14); ELEMENT elt71=elementcreer(); elt71->num_at=71;strcpy(elt71->symbole,"Lu");elt71->masse_at=174.97;strcpy(elt71->etat,"solide");inserer(L57,elt71,15);(*e)->T[6][3]=L57; LISTE L72=listecreer(); ELEMENT elt72=elementcreer(); elt72->num_at=72;strcpy(elt72->symbole,"Hf");elt72->masse_at=178.49;strcpy(elt72->etat,"solide");inserer(L72,elt72,1);(*e)->T[6][4]=L72; LISTE L73=listecreer(); ELEMENT elt73=elementcreer(); elt73->num_at=73;strcpy(elt73->symbole,"Ta");elt73->masse_at=180.95;strcpy(elt73->etat,"solide");inserer(L73,elt73,1);(*e)->T[6][5]=L73; LISTE L74=listecreer(); ELEMENT elt74=elementcreer(); elt74->num_at=74;strcpy(elt74->symbole,"W");elt74->masse_at=183.84;strcpy(elt74->etat,"solide");inserer(L74,elt74,1);(*e)->T[6][6]=L74; LISTE L75=listecreer(); ELEMENT elt75=elementcreer(); elt75->num_at=75;strcpy(elt75->symbole,"Re");elt75->masse_at=186.21;strcpy(elt75->etat,"solide");inserer(L75,elt75,1);(*e)->T[6][7]=L75; LISTE L76=listecreer(); ELEMENT elt76=elementcreer(); elt76->num_at=76;strcpy(elt76->symbole,"Os");elt76->masse_at=190.23;strcpy(elt76->etat,"solide");inserer(L76,elt76,1);(*e)->T[6][8]=L76; LISTE L77=listecreer(); ELEMENT elt77=elementcreer(); elt77->num_at=77;strcpy(elt77->symbole,"Ir");elt77->masse_at=192.22;strcpy(elt77->etat,"solide");inserer(L77,elt77,1);(*e)->T[6][9]=L77; LISTE L78=listecreer(); ELEMENT elt78=elementcreer(); elt78->num_at=78;strcpy(elt78->symbole,"Pt");elt78->masse_at=195.08;strcpy(elt78->etat,"solide");inserer(L78,elt78,1);(*e)->T[6][10]=L78; LISTE L79=listecreer(); ELEMENT elt79=elementcreer(); elt79->num_at=79;strcpy(elt79->symbole,"Au");elt79->masse_at=196.97;strcpy(elt79->etat,"solide");inserer(L79,elt79,1);(*e)->T[6][11]=L79; LISTE L80=listecreer(); ELEMENT elt80=elementcreer(); elt80->num_at=80;strcpy(elt80->symbole,"Hg");elt80->masse_at=200.59;strcpy(elt80->etat,"liquide");inserer(L80,elt80,1);(*e)->T[6][12]=L80; LISTE L81=listecreer(); ELEMENT elt81=elementcreer(); elt81->num_at=81;strcpy(elt81->symbole,"Tl");elt81->masse_at=204.38;strcpy(elt81->etat,"solide");inserer(L81,elt81,1);(*e)->T[6][13]=L81; LISTE L82=listecreer(); ELEMENT elt82=elementcreer(); elt82->num_at=82;strcpy(elt82->symbole,"Pb");elt82->masse_at=207.2;strcpy(elt82->etat,"solide");inserer(L82,elt82,1);(*e)->T[6][14]=L82; LISTE L83=listecreer(); ELEMENT elt83=elementcreer(); elt83->num_at=83;strcpy(elt83->symbole,"Bi");elt83->masse_at=208.96;strcpy(elt83->etat,"solide");inserer(L83,elt83,1);(*e)->T[6][15]=L83; LISTE L84=listecreer(); ELEMENT elt84=elementcreer(); elt84->num_at=84;strcpy(elt84->symbole,"Po");elt84->masse_at=209;strcpy(elt84->etat,"solide");inserer(L84,elt84,1);(*e)->T[6][16]=L84; LISTE L85=listecreer(); ELEMENT elt85=elementcreer(); elt85->num_at=85;strcpy(elt85->symbole,"At");elt85->masse_at=210;strcpy(elt85->etat,"solide");inserer(L85,elt85,1);(*e)->T[6][17]=L85; LISTE L86=listecreer(); ELEMENT elt86=elementcreer(); elt86->num_at=86;strcpy(elt86->symbole,"Rn");elt86->masse_at=222;strcpy(elt86->etat,"gaz");inserer(L86,elt86,1);(*e)->T[6][18]=L86; LISTE L87=listecreer(); ELEMENT elt87=elementcreer(); elt87->num_at=87;strcpy(elt87->symbole,"Fr");elt87->masse_at=223;strcpy(elt87->etat,"solide");inserer(L87,elt87,1);(*e)->T[7][1]=L87; LISTE L88=listecreer(); ELEMENT elt88=elementcreer(); elt88->num_at=88;strcpy(elt88->symbole,"Ra");elt88->masse_at=226;strcpy(elt88->etat,"solide");inserer(L88,elt88,1);(*e)->T[7][2]=L88; /**liste 89**/ LISTE L89=listecreer(); ELEMENT elt89=elementcreer(); elt89->num_at=89;strcpy(elt89->symbole,"Ac");elt89->masse_at=227;strcpy(elt89->etat,"solide");inserer(L89,elt89,1); ELEMENT elt90=elementcreer(); elt90->num_at=90;strcpy(elt90->symbole,"Th");elt90->masse_at=232.04;strcpy(elt90->etat,"solide");inserer(L89,elt90,2); ELEMENT elt91=elementcreer(); elt91->num_at=91;strcpy(elt91->symbole,"Pa");elt91->masse_at=231.04;strcpy(elt91->etat,"solide");inserer(L89,elt91,3); ELEMENT elt92=elementcreer(); elt92->num_at=92;strcpy(elt92->symbole,"U");elt92->masse_at=238.03;strcpy(elt92->etat,"solide");inserer(L89,elt92,4); ELEMENT elt93=elementcreer(); elt93->num_at=93;strcpy(elt93->symbole,"Np");elt93->masse_at=237;strcpy(elt93->etat,"synthetique");inserer(L89,elt93,5); ELEMENT elt94=elementcreer(); elt94->num_at=94;strcpy(elt94->symbole,"Pu");elt94->masse_at=244;strcpy(elt94->etat,"synthetique");inserer(L89,elt94,6); ELEMENT elt95=elementcreer(); elt95->num_at=95;strcpy(elt95->symbole,"Am");elt95->masse_at=243;strcpy(elt95->etat,"synthetique");inserer(L89,elt95,7); ELEMENT elt96=elementcreer(); elt96->num_at=96;strcpy(elt96->symbole,"Cm");elt96->masse_at=247;strcpy(elt96->etat,"synthetique");inserer(L89,elt96,8); ELEMENT elt97=elementcreer(); elt97->num_at=97;strcpy(elt97->symbole,"Bk");elt97->masse_at=247;strcpy(elt97->etat,"synthetique");inserer(L89,elt97,9); ELEMENT elt98=elementcreer(); elt98->num_at=98;strcpy(elt98->symbole,"Cf");elt98->masse_at=251;strcpy(elt98->etat,"synthetique");inserer(L89,elt98,10); ELEMENT elt99=elementcreer(); elt99->num_at=99;strcpy(elt99->symbole,"Es");elt99->masse_at=252;strcpy(elt99->etat,"synthetique");inserer(L89,elt99,11); ELEMENT elt100=elementcreer(); elt100->num_at=100;strcpy(elt100->symbole,"Fm");elt100->masse_at=257;strcpy(elt100->etat,"synthetique");inserer(L89,elt100,12); ELEMENT elt101=elementcreer(); elt101->num_at=101;strcpy(elt101->symbole,"Md");elt101->masse_at=258;strcpy(elt101->etat,"synthetique");inserer(L89,elt101,13); ELEMENT elt102=elementcreer(); elt102->num_at=102;strcpy(elt102->symbole,"No");elt102->masse_at=259;strcpy(elt102->etat,"synthetique");inserer(L89,elt102,14); ELEMENT elt103=elementcreer(); elt103->num_at=103;strcpy(elt103->symbole,"Lr");elt103->masse_at=262;strcpy(elt103->etat,"synthetique");inserer(L89,elt103,15);(*e)->T[7][3]=L89; LISTE L104=listecreer(); ELEMENT elt104=elementcreer(); elt104->num_at=104;strcpy(elt104->symbole,"Rf");elt104->masse_at=267;strcpy(elt104->etat,"synthetique");inserer(L104,elt104,1);(*e)->T[7][4]=L104; LISTE L105=listecreer(); ELEMENT elt105=elementcreer(); elt105->num_at=105;strcpy(elt105->symbole,"Db");elt105->masse_at=268;strcpy(elt105->etat,"synthetique");inserer(L105,elt105,1);(*e)->T[7][5]=L105; LISTE L106=listecreer(); ELEMENT elt106=elementcreer(); elt106->num_at=106;strcpy(elt106->symbole,"Sg");elt106->masse_at=271;strcpy(elt106->etat,"synthetique");inserer(L106,elt106,1);(*e)->T[7][6]=L106; LISTE L107=listecreer(); ELEMENT elt107=elementcreer(); elt107->num_at=107;strcpy(elt107->symbole,"Bh");elt107->masse_at=272;strcpy(elt107->etat,"synthetique");inserer(L107,elt107,1);(*e)->T[7][7]=L107; LISTE L108=listecreer(); ELEMENT elt108=elementcreer(); elt108->num_at=108;strcpy(elt108->symbole,"Hs");elt108->masse_at=277;strcpy(elt108->etat,"synthetique");inserer(L108,elt108,1);(*e)->T[7][8]=L108; LISTE L109=listecreer(); ELEMENT elt109=elementcreer(); elt109->num_at=109;strcpy(elt109->symbole,"Mt");elt109->masse_at=109;strcpy(elt109->etat,"synthetique");inserer(L109,elt109,1);(*e)->T[7][9]=L109; LISTE L110=listecreer(); ELEMENT elt110=elementcreer(); elt110->num_at=110;strcpy(elt110->symbole,"Ds");elt110->masse_at=281;strcpy(elt110->etat,"synthetique");inserer(L110,elt110,1);(*e)->T[7][10]=L110; LISTE L111=listecreer(); ELEMENT elt111=elementcreer(); elt111->num_at=111;strcpy(elt111->symbole,"Rg");elt111->masse_at=280;strcpy(elt111->etat,"synthetique");inserer(L111,elt111,1);(*e)->T[7][11]=L111; LISTE L112=listecreer(); ELEMENT elt112=elementcreer(); elt112->num_at=112;strcpy(elt112->symbole,"Cu");elt112->masse_at=285;strcpy(elt112->etat,"synthetique");inserer(L112,elt112,1);(*e)->T[7][12]=L112; LISTE L113=listecreer(); ELEMENT elt113=elementcreer(); elt113->num_at=113;strcpy(elt113->symbole,"Uut");elt113->masse_at=286;strcpy(elt113->etat,"synthetique");inserer(L113,elt113,1);(*e)->T[7][13]=L113; LISTE L114=listecreer(); ELEMENT elt114=elementcreer(); elt114->num_at=114;strcpy(elt114->symbole,"Fl");elt114->masse_at=287;strcpy(elt114->etat,"synthetique");inserer(L114,elt114,1);(*e)->T[7][14]=L114; LISTE L115=listecreer(); ELEMENT elt115=elementcreer(); elt115->num_at=115;strcpy(elt115->symbole,"Uup");elt115->masse_at=288;strcpy(elt115->etat,"synthetique");inserer(L115,elt115,1);(*e)->T[7][15]=L115; LISTE L116=listecreer(); ELEMENT elt116=elementcreer(); elt116->num_at=116;strcpy(elt116->symbole,"Lv");elt116->masse_at=291;strcpy(elt116->etat,"synthetique");inserer(L116,elt116,1);(*e)->T[7][16]=L116; LISTE L117=listecreer(); ELEMENT elt117=elementcreer(); elt117->num_at=117;strcpy(elt117->symbole,"Uus");elt117->masse_at=292;strcpy(elt117->etat,"synthetique");inserer(L117,elt117,1);(*e)->T[7][17]=L117; LISTE L118=listecreer(); ELEMENT elt118=elementcreer(); elt118->num_at=118;strcpy(elt118->symbole,"Uuo");elt118->masse_at=294;strcpy(elt118->etat,"synthetique");inserer(L118,elt118,1);(*e)->T[7][18]=L118; } void tabelementafficher(ELEMENT_TAB e) { int i,j ; for (i=1;i<=7;i++){ for (j=1;j<=18;j++){ listeafficher(e->T[i][j]);} } } void tabelementcopier(ELEMENT_TAB *E1,ELEMENT_TAB E2) { int i,j; for(i=1;i<=7;i++){ for(j=1;j<=18;j++){ LISTE L=listecreer(); ELEMENT e= elementcreer(); elementcopier((*E1)->T[i][j]->tete->info,e); L=e; E2->T[i][j]=L; } } } void tabelementaffecter(ELEMENT_TAB *E1,ELEMENT_TAB E2) { int i,j; for(i=1;i<=7;i++){ for(j=1;j<=18;j++){ LISTE L=listecreer(); ELEMENT e= elementcreer(); elementcopier((*E1)->T[i][j]->tete->info,e); inserer(L,e,1); E2->T[i][j]=L; } } }
Java
UTF-8
427
2.84375
3
[]
no_license
package com.classifier.ttosom.distance; import static java.lang.Math.abs; import weka.core.Instance; public class ManhattanDistance implements Distance{ @Override public double calculate(Instance item1, Instance item2) { double result = 0.0; for(int i=0;i<item1.numAttributes();i++){ if(!item1.isMissing(i) && !item2.isMissing(i)){ result+=abs(item1.value(i)-item2.value(i)); } } return result; } }
Java
UTF-8
1,544
2.25
2
[]
no_license
/******************************************************************************* * Copyright (c) 2012 MadRobot. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * Contributors: * Elton Kent - initial API and implementation ******************************************************************************/ package com.madrobot.di.xml.io.path; import com.madrobot.di.xml.converter.ErrorWriter; import com.madrobot.di.xml.io.HierarchicalStreamReader; import com.madrobot.di.xml.io.ReaderWrapper; /** * Wrapper for HierarchicalStreamReader that tracks the path (a subset of XPath) * of the current node that is being read. * * @see PathTracker * @see Path * * @author Joe Walnes */ public class PathTrackingReader extends ReaderWrapper { private final PathTracker pathTracker; public PathTrackingReader(HierarchicalStreamReader reader, PathTracker pathTracker) { super(reader); this.pathTracker = pathTracker; pathTracker.pushElement(getNodeName()); } @Override public void appendErrors(ErrorWriter errorWriter) { errorWriter.add("path", pathTracker.getPath().toString()); super.appendErrors(errorWriter); } @Override public void moveDown() { super.moveDown(); pathTracker.pushElement(getNodeName()); } @Override public void moveUp() { super.moveUp(); pathTracker.popElement(); } }
JavaScript
UTF-8
1,821
2.5625
3
[]
no_license
/** * --------------------------------------- * This demo was created using amCharts 4. * * For more information visit: * https://www.amcharts.com/ * * Documentation is available at: * https://www.amcharts.com/docs/v4/ * --------------------------------------- */ // Use themes am4core.useTheme(am4themes_animated); // Create chart instance var chart = am4core.create("line-chart", am4charts.XYChart); chart.paddingRight = 20; // Add data chart.data = [{ "date": new Date(2018, 3, 20), "value": 90, "value2": 45 }, { "date": new Date(2018, 3, 21), "value": 102, "value2": 90 }, { "date": new Date(2018, 3, 22) }, { "date": new Date(2018, 3, 23), "value": 125 }, { "date": new Date(2018, 3, 24), "value": 55, "value2": 90 }, { "date": new Date(2018, 3, 25), "value": 81, "value2": 60 }, { "date": new Date(2018, 3, 26) }, { "date": new Date(2018, 3, 27), "value": 63, "value2": 87 }, { "date": new Date(2018, 3, 28), "value": 113, "value2": 62 }]; // Create axes var dateAxis = chart.xAxes.push(new am4charts.DateAxis()); dateAxis.renderer.minGridDistance = 50; dateAxis.renderer.grid.template.location = 0.5; dateAxis.startLocation = 0.5; dateAxis.endLocation = 0.5; // Create value axis var valueAxis = chart.yAxes.push(new am4charts.ValueAxis()); // Create series var series1 = chart.series.push(new am4charts.LineSeries()); series1.dataFields.valueY = "value"; series1.dataFields.dateX = "date"; series1.strokeWidth = 3; series1.tensionX = 0.8; series1.bullets.push(new am4charts.CircleBullet()); series1.connect = false; var series2 = chart.series.push(new am4charts.LineSeries()); series2.dataFields.valueY = "value2"; series2.dataFields.dateX = "date"; series2.strokeWidth = 3; series2.tensionX = 0.8; series2.bullets.push(new am4charts.CircleBullet());
Python
UTF-8
887
2.953125
3
[]
no_license
n = int(input()) if n==0: print(0) elif n==1: print(1) else: pn = 0 pnn = 1 sum = 1 lst = list() lst.append(0) lst.append(1) index = 2 flag = 0 for i in range(n-1): pnew = pn + pnn pn = pnn pnn = pnew sum = (sum+pnn)%10 lst.append(pnew%10) index = index+1 if lst[index-2] == 0 and lst[index-1] == 1 : lst.pop(index-1) lst.pop(index-2) flag = 1 index = index-2 break if flag == 1: lstsum = 0 remsum = 0 q = int(n/index) r = int(n%index) for i in range(index): lstsum = lstsum + lst[i] if i<=r: remsum = remsum + lst[i] sum = (q*lstsum + remsum)%10 print(sum) else: print(sum)
Java
UTF-8
12,648
3.46875
3
[]
no_license
package edu.wmich.cs3310.hw2.Thompson.application; import java.io.*; import java.util.*; import edu.wmich.cs3310.hw2.Thompson.queues.DoubleStackQueue; import edu.wmich.cs3310.hw2.Thompson.queues.IQueue; import edu.wmich.cs3310.hw2.Thompson.queues.Queue; import edu.wmich.cs3310.hw2.Thompson.stacks.DoubleQueueStack; import edu.wmich.cs3310.hw2.Thompson.stacks.IStack; import edu.wmich.cs3310.hw2.Thompson.stacks.Stack; /** * Main Class. Runs test on all of the implemented data structures with various different data types. * @author Tyler Thompson * */ public class Main { /** * Main method. uncomment "runTestProgram();" to see a more extensive test of the different implementations. * @param args */ public static void main(String[] args) { //Uncomment to following line to run a more extensive test of all implementations with various data types. //runTestProgram(); long curTime = System.currentTimeMillis(); runTestProgramFromFile("./TestForMinValue.txt"); runTestProgramFromFile("./TestForStackAndQueue.txt"); // runTestProgramFromFile("./TestInput.txt"); // runTestProgramFromFile("./LargeTestInput.txt"); long afterTime = System.currentTimeMillis(); long runTime = afterTime - curTime; System.out.println("Runtime: " + runTime + " milliseconds"); } /** * Runs a test of all implementations on the file specified. Since the data is read in as a string, it only tests on strings. * To test on data other then strings, run runTestProgram() * @param file File to run tests on. */ public static void runTestProgramFromFile( String file ) { System.out.println("Running test on file: " + file + "\n"); String[] stringArray = readFile(file); IStack<String> stringStack = new Stack<String>(); IQueue<String> stringQueue = new Queue<String>(); IStack<String> stringDoubleQueueStack = new DoubleQueueStack<String>(); IQueue<String> stringDoubleStackQueue = new DoubleStackQueue<String>(); fillStackString(stringStack, stringArray); fillQueueString(stringQueue, stringArray); stringDoubleQueueStack = fillStackString(stringDoubleQueueStack, stringArray); fillQueueString(stringDoubleStackQueue, stringArray); stringDoubleQueueStack.pop(); printStack(stringStack); printQueue(stringQueue); printStack(stringDoubleQueueStack); printQueue(stringDoubleStackQueue); System.out.println("Done.\n"); } /** * Reads data in a file and returns it in an array of type string. * @param fileLocation Location of the file to read. * @return The data in the file split up into a String array. */ public static String[] readFile( String fileLocation ) { ArrayList<String> listData = new ArrayList<String>(); try(BufferedReader br = new BufferedReader(new FileReader(fileLocation))) { for(String line; (line = br.readLine()) != null; ) { String [] lineData = line.split("\\s+"); for ( int i = 0; i < lineData.length; i++ ) { listData.add(lineData[i]); } } } catch (IOException e) { String[] error = { "Error", "reading", "file" }; return error; } String[] data = new String[listData.size()]; for ( int i = 0; i < listData.size(); i++ ) { data[i] = listData.get(i); } return data; } /** * Runs through all of the implementations with a few different data types. */ public static void runTestProgram() { String[] stringArray = { "1.02", "45", "1.001", "100", "2", "345", "50", "4.6", "8", "0" }; int[] intArray = { 9, 8, 17, 3, 5, 4, 5, 2, 1, 0 }; double[] doubleArray = { 23.3, 0.002, 23.3, 234.54345, 234.2, 2.2, 43.768, 0.0, }; float[] floatArray = { 234.3f, 234.45f, 0.00001f, 6.6f, 234.4f, 2340f, 26.2f, 0.0f }; long[] longArray = { 32423423L, 23458354L, 23458374598L, 238471857L, 9230943L, 489375L, 23423435345L, 0L }; IStack<String> stringStack = new Stack<String>(); fillStackString(stringStack, stringArray); IStack<Integer> intStack = new Stack<Integer>(); fillStackInt(intStack, intArray); IStack<Double> doubleStack = new Stack<Double>(); fillStackDouble(doubleStack, doubleArray); IStack<Float> floatStack = new Stack<Float>(); fillStackFloat(floatStack, floatArray); IStack<Long> longStack = new Stack<Long>(); fillStackLong(longStack, longArray); IQueue<String> stringQueue = new Queue<String>(); fillQueueString(stringQueue, stringArray); IQueue<Integer> intQueue = new Queue<Integer>(); fillQueueInt(intQueue, intArray); IQueue<Double> doubleQueue = new Queue<Double>(); fillQueueDouble(doubleQueue, doubleArray); IQueue<Float> floatQueue = new Queue<Float>(); fillQueueFloat(floatQueue, floatArray); IQueue<Long> longQueue = new Queue<Long>(); fillQueueLong(longQueue, longArray); IStack<String> stringDoubleQueueStack = new DoubleQueueStack<String>(); fillStackString(stringDoubleQueueStack, stringArray); IStack<Integer> intDoubleQueueStack = new DoubleQueueStack<Integer>(); fillStackInt(intDoubleQueueStack, intArray); IStack<Double> doubleDoubleQueueStack = new DoubleQueueStack<Double>(); fillStackDouble(doubleDoubleQueueStack, doubleArray); IStack<Float> floatDoubleQueueStack = new DoubleQueueStack<Float>(); fillStackFloat(floatDoubleQueueStack, floatArray); IStack<Long> longDoubleQueueStack = new DoubleQueueStack<Long>(); fillStackLong(longDoubleQueueStack, longArray); IQueue<String> stringDoubleStackQueue = new DoubleStackQueue<String>(); fillQueueString(stringDoubleStackQueue, stringArray); IQueue<Integer> intDoubleStackQueue = new DoubleStackQueue<Integer>(); fillQueueInt(intDoubleStackQueue, intArray); IQueue<Double> doubleDoubleStackQueue = new DoubleStackQueue<Double>(); fillQueueDouble(doubleDoubleStackQueue, doubleArray); IQueue<Float> floatDoubleStackQueue = new DoubleStackQueue<Float>(); fillQueueFloat(floatDoubleStackQueue, floatArray); IQueue<Long> longDoubleStackQueue = new DoubleStackQueue<Long>(); fillQueueLong(longDoubleStackQueue, longArray); printStack(stringStack); printStack(intStack); printStack(doubleStack); printStack(floatStack); printStack(longStack); printQueue(stringQueue); printQueue(intQueue); printQueue(doubleQueue); printQueue(floatQueue); printQueue(longQueue); printStack(stringDoubleQueueStack); printStack(intDoubleQueueStack); printStack(doubleDoubleQueueStack); printStack(floatDoubleQueueStack); printStack(longDoubleQueueStack); printQueue(stringDoubleStackQueue); printQueue(intDoubleStackQueue); printQueue(doubleDoubleStackQueue); printQueue(floatDoubleStackQueue); printQueue(longDoubleStackQueue); } /** * Fills a queue of type int. * @param queue The queue to fill. * @param array The array of data to fill the queue with. * @return IQueue The queue filled with the passed data. */ public static IQueue<Integer> fillQueueInt(IQueue<Integer> queue, int[] array) { for ( int i = 0; i < array.length; i++ ) { queue.add(array[i]); } return queue; } /** * Fills a queue of type string. * @param queue The queue to fill. * @param array The array of data to fill the queue with. * @return IQueue The queue filled with the passed data. */ public static IQueue<String> fillQueueString(IQueue<String> queue, String[] array) { for ( int i = 0; i < array.length; i++ ) { queue.add(array[i]); } return queue; } /** * Fills a queue of type double. * @param queue The queue to fill. * @param array The array of data to fill the queue with. * @return IQueue The queue filled with the passed data. */ public static IQueue<Double> fillQueueDouble(IQueue<Double> queue, double[] array) { for ( int i = 0; i < array.length; i++ ) { queue.add(array[i]); } return queue; } /** * Fills a queue of type float. * @param queue The queue to fill. * @param array The array of data to fill the queue with. * @return IQueue The queue filled with the passed data. */ public static IQueue<Float> fillQueueFloat(IQueue<Float> queue, float[] array) { for ( int i = 0; i < array.length; i++ ) { queue.add(array[i]); } return queue; } /** * Fills a queue of type long. * @param queue The queue to fill. * @param array The array of data to fill the queue with. * @return IQueue The queue filled with the passed data. */ public static IQueue<Long> fillQueueLong(IQueue<Long> queue, long[] array) { for ( int i = 0; i < array.length; i++ ) { queue.add(array[i]); } return queue; } /** * Fills a stack of type int. * @param stack The stack to fill with data. * @param array The array of data to fill the stack with. * @return IStack The stack filled with the passed data. */ public static IStack<Integer> fillStackInt(IStack<Integer> stack, int[] array) { for ( int i = 0; i < array.length; i++ ) { stack.push(array[i]); } return stack; } /** * Fills a stack of type string. * @param stack The stack to fill with data. * @param array The array of data to fill the stack with. * @return IStack The stack filled with the passed data. */ public static IStack<String> fillStackString(IStack<String> stack, String[] array) { for ( int i = 0; i < array.length; i++ ) { stack.push(array[i]); } return stack; } /** * Fills a stack of type double. * @param stack The stack to fill with data. * @param array The array of data to fill the stack with. * @return IStack The stack filled with the passed data. */ public static IStack<Double> fillStackDouble(IStack<Double> stack, double[] array) { for ( int i = 0; i < array.length; i++ ) { stack.push(array[i]); } return stack; } /** * Fills a stack of type float. * @param stack The stack to fill with data. * @param array The array of data to fill the stack with. * @return IStack The stack filled with the passed data. */ public static IStack<Float> fillStackFloat(IStack<Float> stack, float[] array) { for ( int i = 0; i < array.length; i++ ) { stack.push(array[i]); } return stack; } /** * Fills a stack of type long. * @param stack The stack to fill with data. * @param array The array of data to fill the stack with. * @return IStack The stack filled with the passed data. */ public static IStack<Long> fillStackLong(IStack<Long> stack, long[] array) { for ( int i = 0; i < array.length; i++ ) { stack.push(array[i]); } return stack; } /** * Dequeues all elements in the passed queue and prints them to the console. * If there are 1000 or more elements, it skips printing out all the elements. * @param queue The queue to print. */ public static <E> void printQueue(IQueue<E> queue) { int size = queue.size(); System.out.println("Printing " + queue.getClass().getSimpleName() + " of type " + queue.getType() + " with " + size + " elements."); if ( size > 999 ) { System.out.println("Queue to large to print. Will only print queues with less than 1000 elements. Deleting values without printing."); for ( int i = 0; i < size; i++ ) { queue.delete(); } } else { System.out.print("Front--> "); int j = 0; for ( int i = 0; i < size; i++ ) { j++; System.out.print(queue.delete() + " "); if ( j > 10 ) { System.out.println(); j = 0; } } System.out.print("<--Back"); } System.out.println("\n"); } /** * Pops all elements out of the passed stack and prints them to the console. * If there are 1000 or more elements in the stack it skips printing them to the console. * @param stack The stack to print. */ public static <E> void printStack(IStack<E> stack) { int size = stack.size(); System.out.println("Printing " + stack.getClass().getSimpleName() + " of type " + stack.getType() + " with " + size + " elements."); E minValue = stack.minValue(); if ( size > 999 ) { System.out.println("Stack to large to print. Will only print stacks with less than 1000 elements. Poping values without printing."); for ( int i = 0; i < size; i++ ) { stack.pop(); } } else { System.out.print("Top--> "); int j = 0; for ( int i = 0; i < size; i++ ) { j++; System.out.print(stack.pop() + " "); if ( j > 10 ) { System.out.println(); j = 0; } } System.out.print("<--Bottom"); } System.out.println("\nMin Value: " + minValue + "\n"); } }
Ruby
UTF-8
1,437
3.8125
4
[]
no_license
require './deck.rb' require './card.rb' require './maker.rb' @deck = Deck.new('dictionary.txt') @deck.set_current_card puts "Welcome to the Flash Card App\n" puts "You can play a matching game or" puts "create new flash cards" puts "" puts "To play the matching game type '-play'." puts "To create new card type '-create'." puts "To quit the game type '-exit'." puts "" command = "" command = gets.chomp while command != "-exit" case command when '-play' puts "We will show you a definition, you have three \n" puts "tries to guess the matching term. \n" puts "Currently the terms are case sensative." puts "Definition: #{@deck.current_card.definition}" print "What is the matching Term? " command = gets.chomp if @deck.guess_counter < 4 @deck.guess(command) end when '-exit' puts "" puts "Goodbye!" puts "" when '-create' puts "what's the new term?" new_term = gets.chomp puts "What's the definition?" new_definition = gets.chomp new_card_string = "#{new_term}\t#{new_definition}\n" maker = Maker.new maker.add_new_card(new_card_string) else puts "You are in the else" end end #this is a change
Java
UTF-8
286
2.609375
3
[]
no_license
package com.github.henriquesmoco.design_patterns.abstract_factory.cars.normal; import com.github.henriquesmoco.design_patterns.abstract_factory.CarBrakes; public class NormalBrakes implements CarBrakes { public void brake() { System.out.println("Normal Brakes"); } }
Java
UTF-8
1,048
4.0625
4
[]
no_license
package ejercicios; import java.util.Scanner; //validar un numero que se encuentre entre 1 - 10 public class ValidarNumeros { static Scanner in = new Scanner(System.in); public static void main(String[] args) { int minimo , maximo; do { System.out.println("Ingrese minimo"); minimo = in.nextInt(); System.out.println("Ingrese maximo"); maximo = in.nextInt(); } while (ValidarNumeros.validarNumeros(minimo, maximo)); int numero = ValidarNumeros.validarNumero(minimo, maximo); System.out.println("El numero " + numero + " se encuentra entre el rango establecido"); } public static int validarNumero(int minimo, int maximo) { int numero; do { System.out.println("Ingrese un numero"); numero = in.nextInt(); } while ((numero < minimo) || (numero > maximo)); return numero; } private static boolean validarNumeros(int minimo, int maximo) { boolean bandera = false; if (minimo > maximo) { System.out.println("Datos incorrectos"); bandera = true; } return bandera; } }
C#
UTF-8
5,103
3.375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static Algorithms.Sudoku; namespace Algorithms { public class Sudoku { public class PossibleValues { public int Row; public int Col; public List<int> Values; } static int[] PossilbeValues = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; static List<PossibleValues> PossibleValuesList = new List<PossibleValues>(); public static void Solve(int[,] sudoku) { GetPossibleValuesList(sudoku); SolveSudoku(sudoku); } private static bool SolveSudoku(int[,] sudoku) { var emptyCell = GetEmptyCell(sudoku); if(emptyCell.row == -1) { return true; } foreach (var possibleValue in PossibleValuesList.First(x => x.Row == emptyCell.row && x.Col == emptyCell.col).Values) { if(IsValidCellValue(sudoku, emptyCell.row, emptyCell.col, possibleValue)) { sudoku[emptyCell.row, emptyCell.col] = possibleValue; if(SolveSudoku(sudoku)) { return true; } sudoku[emptyCell.row, emptyCell.col] = 0; } } return false; } private static bool IsValidCellValue(int[,] sudoku, int row, int col, int possibleValue) { int rowStart, colStart; rowStart = (row / 3) * 3; colStart = (col / 3) * 3; for (int temp = 0; temp < 9; temp++) { if (sudoku[row, temp] == possibleValue) return false; if (sudoku[temp, col] == possibleValue) return false; if (sudoku[rowStart + (temp % 3), colStart + (temp % 3)] == possibleValue) return false; } return true; } private static (int row, int col) GetEmptyCell(int[,] sudoku) { for (int row = 0; row < 9; row++) { for (int col = 0; col < 9; col++) { if (sudoku[row, col] == 0) { return (row, col); } } } return ( -1, -1); } private static void GetPossibleValuesList(int[,] sudoku) { for (int row = 0; row < 9; row++) { for (int col = 0; col < 9; col++) { if (sudoku[row, col] == 0) { List<int> possilbeVaues = GetPossileValues(sudoku, row, col); if (possilbeVaues.Count() == 1) { sudoku[row, col] = possilbeVaues.FirstOrDefault(); } else if (possilbeVaues.Count() > 1) { PossibleValuesList.Add(new PossibleValues { Row = row, Col = col, Values = possilbeVaues }); } } } } } private static List<int> GetPossileValues(int[,] unsolvedSudoku, int row, int col) { List<int> posibleValues = new List<int>(PossilbeValues); //Eliminate Row and Column values for (int temp = 0; temp < 9; temp++) { if (unsolvedSudoku[row, temp] != 0 && temp != col) { posibleValues.Remove(unsolvedSudoku[row, temp]); } if (unsolvedSudoku[temp, col] != 0 && temp != row) { posibleValues.Remove(unsolvedSudoku[temp, col]); } } //Eliminate sub-matrix values RemoveSubMatrixValues(unsolvedSudoku, posibleValues, row, col); return posibleValues; } private static void RemoveSubMatrixValues(int[,] unsolvedSudoku, List<int> posibleValues, int row, int col) { int rowStart, colStart, rowEnd, colEnd; rowStart = (row / 3) * 3; colStart = (col / 3) * 3; rowEnd = rowStart + 2; colEnd = colStart + 2; for(int i = rowStart; i <= rowEnd; i++) { if (i == row) continue; for(int j= colStart; j <= colEnd; j++) { if (j == col) continue; if (unsolvedSudoku[i, j] != 0) { posibleValues.Remove(unsolvedSudoku[i, j]); } } } } } }
JavaScript
UTF-8
1,756
2.625
3
[ "MIT" ]
permissive
google.charts.load('current', {packages: ['corechart', 'bar']}); google.charts.setOnLoadCallback(drawAnnotations); function drawAnnotations() { var data = new google.visualization.DataTable(); data.addColumn('timeofday', 'Time of Day'); data.addColumn('number', 'Motivation Level'); data.addColumn({type: 'string', role: 'annotation'}); data.addColumn('number', 'Energy Level'); data.addColumn({type: 'string', role: 'annotation'}); data.addRows([ [{v: [8, 0, 0], f: '8 am'}, 1, '1', .25, '.2'], [{v: [9, 0, 0], f: '9 am'}, 2, '2', .5, '.5'], [{v: [10, 0, 0], f:'10 am'}, 3, '3', 1, '1'], [{v: [11, 0, 0], f: '11 am'}, 4, '4', 2.25, '2'], [{v: [12, 0, 0], f: '12 pm'}, 5, '5', 2.25, '2'], [{v: [13, 0, 0], f: '1 pm'}, 6, '6', 3, '3'], [{v: [14, 0, 0], f: '2 pm'}, 7, '7', 3.25, '3'], [{v: [15, 0, 0], f: '3 pm'}, 8, '8', 5, '5'], [{v: [16, 0, 0], f: '4 pm'}, 9, '9', 6.5, '6'], [{v: [17, 0, 0], f: '5 pm'}, 10, '10', 10, '10'], ]); var options = { title: 'Motivation and Energy Level Throughout the Day', annotations: { alwaysOutside: true, textStyle: { fontSize: 14, color: '#000', auraColor: 'none' } }, hAxis: { title: 'Time of Day', format: 'h:mm a', viewWindow: { min: [7, 30, 0], max: [17, 30, 0] } }, vAxis: { title: 'Rating (scale of 1-10)' } }; var chart = new google.visualization.ColumnChart(document.getElementById('chart_div')); chart.draw(data, options); }
Python
UTF-8
203
4.03125
4
[ "MIT" ]
permissive
tuple1 = ('apple', 'banana', 'cherry') for x in tuple1: print(x) # check if item exists if "apple" in tuple1: print('Yes, "apple" is in the fruits tuple') # get tuple length print(len(tuple1))
JavaScript
UTF-8
863
3.375
3
[]
no_license
/* A JavaScript module which returns prime factors of the input integer. Adapted from an existing JavaScript implementation of the algorithm. Citation: Minko Gechev, "javascript-algorithms", https://github.com/mgechev/javascript-algorithms, https://github.com/mgechev/javascript-algorithms/blob/master/src/primes/prime-factor-tree.js */ 'use strict' const primeFactors = (n = null) => { if (n === null) return null let a = [] let s = 6 n = Math.abs(n) while (n > 1 && n % 2 === 0) n = addFactor(n, a, 2) while (n > 2 && n % 3 === 0) n = addFactor(n, a, 3) while (n > 4) { let p = s - 1 let q = s + 1 while (n > 4 && n % p === 0) n = addFactor(n, a, p) while (n > 4 && n % q === 0) n = addFactor(n, a, q) s += 6 } return a } const addFactor = (n, a, n2) => { a.push(n2) n /= n2 return n } export default primeFactors
Java
UTF-8
1,102
2.65625
3
[ "Apache-2.0" ]
permissive
package com.coolapps.logomaker.utilities; import android.annotation.SuppressLint; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.Drawable; public class ColorCircleDrawable extends Drawable { private final Paint mPaint = new Paint(1); private int mRadius = 0; public ColorCircleDrawable(int color) { this.mPaint.setColor(color); } public void draw(Canvas canvas) { Rect bounds = getBounds(); canvas.drawCircle((float) bounds.centerX(), (float) bounds.centerY(), (float) this.mRadius, this.mPaint); } protected void onBoundsChange(Rect bounds) { super.onBoundsChange(bounds); this.mRadius = Math.min(bounds.width(), bounds.height()) / 2; } public void setAlpha(int alpha) { this.mPaint.setAlpha(alpha); } public void setColorFilter(ColorFilter cf) { this.mPaint.setColorFilter(cf); } @SuppressLint("WrongConstant") public int getOpacity() { return -3; } }
Python
UTF-8
1,270
2.828125
3
[]
no_license
# 简化 : 假设其中一个轴为0 def getRange(pts, ax): mx = pts[0][ax] mi = pts[0][ax] for p in pts: if p[ax] < mi: mi = p[ax] if p[ax] > mx: mx = p[ax] return mx - mi def pts2flatten(pts): ret = [] rg = [getRange(pts, i) for i in range(3)] deli = rg.index(min(rg)) print("deli:", deli) rsvi = [i for i in range(3) if i != deli] for p in pts: ret.append([p[rsvi[0]], p[rsvi[1]]]) return ret import math import numpy as np from PIL import Image size = 100 def pts2image(pts): x_range = [min(pts[:, 0]), max(pts[:, 0])] y_range = [min(pts[:, 1]), max(pts[:, 1])] x_w = int((x_range[1]-x_range[0])*size) y_w = int((y_range[1]-y_range[0])*size) arr = np.zeros((y_w+1, x_w+1), dtype=np.uint) print(arr.shape) print(len(pts)) for p in pts: x = int((p[0]-x_range[0])*size) y = int((p[1]-y_range[0])*size) print(x,y) arr[y][x] = 255 print(arr.shape) img = Image.fromarray(arr, '1') img.save('tmp.png') # import pytesseract from PIL import Image # # def getNumAns(pts): pts image = Image.open('tmp.jpg') code = pytesseract.image_to_string(image) return code import numpy as np
TypeScript
UTF-8
601
2.71875
3
[ "MIT" ]
permissive
import * as PropTypes from 'prop-types' import * as React from 'react' import { createElement, ReactElement } from 'react' export type Mapper<T> = (value?: T, key?: number, target?: T[]) => any; /** * Render the result of dispatching to the `map` method of `target` * passing the `with` function as the first argument. */ export function Map<T>({ target, 'with': _with }: { target: T[], with: Mapper<T> }): ReactElement<any> { return createElement(React.Fragment, null, target.map(_with)) } (Map as any).propTypes = { target: PropTypes.any.isRequired, with: PropTypes.func.isRequired }
Markdown
UTF-8
11,018
2.703125
3
[]
no_license
--- layout: entry post-category: geultto title: 글또 5기를 마치며 author: 김성중 author-email: ajax0615@gmail.com description: 글또 5기 활동을 마치며 6개월 동안의 느낀 점을 쓴 글이에요. keywords: 글쓰기, 글또, 회고 thumbnail-image: /images/profile/geultto.png publish: true --- 잊고 있었는데, 생각해보니 글또 시작 전에 [Get comfortable with being uncomfortable](https://sungjk.github.io/2020/11/15/get-comfortable-being-uncomfortable.html)라는 글을 주제로 다짐글을 썼었네요. 글또 활동하면서 기대하는 점과 어떤 글을 쓸지에 대해 기록했었어요. 그때 작성했던 다짐글에 대한 회고를 시작으로 6개월 동안 썼던 글도 되돌아 보고, 글또 활동하면서 좋았던 점과 아쉬웠던 점에 대해서 이야기해볼까 해요. ![geultto](/images/profile/geultto.png "geultto"){: .center-image } ### 다짐글 되돌아보기 첫 번째. 회사, 사이드 프로젝트 또는 개발 공부를 하면서 경험했던 기술적인 이야기들이나 이슈를 적어보려 했었어요. Spring Webflux, 데이터 암호화, Kafka 그리고 2020년 회고에 적었던 사이드 프로젝트 이야기를 적었던게 생각나요. 경험했던 것들을 되도록 많이 기록해두고 싶었는데, 쉽지 않았던거 같아요. 예를 들어, 회사에서 Kafka를 많이 사용하다 보니 개인적으로 공부한 기록은 남겨두었는데, 사용하면서 겪었던 문제나 경험담에 대해 이야기를 하지 못한게 아쉽다는 생각이 들어요. 그래서 다음에는 관심과 필요에 의해 어떤 기술을 주제로 글을 쓸 때, 겪었던 문제나 힘듦 또는 좋았던 점들을 함께 써야겠어요. 다음에 똑같은 문제를 반복하지 않게 하는 회고와 포스트모템(Postmortem)이 될 수도 있고, 글을 읽는 누군가에게 조금이나마 더 도움이 되지 않을까 싶어서요. 두 번째. 개발자로서 요즘은 어떤 일을 하고 있고, 어떤 기술에 관심이 있는지 등 근황에 대한 이야기를 적어보려 했었어요. 이건 회고와는 다르게, 좀 더 가볍게 Chit Chat 정도로 생각했었어요. 아쉽게도? 이걸 주제로 한 글은 하나도 못 썼어요. 대개 이런 글은 블로그보다 트위터에 더 어울릴 것 같다는 생각이 들어요. 블로그 방문자의 대부분이 오가닉 서치(Organic Search)를 통해 유입되기도 하고, 블로그 성격과도 어울리지 않아서요. 그래서 회고와 스터디한 내용을 작성하는 것만으로도 충분할 것 같다는 생각이에요. 세 번째. 책을 읽고 나서 짧게라도 소감을 담은 독후감을 적어보려 했었어요. 기억의 농도는 날이 갈수록 옅어지잖아요. 행복한 순간뿐만 아니라 일상에서의 기록을 사진으로 남겨두는 이유는 이 옅어지는 기억의 농도를 그 순간이나마 짙게 만들기 위함이라고 생각해요. 어떤 순간에 들었던 생각과 느낌도 마찬가지라고 생각해요. 시간이 한참 흐른 뒤에 아무런 기록 없이 어린왕자에 대해 생각해보면 보아뱀, 여우, 장미꽃 등 흐릿한 이미지로만 가득했어요. 어린왕자가 여우를 만나면서 느꼈던 - 물리적인 것이 아닌 정신적인 측면에서 진정한 관계가 만들어질 수 있음을 깨닫는 - 느낌 같은건 없이 말이죠. 그래서 글또 활동 중에 읽었던 책들의 느낌을 기록하려 했었는데, 6개월 동안 작성한 독후감이 하나 밖에 없다는게 조금 아쉬웠어요. 최근에 읽었던 언카피어블 내용이 너무 좋아서 독후감을 쓰려고 했는데, 아직 독후감을 쓰는건 해야 할 숙제처럼 느껴져서 의도적으로 노력을 해야 되더라고요. 완성도 높은 독후감보다는 짧게라도 기록해보는 연습을 시작해봐야겠어요. --- ### 6개월 동안 썼던 글 ![끝](/images/2021/05/02/finish.png "끝"){: .center-image } 글또는 시작할 때 10만원의 예치금을 걷고 나서, 2주에 한 번씩 글을 써야 되는데 한 번 빼먹을 때마다 1만원씩 차감되더라구요. 그리고 바빠서 글을 못 쓰는 경우를 대비해서 2번의 패스를 사용할 수 있었어요. 이왕 참여한거 한 번도 빠지지 말고 써야겠다고 다짐을 했는데, 어렸을 때부터 근성 있게 꾸준히 하는걸 잘해서 목표를 달성할 수 있었어요. 이 글이 5기 활동하면서 마지막으로 쓰는 글이 될 텐데, 꾸준히 썼다는 점에 대해서는 스스로 뿌듯하더라구요. 이뿐만 아니라, 그동안 썼던 글이 검색 엔진의 상위에 노출되거나 구독 중인 기술 블로그에 소개되어서 블로그 지표가 전체적으로 좋아졌어요. 1. 2020.11.08. [Practical 모던 자바](https://sungjk.github.io/2020/11/08/practical-modern-java.html) 2. 2020.11.15. [Get comfortable with being uncomfortable](https://sungjk.github.io/2020/11/15/get-comfortable-being-uncomfortable.html) 3. 2020.11.28. [암호화 알고리즘과 Spring Boot Application에서 Entity 암호화](https://sungjk.github.io/2020/11/28/data-encryption-entity.html) 4. 2020.12.13. [귀차니즘을 해결해주는 Alfred](https://sungjk.github.io/2020/12/13/alfred-tips.html) 5. 2020.12.27. [제레미의 2020년 회고](https://sungjk.github.io/2020/12/27/jeremy.html) 6. 2021.01.10. [Kafka Consumer 알아보기](https://sungjk.github.io/2021/01/10/kafka-consumer.html) 7. 2021.01.23. [Kafka Producer 알아보기](https://sungjk.github.io/2021/01/23/kafka-producer.html) 8. 2021.01.29. [플랫폼 레볼루션](https://sungjk.github.io/2021/01/29/platform-revolution.html) 9. 2021.02.07. [커뮤니케이션 방식과 PR 템플릿 개선해보기](https://sungjk.github.io/2021/02/07/communicaton-and-prtemplate.html) 10. 2021.02.20. [가변성(Variance) 알아보기 - 공변, 무공변, 반공변](https://sungjk.github.io/2021/02/20/variance.html) 11. 2021.03.02. [비난과 비판의 차이](https://sungjk.github.io/2021/03/02/blame-vs-criticism.html) 12. 2021.03.07. [더 나은 글쓰기를 위한 여정](https://sungjk.github.io/2021/03/07/jeremy-writing.html) 13. 2021.03.20. [리팩터링 1 - Refactoring 1](https://sungjk.github.io/2021/03/20/refactoring-01.html) 14. 2021.03.31. [리팩터링 2 - Refactoring 2](https://sungjk.github.io/2021/03/31/refactoring-02.html) 15. 2021.04.17. [리팩터링 3 - Refactoring 3](https://sungjk.github.io/2021/04/17/refactoring-03.html) 16. 2021.04.17. [리팩터링 4 - Refactoring 4](https://sungjk.github.io/2021/04/17/refactoring-04.html) 17. 2021.04.17. [리팩터링 5 - Refactoring 5](https://sungjk.github.io/2021/04/17/refactoring-05.html) 18. 2021.05.02. [글또 5기를 마치며](https://sungjk.github.io/2021/05/02/geultto-5th.html) ![Kafka Consumer](/images/2021/05/02/kafka-consumer.png "Kafka Consumer"){: .center-image } ![platform-revolution](/images/2021/05/02/platform-revolution.png "platform-revolution"){: .center-image } ![spring-boot-encryption](/images/2021/05/02/spring-boot-encryption.png "spring-boot-encryption"){: .center-image } ![alfred](/images/2021/05/02/alfred.png "alfred"){: .center-image } --- ### 글또 5기 되돌아보기 글또 활동하면서 유일하게 작성했던 독후감인 [플랫폼 레볼루션](https://sungjk.github.io/2021/01/29/platform-revolution.html)에도 잠깐 비슷한 개념이 나오는데, 요즘 관심 있는 개념 중 하나가 아마존의 플라이 휠(Fly Wheel)이에요. 플라이 휠은 동력 없이 관성만으로 회전 운동을 하는 자동차 부품이에요. 처음에는 플라이 휠을 돌리기 위해 엄청난 추진력이 필요하지만, 한 번 가속도가 붙으면 알아서 돌아가요. 제프 베조스(Jeff Bezos)는 아마존을 어마어마한 회사로 성장시키기 위해 기업 경영에 이런 플라이 휠 개념을 적용했어요. 1. 가격을 낮춰 고객을 모은다. 2. 고객이 늘면 물건을 팔려는 판매자들이 많아진다. 3. 규모가 커지면 고정 비용이 낮아지고 효율성이 높아진다. 4. 효율성이 높아지면 가격을 더 낮출 수있다. ![amazon-flywheel](/images/2021/05/02/amazon-flywheel.jpg "amazon-flywheel"){: .center-image } 얘기만 들어보면 아주 이상적이고 당연한 이야기처럼 들리지만, 처음 플라이 휠을 돌리기 위해 엄청난 추진력이 필요한 것처럼 시작이 가장 어려운 법이에요. 이건 경영 뿐만 아니라 어떤 습관을 기르는데에도 똑같이 적용 된다고 생각해요. 차이가 있다면 시작할 때 가속을 얼마나 내느냐인데요. 저는 어떤 목표한 바가 있으면 작은 것부터 천천히 시작해보는 편이에요. 처음부터 엄청 가속을 내다보면 오래 가지 못하고 금방 지칠 수 있잖아요. 그래서 작은 것부터 성취해 보면서 나만의 루틴을 만들고, 이런 루틴이 모여서 플라이 휠처럼 Positive Cycle을 만들 수 있다고 생각해요. 이런 면에서 글또는 글쓰는 습관을 기르는데에 좋은 커뮤니티에요. 6개월은 어떤 습관을 만들기 위해 절대 짧은 시간이 아니잖아요. 글을 쓰기 위해 많은 에너지가 필요한건 사실이지만, 꾸준히 글을 쓰다 보면 생각을 정리하는 방법을 배울 수 있고, 잘 정돈된 글로 누군가에게 제안하거나 설득하는 능력도 기를 수 있어요. 내가 작성한 글이 누군가에게 공감을 받거나 누군가의 생각을 설득하는 경험을 한 번 해보면, 글을 더 잘 쓰고 싶다는 생각이 커지고 이 과정을 천천히나마 반복하게 되더라구요. ![feedback](/images/2021/05/02/feedback.png "feedback"){: .center-image } 저는 피드백을 받고 싶어서 글또에 참여했는데, 좋은 피드백을 주고 받기는 참 쉽지 않은거 같아요. 좋은 피드백에 대한 기준이 서로 다를 뿐만 아니라, 서로 관심 분야가 다르기도 하고 기술적인 글은 이해하기가 어려운 경우도 있기 때문이에요. 그래서 피드백을 어떻게 주면 좋을지 서로 의견을 나누어 보았는데요, 글을 제출할 때 각자 어떤 피드백을 받고 싶은지 적어주기로 했어요. 이건 코드 리뷰를 할 때에 비슷하게 느꼈던 점인데, 어떤 부분을 중점적으로 보면 좋을지 알려주면 리뷰어 입장에서 좀 더 구체적인 피드백을 줄 수 있더라구요. 그리고 항상 느끼는건데 피드백 문화에 정답은 없는거 같아요. 피드백을 자주 받고 싶은 사람도 있고, 아예 받기 싫은 사람도 있어서 모두의 의견을 존중하고 조율해야 할 필요가 있거든요. 끝으로, 피드백을 꼼꼼히 남기지 못했던 점은 반성하고 그동안 꼼꼼하게 피드백을 남겨주셨던 5기 구성원분들께 감사하다는 인사를 남기고 싶어요.
JavaScript
UTF-8
4,471
3.171875
3
[]
no_license
"use strict"; var name; var playerClass; var EnemyObj = {}; var PlayerObj; var weaponChosen; let Gauntlet = require("./classes.js"); let CreatePlayer = require("./CreatPlayer.js"); let Weapons = require("./ChooseWeapon.js"); let Battle = require("./Battle.js"); $(document).ready(function() { console.log("Gauntlet: ", Gauntlet); // Show the initial view that accepts player name $("#player-setup").show(); // When user enters name $("#selectClass").click(function(event) { name = $("#player-name").val(); console.log("Hello you friggin' ", name); }); // When user clicks a (blue) class button (not the submit button) $(".classButton").click(function(event){ console.log("playerClass", playerClass); playerClass = event.target.textContent; console.log("You added the " + playerClass + " class."); }); // When user clicks surprise me class $(".surpriseButton").click(function(event) { playerClass = event.target.textContent; console.log(event.target.textContent); console.log("Are you crazy? Yes. Yes you are."); }); // When user clicks a (blue) weapon button $(".weaponButton").click(function(event){ weaponChosen = event.target.textContent; console.log("You added the " + weaponChosen + " weapon."); }); // When user submits what class they want to play $("#selectWeapon").click(function(event) { console.log("Gauntlet: ", Gauntlet); PlayerObj = CreatePlayer.createPlayer(playerClass, PlayerObj, name); }); // When user chooses weapon $("#battleButton").click(function(event) { // style="width:0%" // Create Enemy PlayerObj = Weapons.chooseWeapon(weaponChosen, PlayerObj); EnemyObj = createEnemy(); Battle.printToDom(PlayerObj, EnemyObj); $("#player2-progress").css("width", '100%'); $("#player1-progress").css("width", '100%'); console.log("FINAL ENEMY: ", EnemyObj); }); // Attack Button $("#attackButton").click(function(event) { console.log("----------- Enemy Health: ", EnemyObj.health); console.log("----------- Player Health: ", PlayerObj.health); console.log("----------- Enemy Strength: ", EnemyObj.strength); console.log("----------- Player Strength: ", PlayerObj.strength); if(Battle.attack(PlayerObj, EnemyObj)){ console.log("1st True"); Battle.printToDom(PlayerObj, EnemyObj); } if(Battle.attack(EnemyObj, PlayerObj)){ console.log("2nd True"); Battle.printToDom(PlayerObj, EnemyObj); }else{ Battle.printToDom(PlayerObj, EnemyObj); console.log("GAME 2 ELSE"); } }); // Creates the random enemy function createEnemy () { let tempHealth = (Math.floor(Math.random() * 175) + 100).toFixed(0); EnemyObj = { name: "Enemy", playerName: "Adam", health: tempHealth, initialHealth: tempHealth, strength: (Math.floor(Math.random() * 50) + 1.8).toFixed(0), intelligence: (Math.floor(Math.random() * 5) + 1).toFixed(0), }; var FingersOfFury = { name: "Fingers of Fury", hands: 2, damage: (Math.floor(Math.random() * 50) + 1) }; EnemyObj.weapon = FingersOfFury; return EnemyObj; } /*****************/ /*** DOM STUFF ***/ /*****************/ // When any button with card__link class is clicked, move on to the next view. $(".card__link").click(function(e) { var nextCard = $(this).attr("next"); var moveAlong = false; switch (nextCard) { case "card--class": moveAlong = ($("#player-name").val() !== ""); break; case "card--weapon": moveAlong = ((playerClass) !== undefined); break; case "card--battleground": moveAlong = ((weaponChosen) !== undefined); break; } if (moveAlong) { $(".card").hide(); $("." + nextCard).show(); } }); // When the back button clicked, move back a view $(".card__back").click(function(e) { var previousCard = $(this).attr("previous"); $(".card").hide(); $("." + previousCard).show(); }); });
JavaScript
UTF-8
461
2.671875
3
[ "MIT" ]
permissive
/*global global,globalDocument,isHostMethod */ /* Description: Relies on `document.addEventListener`. */ /* Degrades: IE8, IE7, IE6, IE5.5, IE5, IE4, IE3 */ var attachDocumentListener; if(globalDocument && isHostMethod(globalDocument, 'addEventListener')) { attachDocumentListener = function(eventType, fn) { var listener = function(e) { fn.call(document, e); }; document.addEventListener(eventType, listener, false); return listener; }; }
JavaScript
UTF-8
1,618
2.828125
3
[ "MIT" ]
permissive
/** * @file lib/index.js */ 'use strict'; const cloneDeep = require('lodash.clonedeep'); const isPlainObject = require('is-plain-object'); const request = require('@avidjs/request'); const response = require('@avidjs/response'); /** * An Avid request object. * @typedef {Object} Request */ /** * An Avid response object. * @typedef {Object} Response */ /** * An Avid context object. * @typedef {Object} Context * @property {Request} request * @property {Response} response */ /** * Creates an Avid context object from HTTP request and response objects to * pass through middleware stacks. * @param {Object} ctx * @param {IncomingMessage} req * @param {ServerResponse} res * @return {Context} * @see {@link https://nodejs.org/api/http.html#http_class_http_incomingmessage} * @see {@link https://nodejs.org/api/http.html#http_class_http_serverresponse} */ module.exports = function context(ctx, req, res) { const contextObj = {}; // If the context object's property is a plain object, perform a deep clone // to prevent overriding values defined at the application level. If the // property is a primitive value or class instance, assign directly to avoid // the overhead of deep cloning more complex objects. Object.keys(ctx).forEach((property) => { if (isPlainObject(ctx[property])) { contextObj[property] = cloneDeep(ctx[property]); } else { contextObj[property] = ctx[property]; } }); return Object.assign(contextObj, { request: request(req, ctx.settings), response: response(res, ctx.settings) }); };
Markdown
UTF-8
1,622
2.609375
3
[]
no_license
# Linksys Router Setup **Router Model:** EA6350 | _3.1.10.191322_ Only follow this guide for a new router setup. To factory reset a Linksys hold in the reset button for ~11 seconds and let go (or go to Troubleshooting > Diagnostics > Factory Reset). Also, make sure the computer used to set it up is hardwired! Visit http://192.168.1.1 to access the router. 1. Setup 2.4/5Ghz Wireless access points w/ strong passwords 2. Create a local access account & password 1. Default password is `admin` 3. Rename the router 4. Disable guest access (Forces weak password!) 5. Media Prioritization 1. pi-hole 2. Gaming PC 3. Macbook Pro 6. External Storage 1. Enable Secure Folder Access 1. Create a user with a strong password 2. Create a shared folder for the new user (e.g Public) 2. Disable Media Server 7. Wireless 1. For 2.4 and 5GHz networks: 1. SSID: Clever, long, simple and unique 2. Security Mode: WPA2 Personal 3. Password: Very strong 4. Disable "Broadcast SSID" 8. Connectivity 1. Basic 1. Verify Network Access Points are correct from Step 6 2. Change Time Zone 2. Local Network 1. Change Start IP address 2. Set Maximum number of users 3. Set Static DNS: 1. `192.168.1.2` - pi-hole 2. `1.1.1.1` - CloudFlare 3. `1.0.0.1` - CloudFlare 2 4. `8.8.8.8` - Google 4. DHCP Reservations: Setup any reserved IPs necessary here (need MAC addresses!) 1. Tip: To assign out-of-range, you may need to change the range first, assign DHCP, and change the range back ###### Enjoy!
Java
UTF-8
1,509
2.546875
3
[ "MIT" ]
permissive
package org.hisrc.tenet.base.serialization; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.function.Supplier; import java.util.stream.Stream; import org.apache.commons.lang3.Validate; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema; public class JacksonCsvDeserializer<I> implements Supplier<Stream<? extends I>> { private final InputStream inputStream; private Class<I> itemClass; public JacksonCsvDeserializer(Class<I> itemClass, InputStream inputStream) { Validate.notNull(itemClass); Validate.notNull(inputStream); this.itemClass = itemClass; this.inputStream = inputStream; } @Override public Stream<? extends I> get() { final CsvMapper mapper = new CsvMapper(); final CsvSchema schema = mapper.schemaFor(itemClass).withHeader().withColumnSeparator(';'); final ObjectReader reader = mapper.readerFor(itemClass).with(schema); try { Iterator<I> readValues = reader.readValues(inputStream); List<I> values = new LinkedList<>(); while (readValues.hasNext()) { I next = readValues.next(); values.add(next); } return values.stream(); } catch (Exception ex) { throw new IllegalStateException("Could not read deserialize the object.", ex); } finally { try { inputStream.close(); } catch (IOException ignored) { } } } }
C#
UTF-8
1,138
2.546875
3
[]
no_license
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Security.Claims; using System.Security.Principal; using System.Text; using System.Threading.Tasks; using RabiesApplication.Web.Models; namespace RabiesApplication.Web.Repositories { public class UserRepository : ModelRepository<ApplicationUser> { public UserRepository() { } public string GetUserID(IPrincipal user) { // get claims identity to retrieve app user's id var identity = user.Identity as ClaimsIdentity; if (identity == null || !identity.HasClaim(c => c.Type == ClaimTypes.NameIdentifier)) return null; // user app user's id to fetch app user record with related employee and organization records return identity.Claims.Single(c => c.Type == ClaimTypes.NameIdentifier).Value; } public ApplicationUser GetAppUserForPrincipal(IPrincipal user) { var userId = GetUserID(user); return All().Where(u => u.Id == userId).Include("Employee.Organization").Single(); } } }
Python
UTF-8
889
2.828125
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- from dao import db,Base from datetime import datetime class ItemModel(Base): __tablename__ = 'itens' id = db.Column(db.Integer, primary_key=True) nome = db.Column(db.String(200), unique=True) data_criacao = db.Column(db.DateTime) listas = db.relationship("ItemLista", back_populates="item") def __init__(self, nome): self.nome = nome self.data_criacao = datetime.now() def adicionar(self): db.session.add(self) db.session.commit() @classmethod def encontrar_pelo_id(cls, _id): return cls.query.filter_by(id=_id).first() @classmethod def encontrar_pelo_nome(cls, nome): return cls.query.filter_by(nome=nome).first() @classmethod def listar(cls): return cls.query.all() def remover(self): db.session.delete(self) db.session.commit()
PHP
UTF-8
727
2.84375
3
[ "MIT" ]
permissive
<?php namespace Ayeo\Barcode\Response; use Ayeo\Barcode\Printer; abstract class Response { public function __construct(Printer $printer) { $this->printer = $printer; } abstract function getType(); /** * @param string $text * @param string $filename * @param bool $withLabel * @param string $disposition * @return void */ public function output($text, $filename, $withLabel, $disposition = 'inline') { header(sprintf('Content-Type: %s', $this->getType())); header(sprintf('Content-Disposition: %s;filename=%s', $disposition, $filename)); imagepng($this->printer->getResource($text, $withLabel)); } }
Java
UTF-8
471
2.390625
2
[]
no_license
package model; import java.util.List; import dao.ReserveDAO; // public class ReserveCheck { public boolean checkReserve(int planId,String checkin,int numOfNights){ boolean bool = true; //初期値true ReserveDAO dao = new ReserveDAO(); List<Integer> roomNumList = dao.reserveDays(planId,checkin,numOfNights); for(int reserveDays:roomNumList){ if(reserveDays == 0 ){ bool = false; } } return bool; } }
Java
UTF-8
1,032
2.265625
2
[]
no_license
package com.application.topiclish.dto; import java.io.Serializable; public class Status implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private String code; private String meaning; private String errorMessage; /** * @return the code */ public String getCode() { return code; } /** * @param code the code to set */ public void setCode(String code) { this.code = code; } /** * @return the meaning */ public String getMeaning() { return meaning; } /** * @param meaning the meaning to set */ public void setMeaning(String meaning) { this.meaning = meaning; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } public class Constants{ public static final String successStatus = "Success"; public static final String failureStatus = "Fail"; public static final String successCode = "00"; public static final String failureCode = "01"; } }
Java
UTF-8
1,316
2.21875
2
[]
no_license
package com.okta.spring.example.xmldto; import java.io.Serializable; public class TicketPayload implements Serializable { /** * Serial version */ private static final long serialVersionUID = 1L; private String packageName; private String ticketTitle; private String ticketCurrency; private Double ticketPrice; private String ticketDescription; public String getTicketTitle() { return ticketTitle; } public void setTicketTitle(String ticketTitle) { this.ticketTitle = ticketTitle; } public String getTicketCurrency() { return ticketCurrency; } public void setTicketCurrency(String ticketCurrency) { this.ticketCurrency = ticketCurrency; } public Double getTicketPrice() { return ticketPrice; } public void setTicketPrice(Double ticketPrice) { this.ticketPrice = ticketPrice; } public String getTicketDescription() { return ticketDescription; } public void setTicketDescription(String ticketDescription) { this.ticketDescription = ticketDescription; } public String getPackageName() { return packageName; } public void setPackageName(String packageName) { this.packageName = packageName; } }
Python
UTF-8
2,412
2.671875
3
[]
no_license
#!/usr/bin/env python # # Copyright (C) 2018 FIBO/KMUTT # Written by Nasrun Hayeeyema # ######################################################## # # STANDARD IMPORTS # import sys import os ######################################################## # # LOCAL IMPORTS # from PyQt4 import QtGui ######################################################## # # GLOBALS # ######################################################## # # EXCEPTION DEFINITIONS # ######################################################## # # HELPER FUNCTIONS # ######################################################## # # CLASS DEFINITIONS # class Profile( QtGui.QWidget ): def __init__( self ): super( Profile, self ).__init__() # create name and box to specefiy self.nameLabel = QtGui.QLabel( "Name" ) self.nameEdit = QtGui.QLineEdit() # create address and box specify self.addressLabel = QtGui.QLabel( "Address" ) self.addressEdit_1 = QtGui.QLineEdit() self.addressEdit_2 = QtGui.QLineEdit() # create two lines address edit by v-box layout self.verticalBoxLayout = QtGui.QVBoxLayout() self.verticalBoxLayout.addWidget( self.addressEdit_1 ) self.verticalBoxLayout.addWidget( self.addressEdit_2 ) # create sex and choices to select self.sexLabel = QtGui.QLabel( "Sex" ) self.maleRadioButton = QtGui.QRadioButton( "Male" ) self.femaleRadioButton = QtGui.QRadioButton( "Female" ) # create horizontal layout for groping radio button self.horizontalBoxLayout = QtGui.QHBoxLayout() self.horizontalBoxLayout.addWidget( self.maleRadioButton ) self.horizontalBoxLayout.addWidget( self.femaleRadioButton ) self.horizontalBoxLayout.addStretch() # create two push buttons self.submitButton = QtGui.QPushButton( "Submit!" ) self.cancelButton = QtGui.QPushButton( "Cancel" ) # create form layout for grouping above together self.formLayoutBox = QtGui.QFormLayout() self.formLayoutBox.addRow( self.nameLabel, self.nameEdit ) self.formLayoutBox.addRow( self.addressLabel, self.verticalBoxLayout ) self.formLayoutBox.addRow( self.sexLabel, self.horizontalBoxLayout ) self.formLayoutBox.addRow( self.submitButton, self.cancelButton ) # set layout self.setLayout( self.formLayoutBox ) if __name__ == "__main__": # initial app app = QtGui.QApplication( sys.argv ) # call widget profileWidget = Profile() # show profileWidget.show() # execute app sys.exit( app.exec_() )
Ruby
UTF-8
1,047
2.546875
3
[ "MIT" ]
permissive
require 'swagger/swagger_object' require 'swagger/v2/operation' module Swagger module V2 # Class representing a Swagger "Path Item Object". # @see https://github.com/wordnik/swagger-spec/blob/master/versions/2.0.md#pathItemObject Path Item Object class Path < SwaggerObject extend Forwardable def_delegator :parent, :host VERBS = [:get, :put, :post, :delete, :options, :head, :patch].freeze VERBS.each do |verb| field verb, Operation end field :parameters, Array[Parameter] def operations VERBS.each_with_object({}) do |v, h| operation = send v h[v] = operation if operation end end def uri_template "#{parent.host}#{parent.base_path}#{path}" end def path parent.paths.key self end # Iterates over each Path level parameter. def each_parameter return if parameters.nil? parameters.each do |parameter| yield parameter end end end end end
Python
UTF-8
5,440
3.09375
3
[]
no_license
import matplotlib.pyplot as plt import numpy as np # Artists frequently listened to defaultArtists = {'Taylor Swift', 'Joji', 'Katy Perry', 'Miley Cyrus', 'Ariana Grande', 'Shawn Mendes'} #defaultArtists = {'Taylor Swift'} class MyArtists: longTermArtistsLimit = 50 # Only from 0-50 for now shortTermArtistsLimit = 30 # Only from 0-50 for now def __init__(self, _spotifyClient): self.artists = defaultArtists self.spotifyClient = _spotifyClient # Get my top artists according to spotifies calculated affinities over years of data def AddTopArtistsLongTerm(self): results = self.spotifyClient.current_user_top_artists(self.longTermArtistsLimit, 0, 'long_term') for artist in results['items']: self.artists.add(artist['name']) # Get my top artists according to spotifies calculated affinities over the last 4 weeks. # The idea is to give recognition to fresh artists that I am currently enjoying a lot, even if # I haven't been listening to them for a long time def AddTopArtistsShortTerm(self): results = self.spotifyClient.current_user_top_artists(self.shortTermArtistsLimit, 0, 'short_term') for artist in results['items']: self.artists.add(artist['name']) # maybe add a retrieval for medium term? # Perhaps get popular artists? or artists of popular tracks class ArtistAnalytics: numDataPoints = 50 # Max 50 for now class ArtistStats_t: def __init__(self, artistName, artistPopularity, artistGenres): self.name = artistName self.popularity = artistPopularity self.genres = artistGenres def __init__(self, _spotifyClient): self.spotifyClient = _spotifyClient self.shortTermList = [] self.mediumTermList = [] self.longTermList = [] def QueryArtistStats(self): shortTermResults = self.spotifyClient.current_user_top_artists(ArtistAnalytics.numDataPoints, 0, 'short_term') for artist in shortTermResults['items']: self.shortTermList.append(ArtistAnalytics.ArtistStats_t(artist['name'],artist['popularity'],artist['genres'])) mediumTermResults = self.spotifyClient.current_user_top_artists(ArtistAnalytics.numDataPoints, 0, 'medium_term') for artist in mediumTermResults['items']: self.mediumTermList.append(ArtistAnalytics.ArtistStats_t(artist['name'],artist['popularity'],artist['genres'])) longTermResults = self.spotifyClient.current_user_top_artists(ArtistAnalytics.numDataPoints, 0, 'long_term') for artist in longTermResults['items']: self.longTermList.append(ArtistAnalytics.ArtistStats_t(artist['name'],artist['popularity'],artist['genres'])) # Average popularity of top artists from different time ranges def CreatePopularityBarGraph(self): shortTermPop, mediumTermPop, longTermPop = 0,0,0 for artist in self.shortTermList: shortTermPop += artist.popularity/ArtistAnalytics.numDataPoints for artist in self.mediumTermList: mediumTermPop += artist.popularity/ArtistAnalytics.numDataPoints for artist in self.longTermList: longTermPop += artist.popularity/ArtistAnalytics.numDataPoints data = {'Short Term': shortTermPop, 'Medium Term': mediumTermPop, 'Long Term': longTermPop} names = list(data.keys()) values = list(data.values()) plt.bar(names, values) plt.title('Average Popularity of My Top Artists Over Different Time Ranges') plt.ylabel('Spotify Popularity') plt.ylim(0,100) plt.show() def CreateGenreGroupedBarChart(self): # Should use dictionary shortTermGenres = {} mediumTermGenres = {} longTermGenres = {} for artist in self.shortTermList: for genre in artist.genres: if genre not in shortTermGenres: shortTermGenres[genre] = 1 else: shortTermGenres[genre] += 1 for artist in self.mediumTermList: for genre in artist.genres: if genre not in mediumTermGenres: mediumTermGenres[genre] = 1 else: mediumTermGenres[genre] += 1 for artist in self.longTermList: for genre in artist.genres: if genre not in longTermGenres: longTermGenres[genre] = 1 else: longTermGenres[genre] += 1 #print(shortTermGenres) #print(mediumTermGenres) #print(longTermGenres) width = 0.5 #indShort = np.arange(len(shortTermGenres)) #indMedium = np.arange(len(shortTermGenres)) #indLong = np.arange(len(shortTermGenres)) p1 = plt.bar(list(shortTermGenres.keys()), list(shortTermGenres.values()), width) p2 = plt.bar(list(mediumTermGenres.keys()), list(mediumTermGenres.values()), width) p3 = plt.bar(list(longTermGenres.keys()), list(longTermGenres.values()), width) plt.tight_layout(1) plt.xticks(rotation=90) plt.legend((p1, p2, p3), ('Short Term', 'Medium Term', 'Long Term')) plt.title('Genres Associated with My Top Artists Over Different Time Ranges') plt.xlabel('Genre') plt.show()
PHP
UTF-8
1,947
2.828125
3
[]
no_license
<?php include 'functions.php'; $pdo = pdo_connect_mysql(); if (isset($_GET['id'])) { $stmt = $pdo->prepare('SELECT * FROM polls WHERE id = ?'); $stmt->execute([$_GET['id']]); $poll = $stmt->fetch(PDO::FETCH_ASSOC); if ($poll) { $stmt = $pdo->prepare('SELECT * FROM poll_answers WHERE poll_id = ?'); $stmt->execute([$_GET['id']]); $poll_answers = $stmt->fetchAll(PDO::FETCH_ASSOC); if (isset($_POST['poll_answer'])) { $stmt = $pdo->prepare('UPDATE poll_answers SET votes = votes + 1 WHERE id = ?'); $stmt->execute([$_POST['poll_answer']]); header ('Location: result.php?id=' . $_GET['id']); exit; } } else { die ('Poll with that ID does not exist.'); } } else { die ('No poll ID specified.'); } ?> <head> <meta charset="utf-8"> <title>New Vote System App</title> <link href="newvotes.css" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css"> </head> <style> body { background-image:url("banner.webp"); background-repeat: no-repeat; background-size: 100% 100%; } html { height: 100% } </style> <div class="content poll-vote"> <h2><?=$poll['title']?></h2> <p><?=$poll['desc']?></p> <form action="vote.php?id=<?=$_GET['id']?>" method="post"> <?php for ($i = 0; $i < count($poll_answers); $i++): ?> <label> <input type="radio" name="poll_answer" value="<?=$poll_answers[$i]['id']?>"<?=$i == 0 ? ' checked' : ''?>> <?=$poll_answers[$i]['title']?> </label> <?php endfor; ?> <div> <input type="submit" value="Vote"> <a href="result.php?id=<?=$poll['id']?>">View Result</a> </div> </form> </div>