# parallella-cipher-demo
Demo application for encryption on Parallella using RAW-Feldspar and Zeldspar

## Instructions

### Preparation

    git clone git@github.com:emilaxelsson/imperative-edsl
    git clone git@github.com:emilaxelsson/raw-feldspar
    git clone git@github.com:koengit/zeldspar
    git clone git@github.com:kmate/raw-feldspar-mcs
    git clone git@github.com:kmate/parallella-cipher-demo
    cd parallella-cipher-demo
    cabal sandbox init
    cabal sandbox add-source ../imperative-edsl
    cabal sandbox add-source ../raw-feldspar
    cabal sandbox add-source ../zeldspar
    cabal sandbox add-source ../raw-feldspar-mcs
    cabal install --constraint="language-c-quote -full-haskell-antiquotes"

### Usage

To build, use

    ./make.sh

or on a Parallella:

    ./make_epiphany.sh

Encrypt a file (in-place):

    cp input-file.dat encrypted.dat
    ./run.sh this-is-my-key encrypted.dat

The encrypted file could be restored like this:

    openssl bf-ecb -d -nosalt -nopad -k this-is-my-key -in encrypted.dat -out decrypted.dat

## Known issues

* Host-device communication and one-element buffers makes it slower than is should be.


package nba.com.wr3d_second.ViewHolder;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import nba.com.wr3d_second.Interface.ItemClickListener;
import nba.com.wr3d_second.R;

public class ModsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    public TextView modsName;
    public ImageView modsImage;
    ItemClickListener itemClickListener;

    public void setItemClickListener(ItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    public ModsViewHolder(View itemView) {
        super(itemView);

        modsImage = (ImageView)itemView.findViewById(R.id.mods_image);
        modsName = (TextView)itemView.findViewById(R.id.mods_name);

        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        itemClickListener.onClick(v,getAdapterPosition());    }
}


package com.yh.dao.impl;

import com.yh.dao.EmployeeDao;
import com.yh.entity.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class EmployeeDaoImpl implements EmployeeDao {
    @Autowired
    private JdbcTemplate template;
    @Override
    public List<Employee> getEmpls(){
        String sql ="select * from employee";
        List<Employee> query = template.query(sql, new BeanPropertyRowMapper<Employee>(Employee.class));
        return query;
    }

    @Override
    public void addEmployee(Employee employee) {
        String sql="insert into employee (last_name,email,gender,birth,department_id) values (?,?,?,?,?)";
        int update = template.update(sql, employee.getLastName(), employee.getEmail(), employee.getGender(), employee.getBirth(), employee.getDepartmentId());
    }
}


package com.example.home.myapplication;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class SplashActivity extends Activity {
	static SplashActivity singleton;

	public static SplashActivity getInstance() {
		return singleton;
	}
	protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			singleton = this;
			//notification 없애기
			NotificationManager mNotificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
			mNotificationManager.cancel(GcmIntentService.NOTIFICATION_ID);

			setContentView(R.layout.activity_splash);
			initialize();

		}

	private void initialize() {
		Handler handler = new Handler() {

			public void handleMessage(Message msg) {
				finish();

				Intent i = new Intent(getApplicationContext(), MainActivity.class);
			    startActivity(i);
				overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
			}
		};
		handler.sendEmptyMessageDelayed(0, 1000);
	}

}


package com.wtoe.jrtplib;

import java.io.IOException;
import java.net.ServerSocket;

public class RtpHandle {
    static {
        System.loadLibrary("rtp-handle");
    }

    /**
     * 生成一个可使用的udp端口（20000以上）
     *
     * @param port 传20000即可
     * @return
     */
    public static int getAvailablePort(int port) {
        try {
            ServerSocket socket = new ServerSocket(port);
            socket.close();
            return port;
        } catch (IOException e) {
            return getAvailablePort(port + 2);
        }
    }

    /**
     * 只发送数据，不做接收处理
     */
    public static native long initSendHandle(int localport, String desthost, int destport, RtpListener listener);

    /**
     * 接收数据，并转发
     */
    public static native long initReceiveAndSendHandle(String localhost, int localreceiveport, int localsendport, String desthost, int destport, RtpListener listener);

    /**
     * 发送数据
     */
    public static native boolean sendByte(long rtpHandler, byte[] src, int byteLength, boolean isSpsOrMarker, boolean isRtpData,long lastTime);

    /**
     * 销毁资源
     */
    public static native boolean finiHandle(long rtpHandler);

}


package com.concurrency.chapter3.control;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by ss on 2017/7/20.
 */
public class TimeLock implements Runnable {

