Wednesday, March 24, 2021

Edward Lance Lorilla

Edward Lance Lorilla


【VISUAL C#】Enumerate Windows

Posted: 23 Mar 2021 10:17 PM PDT

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics; // make sure that using System.Diagnostics; is included
using System.Runtime.InteropServices; // namespace for DLL import
namespace enumeratewindow
{
public partial class Form1 : Form
{
protected delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
protected static extern int GetWindowText(IntPtr hWnd, StringBuilder strText, int maxCount);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
protected static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll")]
protected static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);
[DllImport("user32.dll")]
protected static extern bool IsWindowVisible(IntPtr hWnd);
public Form1()
{
InitializeComponent();
}
protected bool EnumWindows(IntPtr hWnd, IntPtr lParam)
{
int size = GetWindowTextLength(hWnd);
if (size++ > 0 && IsWindowVisible(hWnd))
{
StringBuilder sb = new StringBuilder(size);
GetWindowText(hWnd, sb, size);
this.listBox1.Items.Add(sb.ToString());
}
return true;
}
private void button1_Click(object sender, EventArgs e)
{
EnumWindows(new EnumWindowsProc(EnumWindows), IntPtr.Zero);
}
}
}
view raw Form1.cs hosted with ❤ by GitHub

【FLUTTER ANDROID STUDIO and IOS】Perspective 3D

Posted: 23 Mar 2021 07:17 PM PDT

import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
HomePage({Key key}) : super(key: key); // changed
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Offset _offset = Offset(0.2, 0.6);
@override
Widget build(BuildContext context) {
return Transform(
transform: Matrix4.identity()
..setEntry(3, 2, 0.001)
..rotateX(0.01 * _offset.dy)
..rotateY(-0.01 * _offset.dx),
alignment: FractionalOffset.center,
child: GestureDetector(
onPanUpdate: (details) => setState(() => _offset += details.delta),
onDoubleTap: () => setState(() => _offset = Offset(0.2, 0.6)),
child: _app(context),
)
);
}
_app(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blue[200],
appBar: AppBar(
title: Text('Perspective 3D Demo'),
),
body: Center(
child: Column(
children: [
Image.asset("assets/logo.png", scale: 1.5,),
],
),
),
);
}
}
view raw home_page.dart hosted with ❤ by GitHub
import 'splash.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Perspective 3D Demo',
theme: ThemeData.dark(),
home: Splash(),
);
}
}
view raw main.dart hosted with ❤ by GitHub
import 'dart:async';
import 'home_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class Splash extends StatefulWidget {
@override
VideoState createState() => VideoState();
}
class VideoState extends State<Splash> with SingleTickerProviderStateMixin {
var _visible = true;
AnimationController animationController;
Animation<double> animation;
startTime() async {
var _duration = new Duration(seconds: 3);
return new Timer(_duration, navigationPage);
}
void navigationPage() {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) =>
HomePage(
)));
}
@override
void initState() {
super.initState();
animationController = new AnimationController(
vsync: this, duration: new Duration(seconds: 2));
animation =
new CurvedAnimation(parent: animationController, curve: Curves.easeOut);
animation.addListener(() => this.setState(() {}));
animationController.forward();
setState(() {
_visible = !_visible;
});
startTime();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Stack(
fit: StackFit.expand,
children: <Widget>[
new Column(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Padding(padding: EdgeInsets.only(bottom: 30.0),
child: new Image.asset('assets/logo.png', height: 25.0,
fit: BoxFit.scaleDown,))
],),
new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Image.asset(
'assets/logo.png',
width: animation.value * 250,
height: animation.value * 250,
),
],
),
],
),
);
}
}
view raw splash.dart hosted with ❤ by GitHub

【PYTHON OPENCV】K-means clustering algorithm applied to three different 'clusters' of points (k=2)

Posted: 23 Mar 2021 06:52 PM PDT