    private static ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        try {
            if (lock.tryLock(5, TimeUnit.SECONDS)) {
                Thread.sleep(6000);
                System.out.println(Thread.currentThread().getId() + ":Finish work.");
            } else {
                System.out.println(Thread.currentThread().getId() + ":Failed to get lock.");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {

        Thread thread1 = new Thread(new TimeLock());
        Thread thread2 = new Thread(new TimeLock());

        thread1.start();
        thread2.start();
    }
}


package com.example.myapplication.constant;

/**
 * Description:
 * Detail:
 * Create Time: 2018/8/13
 *
 * @author LiuFangQiang
 * @version 1.0
 * @see ...
 * History:
 * @since Since
 */
public class MessageEvent {

    public int code;
    public String message;
    public String name;

    public MessageEvent(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public MessageEvent(int code, String message, String name) {
        this.code = code;
        this.message = message;
        this.name = name;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


https://github.com/kevinam99/Instagram-Like-Bot

Milestones for the bot:

1. Download all necessary drivers etc. for the GitHub 'like bot'.
2. Run the 'like bot' from GitHub, make sure it works and has no bugs. Runs fine, why does it stop after 1 like? FIXED.
3. Test that feeding hashtags of one category to the 'like bot' creates a timeline of associated posts. Does changing the hashtag change the timeline?
4. If step 2 is true, alter code to create a 'save bot', where posts of a certain hashtag are saved not liked.
5. Again, test that the 'save bot' affects the timeline.
6. Next, find a BIG list of hashtags, and write a script that will randomly select a hashtag from that list. Perhaps use the categories that Instagram/fb/google have for interests as the hashtags themselves (e.g. #fitness). https://voymedia.com/facebook-interests-list/
7. Add this to the 'save bot', which should now be a randomised privacy bot.
8. Confirm that the bot does no more saving than Instagram's hourly limit (probably same as the hourly limit for liking).


package com.epam.igor.entity;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import java.io.Serializable;
import java.util.Locale;

@ManagedBean(name = "language")
@SessionScoped
public class LanguageBean implements Serializable {

    private static final long serialVersionUID = -6831921342246196194L;

    private Locale locale;

    /**
     * Method initializes session's locale
     */
    @PostConstruct
    public void init() {
        locale = FacesContext.getCurrentInstance().getExternalContext().getRequestLocale();
    }

    /**
     * @return present locale
     */
    public Locale getLocale() {
        return locale;
    }

    /**
     * @return present language name
     */
    public String getLanguage() {
        return locale.getLanguage();
    }

    /**
     * Method changes present language on another
     *
     * @param language on changing
     */
    public void setLanguage(String language) {
        locale = new Locale(language);
        FacesContext.getCurrentInstance().getViewRoot().setLocale(locale);
    }
}


package com.example.runner;

import com.example.externalproperties.PropertiesDemo;
import com.example.utils.ExternalPropertiesRefresh;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 *
index

 * Created by hanqf on 2020/4/16 22:36.
 */

@RestController
public class IndexController {
    @Autowired
    private ExternalPropertiesRefresh externalPropertiesRefresh;

    @Autowired
    private PropertiesDemo propertiesDemo;

    @RequestMapping("/")
    public String index() {
        return "hello world";
    }

    @RequestMapping("/refresh")
    public String refreshpro() {
        externalPropertiesRefresh.refresh();
        return "refresh properties success";
    }

    @RequestMapping("/{beanName}/refresh")
    public String refreshProByBeanName(@PathVariable String beanName) {
        externalPropertiesRefresh.refresh(beanName);
        return "refresh properties success for " + beanName;
    }

    @RequestMapping("/demo")
    public PropertiesDemo demo() {
        return propertiesDemo;
    }

}


package org.jocean.restfuldemo.ctrl;

import org.jocean.aliyun.oss.OssException;
import org.jocean.idiom.ExceptionUtils;
import org.jocean.svr.annotation.HandleError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import io.netty.handler.codec.http.HttpRequest;

@Component
public class ErrorHandler {
    private static final Logger LOG = LoggerFactory.getLogger(ErrorHandler.class);

    @HandleError(OssException.class)
    String handleOssException(final HttpRequest req, final OssException osserror) {
        LOG.warn("handle oss error when {}, detail: {}", req.uri(), osserror.error());
        return "handle oss error when " + req.uri() + "{\n" + osserror.error().toString() + "\n}";
    }

    @HandleError(Exception.class)
    String handleException(final HttpRequest req, final Exception error) {
        LOG.warn("error when {}, detail: {}", req.uri(), ExceptionUtils.exception2detail(error));
        return "error when " + req.uri() + "{\n" + ExceptionUtils.exception2detail(error) + "\n}";
    }
}


package p2p.repository;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class DataSource {

    private static HikariConfig config = new HikariConfig();
    private static HikariDataSource ds;

    static {
        config.setJdbcUrl("jdbc:h2:~/test;DB_CLOSE_DELAY=-1;MULTI_THREADED=1;");
        config.setUsername("sa");
        config.setPassword("");
        config.setMinimumIdle(25);
        config.setMaximumPoolSize(25);
        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        ds = new HikariDataSource(config);
    }

    private DataSource() {}

    public static Connection getConnection() {
        try {
            return ds.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}


package co.uk.cbaker.eu.game.ai.soldier;

import co.uk.cbaker.eu.game.entity.EntityManager;
import co.uk.cbaker.eu.game.state.State;
import co.uk.cbaker.eu.game.state.StateMachine;

/**
 * Singleton AIState implementation
 *
 * @author Chris B
 */
public class DeadState implements State {

	/** The AIState instance */
	private static State instance;

	/** Private constructor can't be called from outside the class */
	private DeadState() {}

	/**
	 * Returns the singleton AIState instance
	 * @return the singleton AIState instance
	 */
	public static State getInsatnce() {
		if(instance == null) {
			instance = new DeadState();
		}
		return instance;
	}

	@Override
	public void Enter(EntityManager em, int entity, StateMachine machine) {
		// do something when state is entered
		System.out.println("Dead.");
	}

	@Override
	public void Execute(EntityManager em, int entity, StateMachine machine) {

	}

	@Override
	public void Exit(EntityManager em, int entity, StateMachine machine) {
	}

}


package com.sap.fsm.knowledgebase.domain.model;

import org.hibernate.validator.constraints.Length;

import lombok.Data;

import javax.persistence.*;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

import java.util.Date;

@Entity
@Table(name = "knowledgebaseprovidertype")
@Valid
@Data
public class ProviderType {
    @Id
    @NotBlank
    @Column(name = "code", nullable = false, updatable = false,  unique = true)
    @Length(max = 512)
    private String code;

    @NotNull
    @Column(name = "lastchanged")
    @Temporal(TemporalType.TIMESTAMP)
    @Version
    private Date lastChanged;

    @Column
    @Length(max = 512)
    private String name;

/*     @OneToOne(mappedBy = "providerType", fetch = FetchType.LAZY)
    private KnowledgeBaseProviderConfiguration providerConfiguration; */

    @PrePersist
    @PreUpdate
    private void beforeUpdate() {
        this.lastChanged = this.lastChanged ==  null? new Date(): this.lastChanged;
    }
}


package id.kopipintar.pos.model;

public class Paket {
    private String nama;
    private int harga;
    private int diskon;
    private int quantity;
    private String[] items;

    public Paket(String nama, int harga, int diskon, int quantity, String[] items) {
        this.nama = nama;
        this.harga = harga;
        this.diskon = diskon;
        this.quantity = quantity;
        this.items = items;
    }

    public String getNama() {
        return nama;
    }

    public void setNama(String nama) {
        this.nama = nama;
    }

    public int getHarga() {
        return harga;
    }

    public void setHarga(int harga) {
        this.harga = harga;
    }

    public int getDiskon() {
        return diskon;
    }

    public void setDiskon(int diskon) {
        this.diskon = diskon;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public String[] getItems() {
        return items;
    }

    public void setItems(String[] items) {
        this.items = items;
    }
}


package com.luwei.models.checkIn;

import lombok.Data;

import javax.persistence.*;
import java.util.Date;

/**
 * @program: topshow
 * @description: 每日签到
 * @author: ZhangHongJie
 * @create: 2018-12-04 14:18
 **/
@Data
@Entity
public class CheckIn{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer checkInId;

    @Column(columnDefinition = "int(11) not null default 0 comment '用户id'")
    private Integer userId;

    @Column(columnDefinition = "int(11) not null default 0 comment '签到赠送积分'")
    private Integer giveIntegral;

    @Column(columnDefinition = "int(11) not null default 0 comment '连续签到天数'")
    private Integer checkInDate;

    @Column(columnDefinition = "int(11) not null default 0 comment '签到时间'")
    private Integer checkInTime;

    public CheckIn() {
    }

    public CheckIn(Integer userId, Integer giveIntegral, Integer checkInDate, Integer checkInTime) {
        this.userId = userId;
        this.giveIntegral = giveIntegral;
        this.checkInDate = checkInDate;
        this.checkInTime = checkInTime;
    }
}


package com.drivease.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.drivease.model.UserFeedback;

import com.drivease.service.UserFeedbackService;

@Controller
@RequestMapping("/feedback")
public class FeedbackController {

	@Autowired
	UserFeedbackService userfeedbackservice;

	@RequestMapping("/sendfeedback")
	public String sendfeedback(Model model)
	{

		UserFeedback feedback=new UserFeedback();
		model.addAttribute("feedback", feedback);
		model.addAttribute("edit",false);
		return "usercontactus";
	}
	@RequestMapping("/savefeedback")
	public String saveFeedback(@ModelAttribute("feedback") UserFeedback feedback)
	{

		userfeedbackservice.addFeedback(feedback);
		return "redirect:/feedback/sendfeedback";
	}

}


package jp.abekoh.log.sink.converter.mapstruct;

import java.net.MalformedURLException;
import java.net.URL;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MapStructConverterUtil {

    private static final Pattern urlPattern = Pattern.compile("(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]");

    @SourceTextToUrl
    public URL sourceTextToUrl(String sourceText) {
        Matcher matcher = urlPattern.matcher(sourceText);
        if (matcher.find()) {
            try {
                return new URL(matcher.group(0));
            } catch (MalformedURLException e) {
                return null;
            }
        }
        return null;
    }

    @TimestampMsToPostedTime
    public ZonedDateTime timestampMsToPostedTime(String timestampMs) {
        return ZonedDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(timestampMs)), TimeZone.getTimeZone("UTC").toZoneId());
    }
}


package com.ibm.gers.regeditor.editors;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.jface.text.rules.FastPartitioner;
import org.eclipse.ui.editors.text.TextFileDocumentProvider;

public class XMLTextDocumentProvider extends TextFileDocumentProvider {

	protected FileInfo createFileInfo(Object element) throws CoreException {
        FileInfo info = super.createFileInfo(element);
        if(info==null){
                info = createEmptyFileInfo();
        }
        IDocument document = info.fTextFileBuffer.getDocument();
        if (document != null) {
        	IDocumentPartitioner partitioner =
				new FastPartitioner(
					new XMLPartitionScanner(),
					new String[] {
						XMLPartitionScanner.XML_TAG,
						XMLPartitionScanner.XML_COMMENT });
			partitioner.connect(document);
			document.setDocumentPartitioner(partitioner);
        }
        return info;
    }
}


package com.example.pricesexercise.integration;

import com.example.pricesexercise.core.infrastructure.repository.InH2Prices;
import com.example.pricesexercise.core.infrastructure.repository.PricesRepository;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.test.context.ActiveProfiles;

import javax.sql.DataSource;

@Configuration
@ComponentScan({"com.example.pricesexercise.core", "com.example.pricesexercise.delivery.controller"})
@ActiveProfiles("test")
public class TestApplicationConfig {

    @Bean
    public PricesRepository pricesRepository(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("org.h2.Driver");
        dataSource.setUrl("jdbc:h2:file:./data/prod");
        dataSource.setUsername("user");
        dataSource.setPassword("1234");
        return new InH2Prices(dataSource);
    }
}


package com.song.server.handler;

import com.song.util.LoginUtil;
import com.song.util.PacketType;
import com.song.vo.LoginResponsePacket;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * Created by Song on 2019/09/24.
 */
public class AuthHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (LoginUtil.isLogin(ctx.channel())) {
            ctx.pipeline().remove(this);
            super.channelRead(ctx, msg);
        } else {
            LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
            loginResponsePacket.setPacketType(PacketType.login_response);
            loginResponsePacket.setIsSuccess(false);
            loginResponsePacket.setReason("重新的登录");
            ctx.channel().writeAndFlush(loginResponsePacket);

            ctx.channel().close();
        }
    }
}


# Help Me Decide (powered by Yelp!)

*Help Me Decide is a web application that, using predefined categories and user selections, helps a user decide what to do or what to eat using the Yelp Fusion API*

### Have you ever been hungry and not known what to eat, or been bored and not known what to do?

## Help Me Decide is your solution.

![Image of Help Me Decide](/img/helpmedecide.png)

### Step 1: Pick a category.

Choose between Food, Active Life, Night Life, and Entertainment.

### Step 2: Choose options that sound good.

Select one or select all! (Although you should probably select more than one...)

### Step 3: Let the program help you decide!

Click the button. Simple as that.

![Image of Chosen Result](/img/helpmedecide2.png)

Once you're happy with the choice, enter a location near you to get the top 5 local businesses for that category.
You can enter an address, neighborhood, city/state, or zip code.

![Image of Local Businesses](/img/helpmedecide3.png)

If you would like to learn more about a business, simply click the name and you will be redirected to that business's official Yelp page.


package ru.downwine._27_TwentyseventhLab.Ex3;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.Timer;

public class SnakeController implements KeyListener, ActionListener {
    private final SnakeView snakeView;
    private final Timer timer;
    private final Snake snake;

    public SnakeController() {
        snake = new Snake();
        snakeView = new SnakeView(this);
        this.snakeView.addKeyListener(this);
        this.timer = new Timer(200, this);
        startGame();
    }

    public void stopGame() {
        timer.stop();
    }

    public void startGame() {
        timer.start();
    }

    public void keyPressed(KeyEvent e) {
        snake.onMove(e.getKeyCode());
    }

    public void keyReleased(KeyEvent e) {
    }

    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void actionPerformed(ActionEvent arg) {
        snakeView.moveForward();
    }

    public Snake getSnake() {
        return snake;
    }
}


import java.io.*;
public class WordNet {
   public WordNet(String synsets, String hypernyms) throws IOException{
      parseSynset(synsets);
      parseHypernyms(hypernyms);

   }
   private void parseSynset(String synsets) throws IOException{
      FileReader fr1 =  new FileReader(synsets + ".txt");
      BufferedReader br = new BufferedReader(fr1);
      String i;
     while ((i=br.readLine()) != null) {
         String arr1[] =i.split(",");
         System.out.println(arr1[0]);
      }
   }

   private void parseHypernyms(String hypernyms) throws IOException{
      FileReader fr2 =  new FileReader( hypernyms + ".txt");
      BufferedReader br = new BufferedReader(fr2);
      String j;
     while ((j=br.readLine()) != null) {
         String arr2[] =j.split(",");
         System.out.println(arr2);
      }
   }
   public static void main(String[] args) throws IOException{
      WordNet Obj = new WordNet("synsets", "hypernyms");

     }

}


This project uses the popular NASA Astronomy Picture of the Day open API to produce wonderful images with details and lengthy descriptions which the users can scroll through and save to the favorites collection.

Built with vanilla JavaScript, HTML and pure CSS.

Functionality:

🚀 the app displays random Astronomy Pictures formated into cards with an image, title, "add to favorites" star button, description, date and copyright information

🚀 the app displays 10 new images after every loading

🚀 images are lazy-loaded to improve performance - the app will load the image only when it comes close to being scrolled to

🚀 clicking on an image opens the full resolution of that image in a separate tab

🚀 the user can add and remove images to and from the "favorites page," which stores images using local storage

🚀 the app is mobile responsive

The app uses responsive design to be both mobile and desktop friendly.

HTTP Request

GET https://api.nasa.gov/planetary/apod

from:

https://api.nasa.gov/

Live demo:

https://nasa-apod-application.netlify.app/


package com.great.bean;

import java.io.Serializable;

public class Role implements Serializable {

	/**修改
	 * 角色实体对象 @linanp
	 */
	private static final long serialVersionUID = 1L;

	private int roleId;
	private String roleName;
	private int roleState;
	private String roleCdate;

	public Role() {
		super();
	}
	public Role(int roleId, String roleName, int roleState, String roleCdate) {
		super();
		this.roleId = roleId;
		this.roleName = roleName;
		this.roleState = roleState;
		this.roleCdate = roleCdate;
	}
	public int getRoleId() {
		return roleId;
	}
	public void setRoleId(int roleId) {
		this.roleId = roleId;
	}
	public String getRoleName() {
		return roleName;
	}
	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}
	public int getRoleState() {
		return roleState;
	}
	public void setRoleState(int roleState) {
		this.roleState = roleState;
	}
	public String getRoleCdate() {
		return roleCdate;
	}
	public void setRoleCdate(String roleCdate) {
		this.roleCdate = roleCdate;
	}
	public static long getSerialversionuid() {
		return serialVersionUID;
	}

}


#  Setting Up for Development

* install dependencies (Debian/Ubuntu)

        $ sudo apt-get update
        $ sudo apt-get install -y gcc python3-dev python3-venv

* prepare directory for project code and virtualenv:

        $ mkdir -p ~/webapps
        $ cd ~/webapps

* download the project code:

        $ git clone https://github.com/Kenan7/bakujobs.git
* go in to the project dir:

        $ cd bakujobs

* prepare virtual environment
  (with virtualenv you get pip, we'll use it soon to install requirements):

        $ python3 -m venv env
        $ source env/bin/activate

* install requirements (Django, ...) into virtualenv:

        $ pip install -r requirements.txt

* Make migrations:

        $ (env) python manage.py makemigrations

* Build the database:

        $ (env) python manage.py migrate

* Create a superuser:

        $ (env) python manage.py createsuperuser

* Run the development server:

        $ (env) python manage.py runserver


package com.weitao.dao;

import com.weitao.bean.Manager;
import com.weitao.utils.MD5;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * @Author:Cc
 * @Date:2018/10/9
 * @program: weitao
 * @description: ${测试ManageMapper}
 * @create: 2018-10-09 15:18
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class ManageMapperTest {

    @Autowired
    private ManagerMapper managerMapper;

    @Test
    public void addManagerTest() throws Exception {
        Manager manager = new Manager();
        manager.setmPassword(MD5.md5("123456"));
        manager.setmAuthority((byte) 0);

        managerMapper.addManager(manager);
//        返回添加后的主键
        System.out.println(manager.getmId());
    }

    @Test
    public void name() throws Exception {
        Integer aa = 0;
        if(aa == 1){
            System.out.println("dui");
        }
        else System.out.println(".......");
    }
}


package com.Fb.Pages;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

import com.Utilie.Browser_Factory;

import net.bytebuddy.asm.Advice.This;

public class LoginPage extends Browser_Factory {

	WebDriver driver;

	public LoginPage() {

		PageFactory.initElements(driver, This.class);

	}

	@FindBy(id="u_0_m")
	static
	WebElement First_Name;

	@FindBy(className = "inputtext _58mg _5dba _2ph-")
	static
	WebElement Last_Name;

	@FindBy(xpath = "//input[@id='u_0_r']")
	static
	WebElement mail_ID;

	@FindBy(xpath = "//input[@id='u_0_w']")
	static
	WebElement password;

	public static void LOgIN_DEt() {

		First_Name.sendKeys(prop.getProperty("First_Name"));
		Last_Name.sendKeys(prop.getProperty("Last_name"));
		mail_ID.sendKeys(prop.getProperty("Mail"));
		password.sendKeys(prop.getProperty("Pwd"));

	}

}


package com.hyjf.admin.wkcd.wkcdborrow;

import java.io.Serializable;
import java.util.List;

import com.hyjf.common.paginator.Paginator;
import com.hyjf.mybatis.model.auto.WkcdBorrow;

public class WkcdBorrowBean extends WkcdBorrow implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private List<WkcdBorrow> recordList;

	/**
	 * 翻页机能用的隐藏变量
	 */
	private int paginatorPage = 1;

	/**
	 * 列表画面自定义标签上的用翻页对象：paginator
	 */
	private Paginator paginator;

	public int getPaginatorPage() {
		if (paginatorPage == 0) {
			paginatorPage = 1;
		}
		return paginatorPage;
	}

	public void setPaginatorPage(int paginatorPage) {
		this.paginatorPage = paginatorPage;
	}

	public Paginator getPaginator() {
		return paginator;
	}

	public void setPaginator(Paginator paginator) {
		this.paginator = paginator;
	}

	public List<WkcdBorrow> getRecordList() {
		return recordList;
	}

	public void setRecordList(List<WkcdBorrow> recordList) {
		this.recordList = recordList;
	}

}


import java.io.*;
import java.util.*;
import queryclass.Query;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Writeitem extends HttpServlet{
  protected void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException
  {
    int bitid = Integer.parseInt(request.getParameter("it"));
    HttpSession session = request.getSession();
    int uid = (Integer) session.getAttribute("uid");
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println(bitid+""+uid);
    try{
      Query Q  = new Query();
      Q.writeitem(uid,bitid);
    }
    catch(Exception ex){
      out.println(ex);
      ex.printStackTrace();
    }
    RequestDispatcher rd = request.getRequestDispatcher("DispitemU");
    rd.include(request,response);
    out.close();
  }
}


package com.questionnaire.entity.results;

import com.questionnaire.core.QuestionType;

import java.util.List;

/**
 * Created by Igor on 21.11.2016.
 */
public class Question {
    private String id;
    private String title;
    private QuestionType questionType;
    private List<Answer> answers;
    private List<String> openAnswers;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public List<Answer> getAnswers() {
        return answers;
    }

    public void setAnswers(List<Answer> answers) {
        this.answers = answers;
    }

    public QuestionType getQuestionType() {
        return questionType;
    }

    public void setQuestionType(QuestionType questionType) {
        this.questionType = questionType;
    }

    public Question() {

    }

    public List<String> getOpenAnswers() {
        return openAnswers;
    }

    public void setOpenAnswers(List<String> openAnswers) {
        this.openAnswers = openAnswers;
    }
}


package me.skiincraft.mal.entity.experimental.top;

import me.skiincraft.mal.MyAnimeList;

public enum TopType {

    Airing("Top Airing","?type=airing"),
    Upcoming("Top Upcoming","?type=upcoming"),
    TV_Series("Top TV Series","?type=tv"),
    Movies("Top Movies","?type=movie"),
    OVAs("Top OVAs","?type=ova"),
    ONAs("Top ONAs","?type=ona"),
    Special("Top Specials","?type=special"),
    Most_Popular("Most Popular","?type=bypopularity"),
    Most_Favorited("Most Favorited","?type=favorite");

    private static final String TOP_URL = MyAnimeList.SITE_URL + "topanime.php";
    private final String name;
    private final String endpoint;

    TopType(String name, String endpoint) {
        this.name = name;
        this.endpoint = endpoint;
    }

    public String getEndpoint() {
        return endpoint;
    }

    public String getURL() {
        return TOP_URL + endpoint;
    }

    public String getName() {
        return name;
    }
}


package com.example.demo;

import io.swagger.annotations.Api;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * AOP方法级
 *
 * @author huxu
 * @create 2017-08-05 16:14
 **/

@Aspect // FOR AOP
@Order(-99) // 控制多个Aspect的执行顺序，越小越先执行
@Component
public class TestAspect {

    private Logger LOG = LoggerFactory.getLogger(this.getClass());

    @Before("@annotation(test)")// 拦截被TestAnnotation注解的方法；如果你需要拦截指定package指定规则名称的方法，可以使用表达式execution(...)
    public void beforeTest(JoinPoint point, TestAnnotation test) throws Throwable {
        LOG.info("beforeTest:{}",test.name());
    }

    @After("@annotation(test)")
    public void afterTest(JoinPoint point, TestAnnotation test) {
        LOG.info("afterTest:{}",test.name());
    }

}


---
title: Using a template
sidebar_label: Using a template
---

We are going to download `smash-template-react` and run the `dev-server` task on it.

> Make sure you have installed `smash-cli`.

## Download it first

```bash
$ mkdir demo && cd demo
$ smash download smash-template-react
```

Don't forget to install its own dependencies.

```bash
$ npm i
```

## How to use?

### Read the `.smash/task.yml`

Here is what `.smash/task.yml` looks like:

```yaml
# Start webpack-dev-server
dev-server:
  - name: smash-middleware-webpack-v4
    type: dev-server
```

We can find a task named `dev-server`. And a middleware named `smash-middleware-webpack-v4` was used in it.

### Install middleware

Run the command below to install the middleware.

```bash
$ smash install
```

### Run a task

Now, run the `dev-server` task:

```bash
$ smash run dev-server
```

It starts the webpack-dev-server. A few minutes later, you will see a page opened in your browser.

OK! You finished it.


package jmnet.moka.common.template.merge;

import java.util.ArrayList;
import java.util.List;
import jmnet.moka.common.template.parse.model.TemplateElement;

/**
 *
 * <pre>
 * 템플릿 관계 tree를 생성하기 위한 Tree Node 표현
 * 2019. 9. 4. kspark 최초생성
 * </pre>
 * @since 2019. 9. 4. 오후 6:04:45
 * @author kspark
 */
public class TreeNode {
	private TemplateElement templateElement;
	private TreeNode parentNode;
	private List<TreeNode> children;

	public TreeNode(TemplateElement templateElement) {
		this.templateElement = templateElement;
	}

	public TreeNode(TreeNode parentNode, TemplateElement templateElement) {
		this.parentNode = parentNode;
		this.templateElement = templateElement;
	}

	public void addChild(TreeNode childNode) {
		if ( children == null) {
			children = new ArrayList<TreeNode>();
		}
		children.add(childNode);
	}

	public TemplateElement getTemplateElement() {
		return templateElement;
	}

	public boolean hasParent() {
		return parentNode != null;
	}

	public TreeNode getParent() {
		return parentNode;
	}

	public List<TreeNode> getChildren() {
		return children;
	}

	public boolean hasChild() {
		return this.children != null;
	}

}


package cn.cookily.msg.util;

import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;

/**
 * Created by cookily on 2017/5/8.
 */
public class SendMsg {
    public void sendMsg() throws ApiException {
        String serverUrl="http://gw.api.taobao.com/router/rest";
        String appKey="后台可以查看appKey";
        String appSecret="后台可以查看appSecret";

        TaobaoClient client=new DefaultTaobaoClient(serverUrl, appKey, appSecret);
        AlibabaAliqinFcSmsNumSendRequest req=new AlibabaAliqinFcSmsNumSendRequest();
        //req.setExtend("12345回传");//待测 可选
        req.setSmsType("normal");//短信类型 必须
        req.setSmsFreeSignName("短信签名");// 必须
        req.setSmsParamString("{\"userName\":\"通知的消息名\",\"code\":\"验证码\"}");//json格式的短信模板的变量，多个变量括号隔开 可选
        req.setRecNum("接收的手机号码");//接收的手机号码 必须
        req.setSmsTemplateCode("短信模板id");//短信模板id 必须

        AlibabaAliqinFcSmsNumSendResponse rsp= client.execute(req);
        System.out.println(rsp.getBody());
    }
}


package com.project.fabulous.api;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiBuilder {
    private static Api api;
    public static Api getInstance(){
        Gson gson = new GsonBuilder().setLenient().create();

        if (api == null){
//            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
//            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//            OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

            api = new Retrofit.Builder()
                    .baseUrl("https://us-central1-fabulous-journey.cloudfunctions.net/api/")
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build()
                    .create(Api.class);
        }
        return api;
    }
}


import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class MultipleWindows {

	public static void main(String[] args) {

		System.setProperty("webdriver.chrome.driver",
				"C:\\Users\\devendra.swarnkar\\Desktop\\Selenium WebDriver with Java\\chromedriver.exe");
		WebDriver driver = new ChromeDriver();
		driver.get("http://the-internet.herokuapp.com/");

		driver.findElement(By.xpath("//a[@href='/windows']")).click();

		driver.findElement(By.xpath("//a[@href='/windows/new']")).click();
		Set<String> ids = driver.getWindowHandles();

		Iterator<String> id = ids.iterator();

		String partntId = id.next();
		String childId = id.next();

		driver.switchTo().window(childId);

		System.out.println(driver.findElement(By.xpath("//div[@class='example']/h3")).getText());

		driver.switchTo().window(partntId);

		System.out.println(driver.findElement(By.xpath("//div[@class='example']/h3")).getText());
	}

}


package com.kardidev.poc.cloud.probes.consumer.service.load;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class LoadService {

    private final RestTemplate restTemplate;

    public LoadService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * Call a frontservice REST point to add a task with a given weight
     *
     * @param podIP  target pod IP
     * @param weight a weight it's supposed to be load with in milliseconds
     */
    public void load(String podIP, int weight) {

        String url = String.format("http://%s:8080/frontservice/process?weight=%d", podIP, weight);

        ResponseEntity<Object> responseEntity = restTemplate.getForEntity(url, Object.class);

        if (responseEntity.getStatusCode() != HttpStatus.ACCEPTED)
            throw new RuntimeException("Unexpected response from frontend service");
    }

}


package org.didinem;

import org.I0Itec.zkclient.ZkClient;
import org.apache.commons.lang3.StringUtils;
import org.didinem.sprops.DubboProperties;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by zhongzhengmin on 2017/3/10.
 */
public class ZkTest {

    @Autowired
    private DubboProperties dubboProperties;

    @Autowired
    private ZkClient zkClient;

    public void test1() {
        String internalClassName = "com/lvmama/vst/api/biz/service/VstDistrictService";
        String interfaceName = internalClassName.replaceAll("/", "\\.");
        String providerPath = dubboProperties.getSeperator() + StringUtils.joinWith(dubboProperties.getSeperator(), dubboProperties.getRoot(), interfaceName, dubboProperties.getProvider());
        List<String> providerUrlList = zkClient.getChildren(providerPath);
        for (String string : providerUrlList) {
            System.out.println(string);
        }
    }

}


package com.sharpnode.adapter;

import android.content.Context;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import com.sharpnode.DeviceDashboardFragment;

/**
 * Created by admin on 12/8/2016.
 */
public class DeviceDashboardPagerAdaper extends FragmentPagerAdapter {

    private Context _context;
    public static int totalPage = 1;
    public DeviceDashboardPagerAdaper(Context context, FragmentManager fm) {
        super(fm);
        _context = context;
    }
    @Override
    public DeviceDashboardFragment getItem(int position) {
        DeviceDashboardFragment f = new DeviceDashboardFragment();
        switch (position) {
            case 0:
                f = new DeviceDashboardFragment();
                break;
            /*case 1:
                f = new DeviceDashboardFragment();
                break;*/
        }
        return f;
    }
    @Override
    public int getCount() {
        return totalPage;
    }
}


package com.fang.seckill.queue;

import com.fang.seckill.BaseTests;
import com.fang.seckill.consumer.KafkaQueueConsumer;
import com.fang.seckill.entity.GoodsDO;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;

import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * Description：基于kafka的分布式队列
 *
 * @author fangliangsheng
 * @date 2018/12/19
 */
@Slf4j
public class KafkaQueueTests extends BaseTests {

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Test
    public void kafkaQueue() throws Exception{
        IntStream.range(0, 1000).parallel().forEach(i->{
            kafkaTemplate.send("seckill.queue", super.GOODS_ID.toString());
        });

        KafkaQueueConsumer.downLatch.await(2000, TimeUnit.MILLISECONDS);

        Optional<GoodsDO> goodsDO = goodsRepository.findById(GOODS_ID);

        log.info("[kafkaQueue]剩余数量 {}", goodsDO.get().getNumber());
        Assert.assertTrue(goodsDO.get().getNumber() == 0);
    }

}


package web;

import org.json.JSONObject;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Apathetic spawn of Wesb on 11/11/16.
 */
public class CourseConverter {

    public List<Course> convertResultSetToCourseList(ResultSet resultSet) {
        List<Course> courseList = new ArrayList<>();
        try {
            while(resultSet.next()){
                String code = resultSet.getString("Code");
                int number = resultSet.getInt("Number");
                String name = resultSet.getString("Name");
                String description = resultSet.getString("Description");
                int credits = resultSet.getInt("Credits");
                Course course = new Course(code, number, name, description, credits);
                courseList.add(course);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return courseList;
    }
}


package com.yfkey.webapp.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.internal.util.StringHelper;
import org.springframework.web.filter.OncePerRequestFilter;

import com.yfkey.Constants;

/**
 * Filter to wrap request with a request including user preferred locale.
 */
public class ThemeFilter extends OncePerRequestFilter {

	@SuppressWarnings("unchecked")
	public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		String theme = request.getParameter(Constants.BOOTSTRAP_THEME);

		if (StringHelper.isNotEmpty(theme)) {
			HttpSession session = request.getSession(false);

			if (session != null) {
				session.setAttribute(Constants.BOOTSTRAP_THEME, theme);
			}
		}

		chain.doFilter(request, response);
	}
}


package com.company.bean;

/**
 * @author Davi
 * @category 装潢件信息表
 */
public class Decorate {
	/**
	 * 商品编号
	 */
	private int spid;

	/**
	 * 装潢名称
	 */
	private String decoratename;
	/**
	 * 类型Id
	 */
	private int typeid;
	/**
	 * 装潢 编号
	 */
	private int id;

	public int getSpid() {
		return spid;
	}

	public void setSpid(int spid) {
		this.spid = spid;
	}

	public String getDecoratename() {
		return decoratename;
	}

	public void setDecoratename(String decoratename) {
		this.decoratename = decoratename;
	}

	public int getTypeid() {
		return typeid;
	}

	public void setTypeid(int typeid) {
		this.typeid = typeid;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public Decorate(int spid, String decoratename, int typeid, int id) {
		super();
		this.spid = spid;
		this.decoratename = decoratename;
		this.typeid = typeid;
		this.id = id;
	}

	public Decorate() {
		super();
	}

}


package com.bloodsport.whisper.feature.encrypt;

import com.bloodsport.whisper.core.annotation.ResultSkip;
import com.bloodsport.whisper.core.annotation.SecurityParameter;
import com.bloodsport.whisper.model.pojo.PublicKeyDTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 *
@ProjectName:     WhisperServer

 *
@ClassName:       EncryptionController

 *
@PackageName:     com.bloodsport.whisper.feature.encrypt

 *
 *
@Description:     加密解密功能控制器

 *
 *
@author:          lumo

 *
@date:            2019/12/16

 *
@email:           cnrivkaer@outlook.com

 */
@RestController
@RequestMapping(value = "/encrypt")
public class EncryptionController {

    @Value("${encryption.publicKey}")
    String publicKey;

    @SecurityParameter
    @ResultSkip
    @GetMapping(value = "/fetchPublicKey")
    public PublicKeyDTO fetchPublicKey(){
        return new PublicKeyDTO(publicKey.replaceAll("\\\\", ""));
    }
}


package com.lea.servlet.expand.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lzc
 * @create 2020/09/23 下午 2:34
 */
@WebServlet("/listener/contextAttribute")
public class AttributeListenerServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = req.getServletContext();
        // 添加数据
        context.setAttribute("liam", "get chicken");
        // 更新数据
        context.setAttribute("liam", "get much beef");
        // 添加一条新数据
        context.setAttribute("qiqi", "how are you?");
        // 删除数据
        context.removeAttribute("liam"); // 刚开始时，liam写错了，所有没有删除成功，就没有触发删除监听器方法
    }
}


package com.intelliq.appengine.api;

import com.intelliq.appengine.datastore.entries.PermissionEntry;

import java.util.ArrayList;
import java.util.List;

public class PermissionSet {

    public static final byte REQUIRE_ANY = 0;
    public static final byte REQUIRE_ALL = 1;

    private List<PermissionEntry> permissions;
    private byte mode;

    public PermissionSet() {
        super();
        this.permissions = new ArrayList<PermissionEntry>();
        this.mode = REQUIRE_ANY;
    }

    public PermissionSet(List<PermissionEntry> permissions, byte mode) {
        super();
        this.permissions = permissions;
        this.mode = mode;
    }

    public List<PermissionEntry> getPermissions() {
        return permissions;
    }

    public void setPermissions(List<PermissionEntry> permissions) {
        this.permissions = permissions;
    }

    public byte getMode() {
        return mode;
    }

    public void setMode(byte mode) {
        this.mode = mode;
    }
}


package com.stepomy.core.consumer;

import com.stepomy.core.Configuration;
import com.stepomy.core.QueueItem;

import java.util.Timer;
import java.util.concurrent.*;
import java.util.stream.IntStream;

public class Consumer {
    private LinkedBlockingQueue<QueueItem> queue = new LinkedBlockingQueue<>(Configuration.CONSUMER_WORKERS);
    private Timer messageScheduler;
    private ExecutorService executorService;

    public void processMessage() {
        System.out.println("Consumer:processMessage");
        startMessageScheduler();
        startMessageProcess();

    }

    void startMessageScheduler() {
        messageScheduler = new Timer();
        messageScheduler.schedule(new MessageFetch(queue), 0, Configuration.CONSUMER_POOLING_TIME);
    }

    void startMessageProcess() {
        executorService = Executors.newFixedThreadPool(Configuration.CONSUMER_WORKERS);
        IntStream
                .range(0, Configuration.CONSUMER_WORKERS)
                .forEach( it -> executorService.submit(new MessageProcess(queue)));
    }

}


package com.wiatec.bplay.utils.OkHttp.Request;

import java.util.Map;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.Request;

/**
 * Created by patrick on 2016/12/23.
 */

public class PostRequest extends RequestMaster {

    private String url;

    public PostRequest (String  url){
        this.url = url;
    }

    @Override
    protected Request createRequest(Header header, Parameters parameters ,Object tag) {
        Request.Builder builder = new Request.Builder();
        if(header != null){
            Headers headers = Headers.of(header.stringMap);
            builder.headers(headers);
        }
        if(parameters != null){
            FormBody.Builder builder1 = new FormBody.Builder();
            for (Map.Entry<String ,String > entry : parameters.stringMap.entrySet()){
                builder1.add(entry.getKey() ,entry.getValue());
            }
            builder.post(builder1.build());
        }
        if(tag != null){
            builder.tag(tag);
        }
        builder.url(url);
        return builder.build();
    }
}


package com.dev.aurora.utils;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public abstract class LazyFragment extends Fragment {

    private Context context;
    private boolean isFirstLoad = true;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = requireActivity();
    }

    protected abstract int getContentViewId();

    protected abstract void initData();

    protected abstract void initEvent();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return LayoutInflater.from(context).inflate(getContentViewId(), null);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isFirstLoad) {
            initData();
            initEvent();
            isFirstLoad = false;
        }
    }
}


package com.mobile.aquafish;

import android.content.Context;

import static android.content.Context.MODE_PRIVATE;

public class SharedPreferences {

    private static final String AQUAFISH_APP = "aquafishApp";
    static final String AQUA_CODE = "aquaCode";
    static final String AQUA_NAME = "nameUser";

    private android.content.SharedPreferences preferences;
    private android.content.SharedPreferences.Editor editor;

    public SharedPreferences(Context context) {
        preferences = context.getSharedPreferences(AQUAFISH_APP, MODE_PRIVATE);
        editor = preferences.edit();
        editor.apply();
    }

    public void deleteValue() {
        editor.clear();
        editor.commit();
    }

    public void saveStringCode(String key, String value) {
        editor.putString(key, value);
        editor.commit();
    }

    public void saveStringName(String key, String value) {
        editor.putString(key, value);
        editor.commit();
    }

    public String getAquaCode() {
        return preferences.getString(AQUA_CODE, "");
    }

    public String getAquaName() {
        return preferences.getString(AQUA_NAME, "");
    }
}


package pdp.access;

import org.junit.Test;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import static org.junit.Assert.assertEquals;

public class BasicAuthenticationManagerTest {

    private BasicAuthenticationProvider manager = new BasicAuthenticationProvider("user", "password");

    @Test
    public void testAuthenticateHappyFlow() throws Exception {
        Authentication authenticate = manager.authenticate(new TestingAuthenticationToken("user", "password"));
        assertEquals("[ROLE_USER, ROLE_PEP]", authenticate.getAuthorities().toString());
    }