"""
K-means clustering algorithm applied to three different 'clusters' of points (k=2)
"""
# Import required packages:
import numpy as np
import cv2
from matplotlib import pyplot as plt
# Create data (three different 'clusters' of points (it should be of np.float32 data type):
data = np.float32(np.vstack(
(np.random.randint(0, 40, (50, 2)), np.random.randint(30, 70, (50, 2)), np.random.randint(60, 100, (50, 2)))))
# Define the algorithm termination criteria (the maximum number of iterations and/or the desired accuracy):
# In this case the maximum number of iterations is set to 20 and epsilon = 1.0
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 1.0)
# Apply kmeans algorithm# K = 3, which is the number of clusters to split the set bytearray# attempts = 10, which specifies the number of times the algorithm is executed using different initial labellings (the# algorithm returns the labels that yield the best compactness)
# Flag cv2.KMEANS_RANDOM_CENTERS selects random initial centers in each attempt. You can also use cv2.KMEANS_PP_CENTERS
ret, label, center = cv2.kmeans(data, 2, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
# Now separate the data using label output (stores the cluster indices for every sample)
# Therefore, we split the data to different clusters depending on their labels:
A = data[label.ravel() == 0]
B = data[label.ravel() == 1]
# Create the dimensions of the figure and set title:
fig = plt.figure(figsize=(12, 6))
plt.suptitle("K-means clustering algorithm", fontsize=14, fontweight='bold')
fig.patch.set_facecolor('silver')
# Plot the 'original' data:
ax = plt.subplot(1, 2, 1)
plt.scatter(data[:, 0], data[:, 1], c='c')
plt.title("data")
# Plot the 'clustered' data and the centroids
ax = plt.subplot(1, 2, 2)
plt.scatter(A[:, 0], A[:, 1], c='b')
plt.scatter(B[:, 0], B[:, 1], c='g')
plt.scatter(center[:, 0], center[:, 1], s=100, c='m', marker='s')
plt.title("clustered data and centroids (K = 2)")
# Show the Figure:
plt.show()

【FLUTTER ANDROID STUDIO and IOS】Search with BloC

Posted: 23 Mar 2021 05:05 AM PDT

abstract class Bloc {
void dispose();
}
view raw bloc.dart hosted with ❤ by GitHub
import 'package:flutter/material.dart';
import 'screens/searchScreen.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.amber,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: Search(),
);
}
}
view raw main.dart hosted with ❤ by GitHub
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import '../bloc/userBloc.dart';
import '../models/userModel.dart';
class Search extends StatefulWidget {
@override
_SearchState createState() => _SearchState();
}
class _SearchState extends State<Search> {
@override
void initState() {
fetchUsers();
super.initState();
}
List<UserModel> totalUsers = [];
void search(String searchQuery) {
List<UserModel> searchResult = [];
userBloc.userController.sink.add(null);
if (searchQuery.isEmpty) {
userBloc.userController.sink.add(totalUsers);
return;
}
totalUsers.forEach((user) {
if (user.first.toLowerCase().contains(searchQuery.toLowerCase()) ||
user.last.toLowerCase().contains(searchQuery.toLowerCase())) {
searchResult.add(user);
}
});
userBloc.userController.sink.add(searchResult);
}
Future<void> fetchUsers() async {
final url = 'https://randomuser.me/api/?results=100';
http.Response response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
var body = jsonDecode(response.body);
final Iterable list = body["results"];
// map each json object to model and addto list and return the list of Icons.model_training_sharptotalUsers = list.map((model)'
totalUsers = list.map((model) => UserModel.fromJson(model)).toList();
userBloc.userController.sink.add(totalUsers);
}
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => FocusScope.of(context).unfocus(),
child: Scaffold(
backgroundColor: Colors.white,
body: Column(
children: <Widget>[
SizedBox(height: 20),
Container(
padding: const EdgeInsets.all(16.0),
child: TextField(
onChanged: (text) => search(text),
decoration: InputDecoration(
suffixIcon: Icon(Icons.search),
hintText: 'Search',
contentPadding:
EdgeInsets.symmetric(horizontal: 30, vertical: 20),
border: OutlineInputBorder(
borderSide: BorderSide(width: 3.1, color: Colors.red),
borderRadius: BorderRadius.circular(30),
),
),
),
),
Container(
height: 50,
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(color: Colors.green),
),
),
alignment: Alignment.center,
margin: EdgeInsets.symmetric(horizontal: 10),
padding: EdgeInsets.symmetric(horizontal: 10),
child: Text(
'Users',
style: TextStyle(fontSize: 16),
),
),
),
Expanded(child: usersWidget())
],
),
),
);
}
Widget usersWidget() {
return StreamBuilder(
stream: userBloc.userController.stream,
builder:
(BuildContext buildContext, AsyncSnapshot<List<UserModel>> snapshot) {
if (snapshot == null) {
return CircularProgressIndicator();
}
return snapshot.connectionState == ConnectionState.waiting
? Center(
child: CircularProgressIndicator(),
)
: ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: ListTile(
leading: Image.network('${snapshot.data[index].picture}'),
title: Text(
'${snapshot.data[index].first} ${snapshot.data[index]
.last}',
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 18),
textAlign: TextAlign.center,
),
),
);
},
);
},
);
}
}
import 'dart:async';
import 'bloc.dart';
import '../models/userModel.dart';
class UserBloc extends Bloc {
final userController = StreamController<List<UserModel>>.broadcast();
@override
void dispose() {
userController.close();
}
}
UserBloc userBloc = UserBloc();
view raw userBloc.dart hosted with ❤ by GitHub
class UserModel {
final String gender;
final String title;
final String first;
final String last;
final String city;
final String state;
final String country;
final String postcode;
final String picture;
final String phone;
UserModel.fromJson(Map<String, dynamic> json)
: gender = json['gender'],
title = json['name']['title'],
first = json['name']['first'],
last = json['name']['last'],
city = json['city'],
state = json['state'],
country = json['country'],
postcode = json['postcode'],
picture = json['picture']['large'],
phone = json['phone'];
}
view raw userModel.dart hosted with ❤ by GitHub

No comments:

Post a Comment