    @Test(expected = UsernameNotFoundException.class)
    public void testAuthenticateUsername() throws Exception {
        manager.authenticate(new TestingAuthenticationToken("unknown", "password"));
    }

    @Test(expected = BadCredentialsException.class)
    public void testAuthenticateBadCredentials() throws Exception {
        manager.authenticate(new TestingAuthenticationToken("user", "faulty"));
    }
}


package com.bl.springboot.controller;

import com.bl.springboot.model.Product;
import com.bl.springboot.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class ProductController {

    @Autowired
    private ProductService service;

    @GetMapping("/products")
    public List<Product> list(){
        return service.listAll();
    }

    @GetMapping("/products/{id}")
    public Product get(@PathVariable Integer id){
        return service.get(id);
    }

    @PostMapping("/products")
    public void add(@RequestBody Product product){
        service.save(product);
    }

    @PutMapping("/products/{id}")
    public void update(@RequestBody Product product, @PathVariable Integer id){
        Product existProduct = service.get(id);
        service.save(product);
    }

    @DeleteMapping("/products/{id}")
    public void delete(@PathVariable Integer id){
        service.delete(id);
    }
}


package cn.linkmore.ops.biz.controller;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.linkmore.bean.view.ViewPage;
import cn.linkmore.bean.view.ViewPageable;
import cn.linkmore.ops.biz.service.ReceiveService;
/**
 * 领券记录
 * @author   GFF
 * @Date     2018年5月30日
 * @Version  v2.0
 */
@Controller
@RequestMapping("/admin/biz_receive")
public class ReceiveController {

	@Resource
	private ReceiveService receiveService;

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public ViewPage list(HttpServletRequest request, ViewPageable pageable) {
		return receiveService.findPage(pageable);
	}

	@RequestMapping(value = "/detailList", method = RequestMethod.POST)
	@ResponseBody
	public ViewPage detailList(HttpServletRequest request, ViewPageable pageable) {
		return receiveService.findDetailPage(pageable);
	}
}


package com.parkinglot.design.ProblemSolving;

public class InvertBinaryTree {
    static boolean isSymmetric(Node root)
    {
        return true;
    }
    public static void inorderTraversal(Node root)
    {
        if(root == null)
            return;
        inorderTraversal(root.left);
        System.out.print(root.key+" ");
        inorderTraversal(root.right);

    }
    public static void main(String args[])
    {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(2);
        tree.root.left.left = new Node(3);
        tree.root.left.right = new Node(4);
        tree.root.right.left = new Node(4);
        tree.root.right.right = new Node(3);
        boolean output = isSymmetric(tree.root);
        if (output == true)
            System.out.println("Symmetric");
        else
            System.out.println("Not symmetric");
        inorderTraversal(tree.root);
    }
}


package concurrency.motivation;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * @author Created by tom on 03.06.2017.
 */
@WebMvcTest(controllers = {Example3_AppleShop.class})
@RunWith(SpringRunner.class)
public class Example3_AppleShopTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void buyingApples() throws Exception {
        mvc.perform(post("/appleShop/grannySmith"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", is("gs_1")));
    }

}


package com.dongchen.keydemo;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;

/**
 *
 *
 * @author dongchen
 * created at 2018/5/25 17:37
 *
 * 功能：
 * 目的：
 */
public abstract class BaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ActionBar ab = getSupportActionBar();
        if (null != ab) {
            ab.setDisplayHomeAsUpEnabled(true);
        }
        Log.i("class", "activity is " + this.getClass().getName());
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                break;
            default:
        }

        return super.onOptionsItemSelected(item);
    }
}


package com.mcelrea.firstservertry;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;

public class Player {
    private float x;
    private float y;
    private Color color;
    private float prevX;
    private float prevY;

    public Player(Color color) {
        this.color = color;
        x = 300;
        y = 300;
        prevX = x;
        prevY = y;
    }

    public boolean hasMoved() {
        if(prevX != x || prevY != y) {
            prevX = x;
            prevY = y;
            return true;
        }
        return false;
    }

    public void draw(ShapeRenderer shapeRenderer) {
        shapeRenderer.setColor(color);
        shapeRenderer.set(ShapeRenderer.ShapeType.Filled);
        shapeRenderer.circle(x,y,7);
    }

    public void setPosition(float x, float y) {
        this.x = x;
        this.y = y;
    }

    public float getX() {
        return x;
    }

    public float getY() {
        return y;
    }
}


package org.jpc.util.termprocessor.strategy;

import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

import org.jpc.term.Term;
import org.jpc.util.termprocessor.CompositeTermProcessor;
import org.jpc.util.termprocessor.TermProcessor;

public class PredicateTermProcessorStrategy implements TermProcessorStrategy {

    public final List<Map.Entry<Predicate<Term>, TermProcessor>> entries;

    public PredicateTermProcessorStrategy(List<Map.Entry<Predicate<Term>, TermProcessor>> entries) {
        this.entries = entries;
    }

    @Override
    public TermProcessor findTermProcessor(Term term) {
        Term compiledTerm = term;
        //Term compiledTerm = term.compile(); //currently needed to test for unification
        return entries.stream().filter(entry -> entry.getKey().test(compiledTerm)).map(Map.Entry::getValue).findFirst().orElseGet(
                () -> {throw new CompositeTermProcessor.NoTermProcessorAvailableException(compiledTerm);});
    }

}


# Sample
![sample](https://raw.githubusercontent.com/kshwetabh/GoogleCalendarWallpaper-Golang/master/wallpaper.png)

# Install Dependencies:
    - Get the Google Calendar API Go client library and OAuth2 package using the following commands:
        go get -u google.golang.org/api/calendar/v3
        go get -u golang.org/x/oauth2/google
    - Image manipulation library
        go get github.com/fogleman/gg

# Configuration Details
    "SourceImageDirectory": "C:\\Dev\\GoProgramming\\src\\github.com\\ksfnu\\calendar_wallpaper\\input",
    "OutputImageDirectory": "C:\\Dev\\GoProgramming\\src\\github.com\\ksfnu\\calendar_wallpaper\\output",
    "MarginRight": 400,
    "MarginTop": 50,
    "PrintDate": true,
    "TitleFont": "./Fonts/Roboto/Roboto-Bold.ttf",
    "TitleFontSize": 18,
    "ItemFontSize": 14,
    "ItemFont": "./Fonts/Roboto/Roboto-Medium.ttf",
    "TitleText": "Today's Calendar",
    "ItemPadding": 25,
    "GoogleCalendarID": "aaa@group.calendar.google.com"

# All Wallpapers taken from:
[pexels.com](https://www.pexels.com/)


package com.linkedpipes.etl.library.pipeline.adapter;

import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.Value;

import java.util.ArrayList;
import java.util.List;

public class RawPipelineDataFlow {

    /**
     * Connection resource.
     */
    public Resource resource;

    /**
     * Connection source component.
     */
    public Resource source;

    /**
     * Source binding.
     */
    public Value sourceBinding;

    /**
     * Connection target component.
     */
    public Resource target;

    /**
     * Target binding.
     */
    public Value targetBinding;

    /**
     * Vertices.
     */
    public final List<RawPipelineVertex> vertices = new ArrayList<>();

    public RawPipelineDataFlow() {
    }

    public RawPipelineDataFlow(RawPipelineDataFlow other) {
        this.resource = other.resource;
        this.source = other.source;
        this.sourceBinding = other.sourceBinding;
        this.target = other.target;
        this.targetBinding = other.targetBinding;
        for (RawPipelineVertex vertex : other.vertices) {
            this.vertices.add(new RawPipelineVertex(vertex));
        }
    }

}


package ua.bondarenkojek.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import ua.bondarenkojek.models.User;
import ua.bondarenkojek.services.UserService;

@Controller
@RequestMapping("/administrator")
public class AdminController {

    @Autowired
    private UserService userService;

    @GetMapping
    public String getAllUsers(ModelMap modelMap) {
        modelMap.addAttribute("users", userService.getAllUsers());
        return "admin";
    }

    @PostMapping("/delete")
    public String deleteUser(@RequestParam("id") Long id) {
        userService.deleteById(id);
        return "redirect: /administrator";
    }

    @PostMapping("/edit")
    public String editUser(@ModelAttribute("User")User user) {
        userService.save(user);
        return "redirect: /administrator";
    }
}


package com.glosoft.inventory_service.item;

import java.util.concurrent.atomic.AtomicLong;

public class Item {

    private final long id;
    private final long categoryId;
    private final String name;
    private final String description;
    private final String imageURL;

    public long getId() {
        return id;
    }

    public long getCategoryId() {
        return categoryId;
    }
    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public String getImageURL() {
        return imageURL;
    }

    private static final AtomicLong nextId = new AtomicLong();

    public Item(long categoryId, String name, String description, String imageURL) {
        this.id = nextId.incrementAndGet();
        this.categoryId = categoryId;
        this.name = name;
        this.description = description;
        this.imageURL = imageURL;
    }

   // public String getContent() {return content;}
}


public class Client {

    private String _clientName;
    private String _clientType;
    private String _hostname;
    private int _port;
    private int _responseTime;

    public Client(String row){
        // Parse the data, assigning to fields
        String[] data = row.split(",");
        _clientName = data[0];
        _clientType = data[1];
        String[] hostnamePort = data[2].split(":");
        _hostname = hostnamePort[0];
        _port = Integer.parseInt(hostnamePort[1]);
        _responseTime = Integer.parseInt(data[3]);
    }

    void setResponseTime(int responseTime){
        _responseTime = responseTime;
    }

    String getClientName(){
        return _clientName;
    }

    String getClientType() { return _clientType; }

    String getHostname(){
        return _hostname;
    }

    int getPort(){
        return _port;
    }

    int getResponseTime(){
        return _responseTime;
    }

    @Override
    public String toString(){
        return "" + _clientName + "," + _clientType + "," + _hostname + ":" + _port + "," + _responseTime + System.lineSeparator();
    }

}


package shani.firebasetesting;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.google.firebase.database.DatabaseReference;

public class MainActivity extends AppCompatActivity {
   Button addBtn, updBtn, dltBtn;
   public static String test ="Your Task App";
   static  DatabaseReference databaseReference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addBtn=findViewById(R.id.addBtn);
        updBtn=findViewById(R.id.updBtn);
        dltBtn=findViewById(R.id.deletBtn);

    }
public void buttonadd(View view){
    Intent intent=new Intent(MainActivity.this,Activity_UI.class);
    startActivity(intent);
}
public void buttonUpdate(View view){
        Intent intent=new Intent(MainActivity.this, Update_Delete_ViewAll.class);
        startActivity(intent);
}

}


package com.wx.control.login;

import com.wx.VO.ResultVO;
import com.wx.model.user.TUser;
import com.wx.service.user.UserService;
import com.wx.util.ResultVOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * Created by wx
 * 2018/9/19
 */
@RestController
@RequestMapping("/login")
public class LoginControl {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public ResultVO<Map<String,String>> login(String username, String password){
        System.out.printf(username+"---"+password);
        TUser user = userService.findUserByUsernameAndPassword(username,password);
        if(user!=null){
            return ResultVOUtil.succsee(user);
        }else{
            return ResultVOUtil.error(1,"用户名密码不正确");
        }

    }

    @RequestMapping("/logout")
    public ResultVO<Map<String,String>> logout(){
        return ResultVOUtil.succsee("注销成功！");
    }
}


# Replicator
News, full-text, and article metadata extraction in Java with Jsoup

[![Build Status](https://travis-ci.org/nougust3/Replicator.svg?branch=dev)](https://travis-ci.org/nougust3/Replicator)

## Usage
```
Loader loader = new Loader(url,
    new LoaderCallback() {
        @Override
        public void onLoaded(Article article) {
            System.out.println(article.title);
        }
        @Override
        public void onFailure() { }
    });
}
```

### Extracted data elements

- `title` - The document title
- `author` - The document author
- `content` - The main content of the document
- `image` - The main image for the document
- `tags`- Any tags or keywords
- `lang` - The language of the document
- `description` - The description of the document

### Supported languages
Russian, Arabic, Danish, German, Greek, English, Spanish, Finnish, French, Hebrew, Hungarian, Indonesian, Italian, Korean, Macedonian, Norwegian, Dutch, Swedish, Turkish, Vietnamese, Chinese.

### Demo
[replicator.nougust3.com]


package com.example.makanapa;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.fragment.app.Fragment;

public class LobbyFragment extends Fragment {
    private static LobbyFragment lobbyFragment;
    private Presenter presenter;
    private Button btnCari;

    private LobbyFragment(){

    }
    public static LobbyFragment newInstance(Presenter presenter){
        if (lobbyFragment == null){
            lobbyFragment = new LobbyFragment();
        }
        lobbyFragment.presenter = presenter;
        return lobbyFragment;
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View view = inflater.inflate(R.layout.fragment_lobby,container,false);
        this.btnCari = view.findViewById(R.id.btn_cari);
        this.btnCari.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lobbyFragment.presenter.changePage(FoodListener.PAGE2, false);
            }
        });
        return view;
    }
}


package com.shichen.scenicsport.data.source.local;

import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.content.Context;
import android.support.annotation.NonNull;

import com.shichen.scenicsport.data.Sport;

@Database(entities = {Sport.class}, version = 1, exportSchema = false)
public abstract class ScenicSportDatabase extends RoomDatabase {
    private static ScenicSportDatabase INSTANCE;

    public abstract SportsDao sportDao();

    private static final Object sLock = new Object();

    public static ScenicSportDatabase getInstance(@NonNull Context context) {
        synchronized (sLock) {
            if (INSTANCE == null) {
                INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                        ScenicSportDatabase.class, "ScenicSports.db")
                        .build();
            }
            return INSTANCE;
        }
    }
}


package com.coder.kzxt.course.adapter;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.coder.kzxt.activity.R;
import java.util.ArrayList;

/**
 * 课程班级适配器
 * Created by wangtingshun on 2017/3/10.
 */

public class CourseClassAdapter extends FragmentPagerAdapter {

    private Context mContext;
    private ArrayList<Fragment> fragments;
    private String[] titles = new String[1];

    public CourseClassAdapter( Context context,FragmentManager fm,ArrayList<Fragment> fragments) {
        super(fm);
        this.mContext = context;
        this.fragments = fragments;
        this.titles[0] = context.getResources().getString(R.string.courses);
      //  this.titles[1] = context.getResources().getString(R.string.classs);
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles[position];
    }
}


package me.tests;

import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.security.Security;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class IgnoreCertTest {
	private static ChromeDriver chromeDriver;
	private static DevTools chromeDevTools;

	@BeforeClass
	public static void initDriverAndDevTools() {

		chromeDriver = new ChromeDriver();

		chromeDevTools = chromeDriver.getDevTools();
		chromeDevTools.createSession();

	}

	@Test
	public void loadInsecureWebsite() {

		// enable Security
		chromeDevTools.send(Security.enable());

		// set ignore certificate errors
		chromeDevTools.send(Security.setIgnoreCertificateErrors(true));

		// load insecure website
		chromeDriver.get("https://expired.badssl.com/");

		// verify that the page was loaded
		Assert.assertEquals(true, chromeDriver.getPageSource().contains("expired"));

	}
}


package com.duggan.workflow.shared.model.dashboard;

import com.wira.commons.shared.models.SerializableObj;

public class TaskAging extends SerializableObj{

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private String period;
	private int taskCount;
	private int percentage;
	private int position;

	public TaskAging() {

	}

	public TaskAging(String period, int taskCount, int position){
		this.period = period;
		this.taskCount = taskCount;
		this.position = position;
	}

	public String getPeriod() {
		return period;
	}

	public void setPeriod(String period) {
		this.period = period;
	}

	public int getTaskCount() {
		return taskCount;
	}

	public void setTaskCount(int taskCount) {
		this.taskCount = taskCount;
	}

	public int getPercentage() {
		return percentage;
	}

	public void setPercentage(int percentage) {
		this.percentage = percentage;
	}

	public int getPosition() {
		return position;
	}

	public void setPosition(int position) {
		this.position = position;
	}
}


package com.brown3qqq.cstatour.dao.Impl;

import com.brown3qqq.cstatour.dao.UserCustomerRepository;
import com.brown3qqq.cstatour.dao.UserRepository;
import com.brown3qqq.cstatour.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.Iterator;
import java.util.List;

@Repository
public class UserRepositoryimpl implements UserCustomerRepository {

    @Autowired
    protected MongoTemplate mongoTemplate;

    @Override
    public User getUser(String name) {

        try {
            Query query = new Query(Criteria.where("realname").is(name));
            List<User> userlist = mongoTemplate.find(query,User.class,"user");
            Iterator<User> it = userlist.iterator();
            User user = it.next();

            return user;
        }catch (Exception e){

        }

        return null;
    }

}


package com.yang.lock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

import static com.yang.util.Sleeper.sleep;

/**
 * Description:
 *
 * @author mark
 * Date 2020/11/4
 */
public class CyclicBarrierDemo {
    private static final Logger logger = LoggerFactory.getLogger(CyclicBarrierDemo.class);

    private static final CyclicBarrier barrier = new CyclicBarrier(2);

    public static void main(String[] args) {

        new Thread(() -> {
            logger.debug("start");
            try {
                barrier.await();
                logger.debug("end");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }, "t1").start();

        new Thread(() -> {
            logger.debug("start");
            try {
                sleep(3000);
                barrier.await();
                logger.debug("end");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }, "t2").start();
    }
}


# Contributing to ChutesAndLaddersGame

Thanks for your interest in ChutesAndLaddersGame.

## Getting Started

ChutesAndLaddersGame's [open issues are here](https://github.com/animesh2712/ChutesAndLaddersGame/issues).
An easy way to get started helping the project is to *file an issue*.
Issues can include bugs to fix, features to add, or documentation that looks outdated.

## Contributions

ChutesAndLaddersGame welcomes contributions from everyone.

Contributions to ChutesAndLaddersGame should be made in the form of GitHub pull requests. Each pull request will
be reviewed by a core contributor.

## Pull Request Checklist

- Seed branch from the master branch and, if needed, rebase to the current master
  branch before submitting your pull request. If it doesn't merge cleanly with
  master you may be asked to rebase your changes.

- Commits should be as small as possible, while ensuring that each commit is
  correct independently (i.e., each commit should compile and pass tests).

- Add tests relevant to the fixed bug or new feature.


package com.universe.tasks.service;

import com.universe.tasks.model.Family;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.universe.tasks.repository.FamilyRepository;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class FamilyServiceImpl implements FamilyService
{
    @Autowired
    private FamilyRepository familyRepository;

    @Transactional
    public void saveFamily(Family family)
    {
        familyRepository.save(family);
    }
    @Transactional
    public List<Family> getAllFamilies()
    {
        return familyRepository.findAll();
    }

    public List<String> getFamiliesForUniverse(int id){
        return familyRepository.
                getFamiliesForUniverse(id).
                stream().
                map(Family::getFamilyName).
                collect(Collectors.toList());
    }

}


package com.qluxstory.qingshe.information.adapter;

import android.widget.ImageView;

import com.qluxstory.ptrrecyclerview.BaseRecyclerViewHolder;
import com.qluxstory.ptrrecyclerview.BaseSimpleRecyclerAdapter;
import com.qluxstory.qingshe.R;
import com.qluxstory.qingshe.common.utils.ImageLoaderUtils;
import com.qluxstory.qingshe.information.entity.InformationEntity;

/**
 * Created by lenovo on 2016/5/14.
 */
public class InformationAdapter extends BaseSimpleRecyclerAdapter<InformationEntity> {

    @Override
    public int getItemViewLayoutId() {
        return R.layout.item_information_fragment;
    }

    @Override
    public void bindData(BaseRecyclerViewHolder holder, InformationEntity informationEntity, int position) {
        holder.setText(R.id.information_tv1,informationEntity.getNews_big_title());
        holder.setText(R.id.information_tv2,informationEntity.getNews_small_title());
        ImageView mInformationImg=holder.getView( R.id.information_img);
        ImageLoaderUtils.displayImage(informationEntity.getNews_pic_url(), mInformationImg);

    }

}


package com.palehorsestudios.alone;

import java.util.Objects;

public class Food extends Item {
  private double caloriesPerGram;
  private double grams;

  public Food() {

  }

  public Food(String name, double caloriesPerGram, double grams) {
    super(name);
    this.caloriesPerGram = caloriesPerGram;
    this.grams = grams;
  }

  public double getCaloriesPerGram() {
    return caloriesPerGram;
  }

  public void setCaloriesPerGram(double caloriesPerGram) {
    this.caloriesPerGram = caloriesPerGram;
  }

  public double getGrams() {
    return grams;
  }

  public void setGrams(double grams) {
    this.grams = grams;
  }

  @Override
  public String toString() {
    return super.toString();
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    if (!super.equals(o)) return false;
    Food food = (Food) o;
    return Double.compare(food.caloriesPerGram, caloriesPerGram) == 0 &&
            Double.compare(food.grams, grams) == 0;
  }

  @Override
  public int hashCode() {
    return Objects.hash(super.hashCode(), caloriesPerGram, grams);
  }
}


package com.bugjc.ea.gateway.zuul.core.exception;

import lombok.Data;
import lombok.EqualsAndHashCode;

@EqualsAndHashCode(callSuper = true)
@Data
public class BizException extends RuntimeException {

    private int code;  //异常状态码
    private String message;  //异常信息
    private String method;   //发生的方法，位置等
    private String desc;   //描述

    public BizException(String message) {
        super(message);
        this.message = message;
    }

    public BizException(int code, String message) {
        super(message);
        this.code = code;
        this.message = message;
    }

    public BizException(int code, String message, Throwable cause) {
        super(message, cause);
        this.code = code;
        this.message = message;
    }

    public BizException(int code, String message, String method, String desc, Throwable cause) {
        super(message, cause);
        this.code = code;
        this.message = message;
        this.method = method;
        this.desc = desc;
    }
}


# Prototype
![Log In Screen](https://github.com/miseryprevails/TrackFitt/blob/main/Prototype%20HTML%20%26%20Pictures/LogInScreen.jpg)

This the Log In Screen. Here you have a username and password box to enter credentials.
you have the forgot password option to retrieve password, and below you can click new signup to create your new profile below.

![Profile Screen](https://github.com/miseryprevails/TrackFitt/blob/main/Prototype%20HTML%20%26%20Pictures/ProfileScreen.jpg)

Here is the profile screen once you have logged in. you have your feed which shows you food logging activity.
you have the option to add a profile bio, and below that you can set a status (Had a good workout today!)
you can navigate to the tabs to make a post, reply to a connection, or view your total connections.

![Calorie Calculator](https://github.com/miseryprevails/TrackFitt/blob/main/Prototype%20HTML%20%26%20Pictures/CalorieCalculator.PNG)

Here is the page where based on your stats put in, you will get a number back which will determine your total calorie intake needs based on goals selected. you can also sumbit your day activity at the bottom in the day activity bar.


package ee.app.conversamanager.model;

import android.content.Context;
import android.text.TextUtils;

import ee.app.conversamanager.R;

/**
 * Created by edgargomez on 9/15/16.
 */
public class nCategory {

    private final String objectId;
    private final String name;
    private final String avatarUrl;
    private boolean removeDividerMargin;

    public nCategory(String objectId, String name, String avatarUrl) {
        this.objectId = objectId;
        this.name = name;
        this.avatarUrl = avatarUrl;
        this.removeDividerMargin = false;
    }

    public void setRemoveDividerMargin(boolean removeDividerMargin) {
        this.removeDividerMargin = removeDividerMargin;
    }

    public boolean getRemoveDividerMargin() {
        return removeDividerMargin;
    }

    public String getObjectId() {
        return objectId;
    }

    public String getAvatarUrl() {
        return avatarUrl;
    }

    public String getCategoryName(Context activity) {
        if (activity == null) {
            return "";
        } else {
            return (TextUtils.isEmpty(name)) ? activity.getString(R.string.category) : name;
        }
    }

}


This folder contains:
1. Queries for evaluating our systems
2. Configuration files for searching in Galago
3. Raw results from Solr
4. Results from both systems ready for pooling

Experiment 1 (Galago)

Using `Galago`, we analysed the following:
1. Retrieval performance using different query operators:
    - BM25
    - Relevance model (RM)
    - Sequential Dependece model (SDM)
2. Difference in performance with addition of query description

Hence, a total of six different retrieval configurations were created.

Experiment 2 (Solr)

Using `Solr`, we ran our queries in English, Arabic, and Chinese, using
the same search parameters for all the searches.
We compared using topic titles alone, and title + description.

Again, a total of six different configurations were used.

After all the results were generated, the top 100 results for each system
were pooled and shuffled. The team then made relevance judgements to
identify whether each result was relevant to the query.


package org.openmrs.module.mirebalais.smoke.helper;

import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.openmrs.module.mirebalais.smoke.helper.SmokeTestProperties;

import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;

public class Exporter {

    public static void main(String[] args) throws Exception {

        SmokeTestProperties properties = new SmokeTestProperties();

        // database connection
        Class driverClass = Class.forName(properties.getDatabaseDriverClass());

        Connection jdbcConnection = DriverManager.getConnection(properties.getDatabaseUrl(), properties.getDatabaseUsername(), properties.getDatabasePassword());
        IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);

        // partial database export
        QueryDataSet partialDataSet = new QueryDataSet(connection);
        partialDataSet.addTable("patient_identifier");
        FlatXmlDataSet.write(partialDataSet, new FileOutputStream("partial.xml"));
    }
}


import java.util.Arrays;
import java.util.List;

public class Client implements Runnable{

	private Shop shop;

	@Override
	public void run() {
		List<Product> moqtSpisyk =  Arrays.asList(
				new Product("Pork", ProductType.MEATS),
				new Product("Cucumber", ProductType.VEGETABLES),
				new Product("Banana", ProductType.FRUITS));

		while (true) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
				return ;
			}

			System.out.println("Q sega da si ponazaruvam");
			try {
				Product randomProduct = moqtSpisyk.get((int)(Math.random() * moqtSpisyk.size()));
				int randomQuantity = (int)(Math.random() * 3)+1;

				shop.sellProduct(randomProduct, randomQuantity);

				System.out.println("Kupih "+ randomProduct + " - sega shte go izqm!");
			} catch (WarehouseException e) {
				e.printStackTrace();
			}
		}
	}

	public Shop getShop() {
		return shop;
	}

	public void setShop(Shop shop) {
		this.shop = shop;
	}

	public Client(Shop shop) {
		super();
		this.shop = shop;
	}

}


[Video Link](https://egghead.io/lessons/egghead-web-security-course-overview)

# 01. Web Security Course Overview

**These instructions are for macOS**

* Download Charles Proxy [charlesproxy.com/download](https://www.charlesproxy.com/download)
* Download Git run `git --version` in the command line to check if you have it [git](https://git-scm.com/downloads)
* Download Node.js run `node --version` make sure you have a version higher than 8.9.3 [nodejs](https://nodejs.org/en)
* Download npm ot comes with node, check the version `npm --version`
* Download curl check the version with `curl --version` if you don't have curl go to [curl.haxx.se](https://curl.haxx.se)

Make sure you have `sudo` privileges

Open and change the hosts file

```bash
code /etc/hosts
```
At the `127.0.01 localhost` line add evil.com and save it.

```
127.0.01 localhost evil.com
```

Run `sudo npm install` from the root of the repo

Then `cd exercises/01` then run `sudo npm start`

Visit the http://localhost.charlesproxy.com url there should be a username and password prompt

Run `sudo npm run start:evil.com` then will start a new server at https://evil.com:666/index.html.


package com.local_weather_API.external_APIs.darksky;

import com.local_weather_API.external_APIs.darksky.model.Currently;
import com.local_weather_API.external_APIs.darksky.model.WeatherFromDarkSkyApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class DarkSkyApiFetcher {

    @Value("${app.URL_DARKSKYWEATHER}")
    private String url2;

    public WeatherFromDarkSkyApi getWeatherFromApi(float latitude, float longitude) {
        RestTemplate restTemplate = new RestTemplate();
        int latInt = (int) latitude;
        int latDec = (int) Math.abs((latitude * 100) - latInt * 100);
        int lonInt = (int) longitude;
        int lonDec = (int) Math.abs((longitude * 100) - lonInt * 100);
        return restTemplate.getForObject(
                String.format(url2,latInt, latDec, lonInt, lonDec), WeatherFromDarkSkyApi.class);
    }

}


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Created by Dale.
 */
public class Frame extends JFrame {

    private JPanel menu;

    public Frame(){
        this.setLayout(new FlowLayout());
        this.setSize(400,300);
        this.setTitle("DAO");
        this.setBackground(Color.gray);

        this.createMenuPanel();
        this.add(menu);

    }

    private void createMenuPanel(){
        menu = new JPanel();
        JMenuBar statsThing = new JMenuBar();
        JButton winButton = new JButton("win");
        JButton loseButton = new JButton("lose");
        winButton.addActionListener(new WinListener());
        loseButton.addActionListener(new LoseListener());
        menu.add(winButton);
        menu.add(loseButton);

    }

    class WinListener implements ActionListener{

        public void actionPerformed(ActionEvent event){

        }

    }
    class LoseListener implements ActionListener{

        public void actionPerformed(ActionEvent event){

        }

    }

}


package models.base;

import java.util.Date;
import models.TicketPriority;

public class Task extends Item {
	private TicketPriority priority;
	private String assignee ;
	private Date plannedTime;
	private Date dueDate;

	public Task(String title, String description, Date dueDate, TicketPriority priority, Date plannedTime,
			String assignee) {
		super(title, description);
		this.priority = priority;
		this.assignee = assignee;
		this.plannedTime = plannedTime;
		this.dueDate = dueDate;
	}

	public TicketPriority getPriority() {
		return priority;
	}

	public void setPriority(TicketPriority priority) {
		this.priority = priority;
	}

	public String getAssignee() {
		return assignee;
	}

	public void setAssignee(String assignee) {
		this.assignee = assignee;
	}

	public Date getPlannedTime() {
		return plannedTime;
	}

	public void setPlannedTime(Date plannedTime) {
		this.plannedTime = plannedTime;
	}

	public Date getDueDate() {
		return dueDate;
	}

	public void setDueDate(Date dueDate) {
		this.dueDate = dueDate;
	}

}


import java.io.Serializable;

public class packet implements Serializable{
    private byte sequenceNum;
    private byte packetId;
    private int checksum;
    private String content;

    public packet(byte seqNum, byte packetId, int checksum, String content){
        this.sequenceNum = seqNum;
        this.packetId = packetId;
        this.checksum = checksum;
        this.content = content;
    }

    public byte getSequenceNum(){
        return this.sequenceNum;
    }

    public byte getPacketId(){
        return this.packetId;
    }

    public int getChecksum(){
        return this.checksum;
    }

    public String getContent(){
        return this.content;
    }

    public void corruptPacket(){
        this.checksum++;
    }

    public void recalculateChecksum(){ //for use by sender only :x
        int checksum = 0;
        for (char ch : this.getContent().toCharArray()) {
            checksum += ch;
        }
        this.checksum = checksum;
    }
}


# Configuration

All application extension configuration is defined with Guillotina's `configure`
module and the `app_settings` object.

Defining content types, behaviors, services, etc all require the use of the
`configure` module. Guillotina reads all the registered configuration in code
for each install application and loads it.

## app_settings

Guillotina also provides a global `app_settings` object::

```python
from guillotina import app_settings
```

This object contains all the settings from your `config.yaml` file as well as
any additional configuration settings defined in addons.

`app_settings` has an order of precedence it will use pick settings from:

 - guillotina's default settings
 - each application in order it is defined can override default guillotina settings
 - config.yaml takes final precedence over all configuration

`app_settings` has an extra key `__file__` that contains the path of the
configuration file, allowing relative paths to be used in an application
settings.


package com.example.spikespringsecurity.student;

import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("management/v1/students")
@RequiredArgsConstructor
public class StudentManagementController {
  private final StudentRepository studentRepository;

  @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_ADMINTRAINEE')")
  @GetMapping
  public List<Student> getAllStudents() {
    System.out.println("get all student");
    return studentRepository.findAll();
  }

  @PreAuthorize("hasAuthority('student:write')")
  @PostMapping
  public void registerNewStudent(@RequestBody Student student) {
    studentRepository.save(student);
  }

  @PreAuthorize("hasAuthority('student:write')")
  @DeleteMapping(path = "{studentId}")
  public void deleteStudent(@PathVariable Integer studentId) {
    studentRepository.deleteById(studentId);
  }

  @PutMapping(path = "{studentId}")
  public void updateStudent(@PathVariable Integer studentId, @RequestBody Student student) {
    studentRepository.save(student);
  }
}


package com.aaa.dao;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.aaa.bean.Command;
import com.aaa.db.DBAccess;

/**
 * 和Command表相关的数据库操作
 */
public class CommandDao {
	/**
	 * 根据查询条件查询指令列表
	 */
	public List<Command> queryCommandList(String name, String description) {
		DBAccess aDbAccess = new DBAccess();
		SqlSession aSqlSession = null;
		List<Command> CommandList = new ArrayList<Command>();
		try {
			aSqlSession = aDbAccess.getSqlSession();
			Command aCommand = new Command();
			aCommand.setName(name);;
			aCommand.setDescription(description);
			// 通过SqlSession执行SQL语句，通过Command.xml配置文件读取相应的sql语句操作数据库
			CommandList = aSqlSession.selectList("Command.queryCommandList", aCommand);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (aSqlSession != null) {
				aSqlSession.close();
				aSqlSession = null;
			}
		}
		return CommandList;
	}

}