text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91
values | source stringclasses 1
value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
A structure which stores a specific view position, view direction and FOV, together with a textual description. More...
#include <SceneInfo.hpp>
A structure which stores a specific view position, view direction and FOV, together with a textual description.
Definition at line 158 of file SceneInfo.hpp.
Returns a list of all global views of a scene.
If the scene is invalid, an empty list is returned.
Returns a list of all user-generated views of a scene.
If the scene is invalid, an empty list is returned.
Saves the given user views to userviews.ini, replacing all views existing for this scene The scene MUST be valid, will throw an assertion if not.
A description of the view.
Definition at line 166 of file SceneInfo.hpp.
True if this is a position stored next to the scene definition (viewpoints.ini). If false, this is a user-defined view (from userdir\stellarium\scenery3d\userviews.ini).
Definition at line 172 of file SceneInfo.hpp.
Julian Date of interest.
Definition at line 174 of file SceneInfo.hpp.
Indicate if stored date is potentially relevant.
Definition at line 176 of file SceneInfo.hpp.
A descriptive label.
Definition at line 164 of file SceneInfo.hpp.
Stored grid position + current eye height in 4th component.
Definition at line 168 of file SceneInfo.hpp.
Alt/Az angles in degrees + field of view.
Definition at line 170 of file SceneInfo.hpp. | http://stellarium.org/doc/0.16/structStoredView.html | CC-MAIN-2018-09 | refinedweb | 233 | 62.34 |
Lang...
project
project sir
i want a java major project in railway reservation
plz help me and give a project source code with entire validation
thank you
java util date - Time Zone throwing illegal argument exception
java util date - Time Zone throwing illegal argument exception Sample Code
String timestamp1 = "Wed Mar 02 00:00:54 PST 2011";
Date d = new Date...());
The date object is not getting created for IST time zone. Java
project...
project...
enter 10 integers, store it using array then display... them from lowest to highest
number to words conversion create a java program... in words
example enter an integer 123
equivalent in words one hundred twenty
project
should write Java code, so as to:
1. Compute Gross Monthly Salary for all employees... in the correct place
The given code calculates the employees gross monthly
Java Project - Java Beginners
Java Project Write a Java program to create simple Calculator for 4... the following link:... code for making this calculator operational. Students are expected to handle
Java Util Package - Utility Package of Java
Java Util Package - Utility Package of Java
Java Utility package is one of the most commonly used packages in the java
program. The Utility Package of Java consist
java project
java project i would like to get an idea of how to do a project by doing a project(hospital management) in java.so could you please provide me with tips,UML,source code,or links of already completed project with documentation
about project code - Java Beginners
about project code Respected Sir/Mam,
I need to develop an SMS....
This can be developed using any kind of components using JAVA.
The following... source) available in JAVA. Even if we use those API's how the message will be sent
My name, java project
My name, java project Write a class that displays your first name... letter being displayed should have the lines of code needed to
display that letter in a method with the following name (for example, for
letter A,
public
project - Java Beginners
project in Java Need example project in Java
Java Project how to write a program for competitive exams(for student practice purpose)?
for example: first student have to login after login then he has to select the particular exam what he want to write i.e the exam may
online shopping project report with source code in java
online shopping project report with source code in java Dear Sir/Mam,
i want to a project in java with source code and report project name online shopping.
thank you
java project - Java Beginners
java project how can i download the source code for the project college admission system
Sample Code For ArrayLlist - Java Beginners
about ArrayList.
project
project suggest a network security project based on core java with explanation
project
project i need a project in java backend sql
Java Project - Java Beginners
Java Project Hello Sir I want Mini Student Admission System project in java
with Source Code and Back end Database is MS Access.
plz Give That Sir its Very Very Urgent
Java Project - Java Beginners
,
Please visit the following links:
Example Code - Java Beginners
Example Code I want simple Scanner Class Example in Java and WrapperClass Example.
What is the Purpose of Wrapper Class and Scanner Class .
when i compile the Scanner Class Example the error occur :
Can not Resolve symbol
JAVA Project Hi Friends,
Can somebody please tell me a website from where I can download java live projects along with the source code
Project
Project How to show Questions randomly so that no two student get the same questions in online examination system project in Java Server Pages
project
project I'm designing a netbeans java program/project. I have to design a program that captures the persons name and mark #.then find the average mark of the whole class.after that need to count and display who had the highest
java - code problem - Java Beginners
java - code problem hi I want to create log file for my new project. so i choose logging class from util package. But here print some unwanted texts....
Other Wise send ur code.
Thanks
Project - Java Beginners
Project Give me a sample project idea done using code Java
project
project write a program in java to develop a port scanner for common devices(HTTP,FTP,Telnet
project
project how to make blinking eyes using arc, applet in core java
Java Project - Java Beginners
question in my java project.
But this program is shoing error on the 50th line...Java Project Create a class Computer that stores information about... : 150,0000/- Hi Friend,
Try the following code:
import
java project - JavaMail
java project i want to make a project in java on ethernet mailing system.....can you provide the source code of this?and give me more suggestions to make
project in java - JDBC
friend,
i am sending java project link, visit following link
http...project in java hi,
i should do a project that enables a local cable operator to manage his customers. this should be done in java plz send me
project query
project query I am doing project in java using eclipse..My project is a web related one.In this how to set sms alert using Jsp code. pls help me
Java Hello World code example
Java Hello World code example Hi,
Here is my code of Hello World program in Java:
public class HelloWorld {
public static void main...");
}
}
Thanks
Deepak Kumar Hi,
Learn Java
Project in jsp
Project in jsp Hi,
I'm doing MCA n have to do a project 'Attendance Consolidation' in JSP.I know basic java, but new to jsp. Is there any JSP source code available for reference...? pls help me
Looking for sample project in java using netbeans
Looking for sample project in java using netbeans Hi all,
i am novice in developing desktop application in java using netbeans. can anyone pls help.../example/java/swing/addeditanddeleteemployee_inf.shtml
Java Project Deployment
Java Project Deployment Hi I have created a website using servlet and JSP. There are three type of users on the website namely administrator... your database. For example if you are using database MySql then you might
java project question
java project question how to calculate bill extracting quantity n price from one database table and inserting the result into another in java
Hi Friend,
Try the following code:
import java.sql.*;
import java.util.
sir plz send the project on quiz system code
sir plz send the project on quiz system code sir plz send the client server based project in core java
database in my sql
Java Project
Java Project Java project using with collection and generic with observer design pattern
Java hasNext
Java hasNext()
This tutorial discusses how to use the hasNext() method... Iterator. We are going to use
hasNext()
method of interface Iterator
in Java. The description of the code is given below for the usage of the method
want a project
want a project i want to make project in java on railway reservation using applets and servlets and ms access as database..please provide me code and how i can compile and run
abt java project - Java Beginners
abt java project if we want to create a pannel on the button how to write on the code in side the button plz help
java project
java project how many tables are required in backend for online examination system project in jsp
If backend is SQL
Help With My Java Project?
Help With My Java Project? Write a console program that repeatedly prompts the user to enter data until they type done (any case, Upper, Lower... by the first dimension.
Grading Notes:
Example:
User types:
apple
Apple
Zone
util
regarding project
and come up with combined solution quickly.
PROJECT NAME: DID I WRITE A GOOD JAVA PROGRAM?(JAVA/MVC/UI)
BRIEF DESCRIPTION OF A PROJECT:
The program helps....
The application should take the inputs of the following:
The java code
regarding project
solution quickly.
PROJECT NAME: DID I WRITE A GOOD JAVA PROGRAM?(JAVA/MVC/UI... of the following:
The java code class and package(either the exact file path...regarding project OBJECTIVES OF THIS PROJECT:
-Ability to test
regarding project
JAVA PROGRAM?(JAVA/MVC/UI)
BRIEF DESCRIPTION OF A PROJECT:
The program helps...:
The java code class and package(either the exact file path or the jar file containing...regarding project sir we need help about project. we have idea
Java Project Questions - Java Beginners
Java Project Questions Hello sir ,I want Course Form in JAVA SWING... Do that,plz Help Me Sir. Hi Friend,
Try the following code...*;
import java.sql.*;
import java.util.*;
class Project {
JFrame f
Java Final Project - Java Beginners
Java Final Project I am having a real hard time with this java... Project Overview
This document provide a sample of what is possible, and could lead to a project worth the maximum grade of 100% Something to think about
Project Guidance
Project Guidance Hello,
I have a project in SE at college and me... not looking for any piece of code or such...but I was wondering if you could give me... a combination of one or more of the following technologies: JavaScript, Java, JSP, XHTML
JAVA project
JAVA project How to extract tags and their corresponding properties of a "cascading style sheet" file using JAVA
Java util date
Java util date
The class Date in "java.util" package represents... to
string and string to date.
Read more at:
http:/
Java Project for College Admission System - Java Beginners
Java Project for College Admission System I want Project for Student Information System in Java
Back end-MS Access
plz Give Me source code or website to download it.
plz Help Me
Spring 3.0 Tutorials with example code
Spring 3.0 - Tutorials and example code of Spring 3.0 framework... of example code. The
Spring 3.0 tutorial explains you different modules...
download the example code in the zip format. Then run the code in Eclipse
java code - Java Beginners
java code can u plz provide source code for the mini project of "online course portal for a campus
abt java project - Java Beginners
abt java project this program compile sucessfully but data is not store in data base if any thing correction plz do it
import java.awt.*;
import...=new simple();
}
} Hi Friend,
Try the following code
java project
java project Connecting to MySQL database and retrieving and displaying data in JSP page by using netbeans
Associate a value with an object
with an object in Java util.
Here, you
will know how to associate the value for the separate code. Values regarding to
the separate code are maintained.... It takes four numeric value for the hash code of the several separate
object
project development
project development i have one html page called register.html page... database and i want code for jsp or servlets through access database urgent sir.
Here is a code that creates a registration form and save the data
i-election voting system project in java
i-election voting system project in java I want source code and documentation project in java. send
Java Project for College Admission System - Java Beginners
Java Project for College Admission System Hello Sir I urgently wants College Admission Project in Java,with Back End
Microsft Access 2007 ,sir plz Give me Full Source Code. Could u give me the filed should
Java Code - Java Beginners
the following links: Code Write a Java Program that display an Image and Apply
Create Project SplashScreen - Java Beginners
Create Project SplashScreen I want to Create project splashscreen that visible only for 1 minute after 1 minute i want to display LogIn form how i can create in java.
Hi Friend,
Try the following code:
1
code in java
code in java In NASA, two researchers, Mathew and John, started their work on a new planet, but while practicing research they faced a mathematical... with 1, then it is called John number.
Example of John numbers is:
13 = 1^2 + 3^2
Java Project - Java Beginners
Java Project Hey, thanks for everything your doing to make us better. Am trying to work on a project in java am in my first year doing software Engineering and the project is m end of year project. Am really believing
how to start a java project from scratch level
how to start a java project from scratch level 1.how to start a java project from scratch level ?can u give me small example
from design to development process
code - Java Beginners
code code for supermarket project
Java Project - Java Beginners
Java Project I'm a III yr Engineering student. I've been ask 2 prepare a project on Java. Can u plz suggest me some topics ? Hi friend... Java project topic with more information.
1. Asset Management
2. Shopping
JAVA code - Java Beginners
JAVA code I want to create an indexed output file that I can read, update records, add records to, and delete records from. I cannot determine the JAVA code to do that. Does anyone have an example
java code for threading example for connecting data base
java code for threading example for connecting data base Write a program that has two threads
First thread queries the database and fetches all the employee records from the emp table.
Stores the employee objects
java project - Java Beginners
java project project for internet banking Hi friend,
I am sending you a link. This link will help you.
Please visit for more information.
Thanks
JAVA PROJECT - Java Beginners
JAVA PROJECT Dear Sir,
I going to do project in java " IT in HR, recruitment, Leave management, Appriasal, Payroll"
Kindly guide me about... etc. I am doing project first time.
waiting for your reply,
Prashant
java code - Java Beginners
java code how can we convert an RGB image into its grayscale representation? Hi Friend,
Please visit the following link:
The code, you
java project - Java Beginners
java project hi this amol
i wish to do a project on banking software in java
can u help
how can i help u .. and what the kind... adam
certified java programmer
certified websphere ya sure!!
what
Java Code - Java Interview Questions
Java Code why overiding method used in your project
student admission system project
student admission system project College Student Admission System Project in Java Front End -JAVA Back End - MS Access Hello Sir, I want College Student Admission Project in Java with Source code, that includes Following Forms
Java Code - Java Beginners
Java Code Code a statement that creates an array of doubles named...(" " + num[i]);
}
}
}
For more example on Java visit to :
Thanks Dear Sir,
I have to do Project in "IT in HR i.e. Recruitment, Leave Management, Appraisal & payroll. These are Four main modules... employee master.
Now, can you tell in Java programming with Mysql How can
java code - Java Beginners
java code write a program for immutable class Hi Friend,
Try the following code:
final class ImmutableClass{
private final...(){
return price;
}
}
public class Example{
public static void main(String
mini project using html,javascript and ms access with source code
mini project using html,javascript and ms access with source code I want a mini project which uses html and java script and backend as ms access with source code. plz send its important and urgent
project detail - Java Beginners
project detail Dear roseindia,
i wnat to the idea for doing project in the java | http://www.roseindia.net/tutorialhelp/comment/20855 | CC-MAIN-2013-48 | refinedweb | 2,588 | 59.03 |
On Sat, 2002-12-21 at 18:43, Nuutti Kotivuori wrote:
> People would be stupid not to follow a well-made specification for
> these properties. And there's no reason to have it in the 'svn'
> namespace.
If it's used by a Subversion program, it should be in the svn:
namespace. Otherwise it shouldn't be.
Of course, that just reduces the question to equally unresolved
questions, like "are there any Subversion GUI programs which count as
Subversion programs?" and "should {rapidsvn/gsvn/svn ls -v/} use a
description property?" I have no opinion on those questions.
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@subversion.tigris.org
For additional commands, e-mail: dev-help@subversion.tigris.org
Received on Sun Dec 22 00:54:26 2002
This is an archived mail posted to the Subversion Dev
mailing list. | https://svn.haxx.se/dev/archive-2002-12/1451.shtml | CC-MAIN-2018-17 | refinedweb | 138 | 68.06 |
Many great if when you entered an art gallery, a computer could tell you which painting you look most like?
Well, I think it would be great. This is my blog, so what I say goes!
Getting The Data
I'm using the Tate's Open Data Set to grab scans of all their artwork. ~60,000 images in total.
Finding Faces
Not all paintings are of people. Some artsy types like to paint landscapes, dogs, starry nights, etc.
Using Python and OpenCV, we can detect faces in paintings. Then crop out the face and save it. The complete code is on GitHub - but here are the essentials.
import sys, os import cv2 import urllib from urlparse import urlparse def detect(path):, file_name): i = 0 # Track how many faces found for x1, y1, x2, y2 in rects: print "Found " + str(i) + " face!" # Tell us what's going on cut = img[y1:y2, x1:x2] # Defines the rectangle containing a face file_name = file_name.replace('.jpg','_') # Prepare the filename file_name = file_name + str(i) + '.jpg' file_name = file_name.replace('n','') print 'Writing ' + file_name cv2.imwrite('detected/' + str(file_name), cut) # Write the file i += 1 # Increment the face counter def main(): # all.txt contains a list of thumbnail URLs for line in open('all.txt'): file_name = urlparse(line).path.split('/')[-1] print "URL is " + line if (urllib.urlopen(line).getcode() == 200): # Download to a temp file urllib.urlretrieve(line, "temp.jpg") # Detect the face(s) rects, img = detect("temp.jpg") # Cut and kepp box(rects, img, file_name) else: print '404 - ' + line if __name__ == "__main__": main()
We now have a directory of files. Each file is a separate face. We assume that no two faces are of the same person - this is important for the next stage...
Building Eigenfaces
Imagine that a picture of your face could be represented by a series of properties. For example
- How far apart your eyes are.
- Distance from nose to mouth.
- Ratio of ear length to nose width.
- etc.
That is, in grossly simplified terms, what an Eigenface is.
If I have a database of Eigenfaces, I can take an image of your face and compare it with all the others and find the closest match.
We'll split this process into two parts.
Generate the EigenFaces
We need the arrange the images so that each unique face is in its own directory. If you know that you have more than one picture of each person, you can put those images in the same directory.
E.G.
|-path -|-Alice | |-0.jpg | |-1.jpg | |-Bob | |-0.jpg | |-Carly ...
This code is adapted from Philipp Wagner's work.
It takes a directory of images, analyses them, and creates an XML file containing the Eigenfaces.
WARNING: This code will take a long time to run if you're using thousands of images. On a dataset of 400 images, the resulting file took up 700MB of disk space.
import os import sys import cv2 import numpy as np def normalize(X, low, high, dtype=None): """Normalizes a given array in X to a value between low and high.""" X = np.asarray(X) minX, maxX = np.min(X), np.max(X) # normalize to [0...1]. X = X - float(minX) X = X / float((maxX - minX)) # scale to [low...high]. X = X * (high-low) X = X + low if dtype is None: return np.asarray(X) return np.asarray(X, dtype=dtype) def read_images(path, sz=None): X,y = [], [] count = 0 for dirname, dirnames, filenames in os.walk(path): for subdirname in dirnames: subject_path = os.path.join(dirname, subdirname) for filename in os.listdir(subject_path): try: im = cv2.imread(os.path.join(subject_path, filename), cv2.IMREAD_GRAYSCALE) # resize to given size (if given) if (sz is not None): im = cv2.resize(im, sz) X.append(np.asarray(im, dtype=np.uint8)) y.append(count) except IOError, (errno, strerror): print "I/O error({0}): {1}".format(errno, strerror) except: print "Unexpected error:", sys.exc_info()[0] raise count = count+1 return [X,y] if __name__ == "__main__": if len(sys.argv) < 1: print "USAGE: eigensave.py " sys.exit() # Now read in the image data. This must be a valid path! [X,y] = read_images(sys.argv[1], (256,256)) # Convert labels to 32bit integers. This is a workaround for 64bit machines, y = np.asarray(y, dtype=np.int32) # Create the Eigenfaces model. model = cv2.createEigenFaceRecognizer() # Learn the model. Remember our function returns Python lists, # so we use np.asarray to turn them into NumPy lists to make # the OpenCV wrapper happy: model.train(np.asarray(X), np.asarray(y)) # Save the model for later use model.save("eigenModel.xml")
After that has run - assuming your computer hasn't melted - you should have a file called "eigenModel.xml"
Compare A Face
So, we have a file containing the Eigenfaces. Now we want to take a photograph and compare it to all the other faces in our model.
This is called by running:
python recognise.py /path/to/images photo.jpg 100000.0
The "100000.0" is a floating-point number which determines how close you want the match to be. A value of "100.0" would be identical. The larger the number, the less precise the match.
import os import sys import cv2 import numpy as np if __name__ == "__main__": if len(sys.argv) < 4: print "USAGE: recognise.py sampleImage.jpg threshold" print "threshold is an float. Choose 100.0 for an extremely close match. Choose 100000.0 for a fuzzier match." print str(len(sys.argv)) sys.exit() # Create an Eign Face recogniser t = float(sys.argv[3]) model = cv2.createEigenFaceRecognizer(threshold=t) # Load the model model.load("eigenModel.xml") # Read the image we're looking for sampleImage = cv2.imread(sys.argv[2], cv2.IMREAD_GRAYSCALE) sampleImage = cv2.resize(sampleImage, (256,256)) # Look through the model and find the face it matches [p_label, p_confidence] = model.predict(sampleImage) # Print the confidence levels print "Predicted label = %d (confidence=%.2f)" % (p_label, p_confidence) # If the model found something, print the file path if (p_label > -1): count = 0 for dirname, dirnames, filenames in os.walk(sys.argv[1]): for subdirname in dirnames: subject_path = os.path.join(dirname, subdirname) if (count == p_label): for filename in os.listdir(subject_path): print subject_path count = count+1
That will spit out the path to the face that most resembles the photograph.
Who Am I?
Well, it turns out that my nearest artwork in the Tate's collection is...
So, there you have it. My laptop isn't powerful enough to crunch through the ~3,000 faces found in The Tate's collection. I'd love to see how this works given a powerful enough machine with lots of free disk space. If you fancy running the code - you'll find it all on my GitHub page.
22 thoughts on “Which Painting Do You Look Like? Comparing Faces Using Python and OpenCV”
Cool. You (or someone) should compile all this into a little web app.
Hi Terence, i found this proyect very useful for my FGP.
I´m having a problem when running the script eingesave.py.
I´m using Python 2.7 on Windows 8 64 bits.
I have all the libraries installed and my own database format. Jpg.
When I run this script in the command windows, an error appears:
"OpenCV Error: Assertion failed (ssize.area ()> 0) in unknown function, file .. .. .. src opencv modules imgproc src imgwarp.cpp, line 1723
Unexpected error:
Traceback (most recent call last):
File "C: Users William Desktop THESIS Python facerec2 eigensave.py", line 118, in
[X, y] = read_images (sys.argv [1], (256,256))
File "C: Users William Desktop THESIS Python facerec2 eigensave.py", line 87, in read_images
cv2.resize im = (im, sz)
cv2.error: .. .. .. src opencv modules imgproc src imgwarp.cpp: 1723: error: (-215) ssize.area ()> 0 "
What can be the problem?
Thank you very much.
Are all your images already square? I don't use Windows, so I'm not much help there - sorry!
Yes, they are squares. Specially, i`ve problem with this function: [X, y] = read_images (sys.argv [1], (256,256))
I managed to fix the read_images problem, now the problem is as follows:
File "C:UsersWilliamDesktopTESISPythonfacerec2eigensave.py", line 105,
in
y = np.asarray(y, dtype=np.int32)
File "C:Python27Libsite-packagesnumpycorenumeric.py", line 462, in asarr
ay
return array(a, dtype, copy=False, order=order)
ValueError: invalid literal for long() with base 10: 'C:UsersWilliamDeskto
pTESISPythonfacerec2datawils1.jpg'
I read that is somithing about converting label to integer.
Thanks
i have a error here i run recognise.py
OpenCV error: unspecified error (file can't be opened for writing!)
traceback (most recent call last):
file "recognise.py", line 35, in
model.load("eigenModel.xml")
cv2.error: ...facerec.cpp:398
help me, thanks.
The error message is quite clear - your computer cannot write to the file. Ensure that your permissions are set correctly.
thank you so much for your support
Is there any way to make this multithreaded?
Good day!
First of all, congratulations on this! This is so interesting and I did some modifications on this one.
I do have some questions, what is the confidence formula? what is it based? Thanks in advance!
I'm not sure - take a look at the OpenCV Eigenface documentation.
I tried it on macos 10.10 and ı get this error ? thanks
Traceback (most recent call last):
File "newfaces.py", line 47, in
[X,y] = read_images(sys.argv[1], (256,256))
File "newfaces.py", line 31, in read_images
im = cv2.resize(im, sz)
cv2.error: /opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_tarballs_ports_graphics_opencv/opencv/work/opencv-2.4.10/modules/imgproc/src/imgwarp.cpp:1968: error: (-215) ssize.area() > 0 in function resize
Hello, Thank you! Scripts work very well on Centos 7 x64.
But I have one question:
# Look through the model and find the face it matches
[p_label, p_confidence] = model.predict(sampleImage)
It returns the best match, or first that fits the threshold ?
Thanks Again!
Another result:
Using Visual Similarity with Google Image Search:
Can the trained model return multiple matches or does it only return the best possible match?
Hey I used the same code as ur's...Im getting This Result for any Images (0, 0.0)
Predicted label = 0 (confidence=0.00) ....Any help?
Looks like you either don't have the correct version of OpenCV installed, or you're not sending it any images.
I have created Java version of your face extraction code here:
Brilliant 🙂
Hi,
I have receive this error:
[X, y] = read_images (sys.argv [1], (256,256))
IndexError: list index out of range
How do I solve the problem?
Thank you very much
It looks like you're trying to read from a list element which doesn't exist. I'd suggest taking a quick look around some Python tutorials to see why.
Hi,
I managed to solve the problem, but is there any way which it can match more accurately?
Thank you | https://shkspr.mobi/blog/2014/06/which-painting-do-you-look-like-comparing-faces-using-python-and-opencv/ | CC-MAIN-2019-09 | refinedweb | 1,815 | 70.19 |
Hi, when comiling emacs on hppa-linux-gnu, I had the following error: > LC_ALL=C ./temacs -batch -l loadup dump ... Loading term/tty-colors... make[1]: *** [emacs] Bus error I found, that there is a problem in src/alloc.c, where pure_bytes_used becomes aligned for pure_floats, but PUREBEG is only int alinged. So the resulting adress after aligning pure_bytes_used to pure_float is still int aligned. The emacs version I used is 21.2. I could fix this problem with the following diff: # cat alloc_pure_float.patch --- src/alloc.c 2003/01/02 16:39:01 1.1 +++ src/alloc.c 2003/01/02 16:41:01 @@ -3802,7 +3802,7 @@ #else alignment = sizeof (struct Lisp_Float); #endif - pure_bytes_used = ALIGN (pure_bytes_used, alignment); + pure_bytes_used = (ALIGN (pure_bytes_used + (long) PUREBEG, alignment)) - (long) PUREBEG; } nbytes = ALIGN (size, sizeof (EMACS_INT)); Please fix possible wrong linebreaks before applying. I can also send this patch as attachement if needed. Berthold ______________________________________________________________________________ Bequemer und billiger - SMS mit FreeMail verschicken! Mehr Information unter: | https://lists.gnu.org/archive/html/bug-gnu-emacs/2003-01/msg00050.html | CC-MAIN-2021-17 | refinedweb | 161 | 76.93 |
Haskell: Using qualified imports to avoid polluting the namespace
In most of the Haskell code I've read any functions from other modules have been imported directly into the namespace and I reached the stage where I had this list of imports in a file:
import System.IO import Data.List.Split import Data.Char import Data.Bits import Control.Monad import Data.Map import Data.Set import Data.List import Data.Maybe
This becomes a problem when you want to use a function which is defined in multiple modules such as filter:
clustering.hs:53:43: Ambiguous occurrence `filter' It could refer to either `Data.List.filter', imported from `Data.List' at clustering.hs:11:1-16 (and originally defined in `GHC.List') or `Data.Set.filter', imported from `Data.Set' at clustering.hs:10:1-16 or `Data.Map.filter', imported from `Data.Map' at clustering.hs:9:1-16:
> import qualified Data.Map > Data.Map.assocs $ Data.Map.fromList [(1,2), (3,7)] [(1,2),(3,7)]
That's a bit long winded though so we can rename imports with a shorter name to make our life a bit easier:
import System.IO import Data.List.Split import Data.Char import Data.Bits import qualified Control.Monad as Monad import qualified Data.Map as Map import qualified Data.Set as Set import qualified Data.List as List import qualified Data.Maybe as Maybe
We can then use functions in those packages like so:
> Maybe.maybeToList (Just 3) [3]
For this particular function I haven't come across any with the same name so we might want to import that one into our namespace but require the use of the Maybe prefix for any other functions:
import qualified Data.Maybe as Maybe import Data.Maybe (maybeToList)
> maybeToList (Just 3) [3]
There's a wiki entry I came across which explains Haskell modules this in a bit more detail and is worth a read.
About the author
Mark Needham is a Developer Relations Engineer for Neo4j, the world's leading graph database. | https://markhneedham.com/blog/2012/12/30/haskell-using-qualified-imports-to-avoid-polluting-the-namespace/ | CC-MAIN-2018-47 | refinedweb | 343 | 63.36 |
testing locks.
Prakash Krishnamurthy
Ranch Hand
Joined: Oct 08, 2002
Posts: 154
posted
Apr 15, 2003 20:13:00
0
I am trying to
test
my locks. I have a test class that spawns a few threads. Each thread represents a client which is booking the same flight. The intention is to have multiple clients book the same flight at the same time so that I know if my locking and unlocking algorithm is working or not.
The problem is, on the client side I have the thread name with the output, so I know which client is doing what. But on the server side, I am not able to associate the clients with their respective threads on the server.
Any ideas how I can go about this?
Andrew Monkhouse
author and jackaroo
Marshal Commander
Joined: Mar 28, 2003
Posts: 11776
126
I like...
posted
Apr 15, 2003 20:38:00
0
Hi Prakash,
Depending on how readable you want your output to be, you have some choices:
Within the thread, if you simply do a System.out.print(this) you should get at least some sort of unique identifier (possibly the hashcode for the thread), and possibly a whole lot of debugging information as well.
public class ThreadTest extends Thread { public static void main(String[] args) { new ThreadTest().start(); new ThreadTest().start(); } public void run() { System.out.println("Thread: " + this); } } Thread: Thread[Thread-1,5,main] Thread: Thread[Thread-2,5,main]
Or, overide the constructor (you are doing that anyway for your tests), and pass in a unique identifier:
public class ThreadTest extends Thread { int id; public static void main(String[] args) { for (int i = 0; i < 2; i++) { new ThreadTest(i).start(); } } public ThreadTest(int id) { this.id = id; } public void run() { System.out.println(id + " Thread: " + this); } } 0 Thread: Thread[Thread-1,5,main] 1 Thread: Thread[Thread-2,5,main]
You can even override the toString() method to make it nicer:
public class ThreadTest extends Thread { int id; public static void main(String[] args) { for (int i = 0; i < 2; i++) { new ThreadTest(i).start(); } } public ThreadTest(int id) { this.id = id; } public void run() { System.out.println(this); } public String toString() { return "Currently running thread " + id; } } Currently running thread 0 Currently running thread 1
Does any of this help? If not please give more details of what you are trying to do.
Regards, Andrew
The Sun Certified Java Developer Exam with J2SE 5:
paper version from Amazon
,
PDF from Apress
, Online reference:
Books 24x7
Personal blog
Prakash Krishnamurthy
Ranch Hand
Joined: Oct 08, 2002
Posts: 154
posted
Apr 16, 2003 09:00:00
0
Andrew:
Probably, I wasn't too clear about my question. Let me re-ask this question. On the clientside when i run my threadtest class to test my locks I get the following output
Thread Name: Thread[One,5,main] Thread Name: Thread[Two,5,main] One: getting into criteriaFind Two: getting into criteriaFind Two: going to book record number 1 Two:getting into locking Two :Finished Locking One: going to book record number 1 One:getting into locking One :Finished Locking Two: Finished modifying the database! One: Finished modifying the database! Two: finished unlocking record no 1 One: finished unlocking record no 1
On the server though, I get this
The record number that is about to be locked is 1 Locking record number 1 ReadWriteLock: method writelock There seems to be no outstanding locks, hence locking the current thread hashed record numebr 1 The record number that is about to be locked is 1 Somebody is accessing this record, Please wait! Just about to enter the unlock for record no 1 Entered done method done method is finished Just about to enter the unlock for record no 1 Entered done method done method is finished
On the client I am clear about the thread name. But, on the server I am not sure which thread is locking and which thread is unlocking. Like, on the server side it says .
"The record number that is about to be locked is 1
Somebody is accessing this record, Please wait!
Just about to enter the unlock for record no 1"
It is not clear to me which thread does this corrrespond to...
I am going to try just doing
System.out.println("Thread : "+ this);
and see if things are clear on the server side. I think my question did get answered, though. I was just trying to make sure I had explained the problem well.:-)
[ April 16, 2003: Message edited by: Prakash Krishnamurthy ]
I agree. Here's the link:
subject: testing locks.
Similar Threads
gui clients can lock same record
Should the client be responsible for locking?
Best way to test multiple bookings
Test Client For FBN
Remote testing
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/183244/java-developer-SCJD/certification/testing-locks | CC-MAIN-2015-48 | refinedweb | 815 | 68.81 |
CodePlexProject Hosting for Open Source Software
Hi @all. First off I am completely new to Python Tools for VS as well as to Python in general. I started down this path to write a simple plugin for Plex Media Server (plexapp.com). Their Plugin-Framework is mostly Python. After coding a tiny bit in Notepad++
I was looking for some extra functionality like code completion.
Now I am struggling to figure out what I have to do so that I get some code completion working for objects and methods included in that framework. As far as I can see the relevant .py files that contain the framework objects are scattered in various sub-folders
of a folder called "Framework.bundle". Plugins do not require you to add any "import" statements as the framework is already loaded by the time the plugin code gets called by Plex Media Server.
Any help on this matter would be much appreciated.
Thanks & Best Regards,
Gundy
from Framework.bundle import *
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | http://pytools.codeplex.com/discussions/431415 | CC-MAIN-2014-52 | refinedweb | 201 | 75.1 |
New Safety Rules in C++ Code Analysis
Hwi-sung
In Visual Studio version 16.8 Preview 3, we are adding.
This blog post will introduce new rules related to
VARIANT and its sibling types – such as
VARIANTARG, or
PROPVARIANT. To help with the new rules, we have built a code analysis extension, called
VariantClear, that detects violations of these new rules in code. It is named
VariantClear because the primary rule it detects is about misuse of
VariantClear function.
The
VariantClear
extension detects and reports the following warnings:extension detects and reports the following warnings:
- C33001: VARIANT ‘var’ was cleared when it was uninitialized
- C33004: VARIANT ‘var’, which is marked as Out was cleared before being initialized
- C33005: VARIANT ‘var’ was provided as an input or input/output parameter but was not initialized
While Visual Studio version 16.8 Preview 3 already has the VariantClear extension included, it is not yet enabled by default. To enable this extension, please add the following lines either to your project file or to the
Microsoft.CodeAnalysis.Extensions.props file under
MSBuild\Microsoft\VC\v160 folder in the Visual Studio installation location:
If you want to add this to individual project file, add it after all other
<PropertyGroup> elements:
<PropertyGroup Condition="'$(ConfigurationType)'!='Utility' and '$(ConfigurationType)'!='Makefile'"> <EspXtensions Condition="'$(EnableVariantClear)'!='false'">VariantClear.dll;$(EspXtensions)</EspXtensions> </PropertyGroup>
If you want to modify your Visual Studio installation, you can add this to the
Microsoft.CodeAnalysis.Extensions.props file, after the similar element for
HResultCheck:
<EspXtensions Condition="'$(EnableVariantClear)'!='false'">VariantClear.dll;$(EspXtensions)</EspXtensions>
Please note that this will likely be overwritten if you repair or reinstall Visual Studio, or upgrade to a later release. Please stay tuned for update when we have this extension enabled in Visual Studio.
VariantClear Rules
VARIANT is a very convenient structure, allowing exchange of many different types of data using a single struct type. At any given time, it can hold either one of the alternative types, or no value. Type of the contained data or the fact that it contains no value is identified by the
VARIANT::vt member.
A
VARIANT object needs to be explicitly initialized before use or passed to some other code. Otherwise, this will cause random data to be accessed and used, causing different problems depending on what is accessed and how it is used.
A
VARIANT object also needs to be cleared when it is no longer needed. Otherwise, it can leave some resources behind, leaking resources or letting others mistakenly access and use the resource after its intended lifetime.
Initialization of a
VARIANT object is usually done through calling
VariantInit function. Clean up of a
VARIANT object is mostly done through calling
VariantClear function.
There are some wrapper types for VARIANT struct to make it easier and safer to use, e.g.
CComVariant and
_variant_t. Their default constructors initialize the instances being created and mark them as having no value, usually by calling
VariantInit, passing the current instance. Their destructors clear the instances being destructed and mark them as having no value, usually by calling
VariantClear, passing the current instance.
VariantClear rules try to enforce the general rules of proper initialization of VARIANT instances before their use, including cleaning them up.
Warning C33001
This warning is triggered when an uninitialized
VARIANT is passed into an API that clears a
VARIANT such as
VariantClear. These APIs expect the
VARIANT is initialized before they can be cleared. Unfortunately, developers often forget this step.
Here is a simplified example:
#include <Windows.h> HRESULT foo(bool some_condition) { VARIANT var; if (some_condition) { //... VariantInit(&var); //... } VariantClear(&var); // C33001 }
This code will trigger a C33001 warning because the
VARIANT
var is conditionally initialized only if
some_condition is
true. If the condition is
false, it will not be initialized when it is passed to
VariantClear function. To fix this problem, we have to make sure that we are calling
VariantClear only for the
VARIANTs that have been initialized:
#include <Windows.h> HRESULT foo(bool some_condition) { VARIANT var; if (some_condition) { //... VariantInit(&var); //... VariantClear(&var); // C33001 } }
Warning C33004
This warning is triggered when a
VARIANT parameter with
_Out_ SAL (source-code annotation language) annotation, which may not be to be initialized on input, is passed to an API such as
VariantClear that expects an initialized
VARIANT.
A parameter that is annotated as
_Out_ is not required to have been initialized when calling the function. It will be initialized upon return from the function. For more details of SAL annotations, please refer to SAL Annotations.
During code analysis, an
_Out_ VARIANT parameter is assumed to be uninitialized, to be on the safer side. If this parameter is passed to a function such as
VariantClear that expects an initialized
VARIANT object, it will try to clean up or use a random type of data, possibly at random memory location. Here is a simplified example:
#include <Windows.h> HRESULT t2(_Out_ VARIANT* pv) { // ...... VariantClear(pv); // C33004. pv is assumed uninitialized. // ...... return S_OK; }
To fix this problem, we have to make sure to initialize the
_Out_ VARIANT parameter before using it or passing it to another function that expects an initialized
VARIANT instance:
#include <Windows.h> void t2(_Out_ VARIANT* pv) { VariantInit(pv); // ...... VariantClear(pv); // OK // ...... }
Warning C33005
This warning is triggered when an uninitialized
VARIANT is passed to a function as input only or input/output parameter – for example, a parameter of
const VARIANT* type. Here is an example:
#include <Windows.h> void bar(VARIANT* v); // v is assumed to be input/output void foo() { VARIANT v; bar(&v); // C33005 // ...... VariantClear(&v); // OK, assumed to be initialized by bar }
Please note that the checker assumes a function that takes a non-const
VARIANT* parameter would initialize the
VARIANT object upon return from the function, to avoid generating noisy warnings.
Again, to fix this problem, we simply need to make sure to initialize the
VARIANT object before passing it to another function as an input-only or input-output parameter:
#include <Windows.h> void bar(VARIANT* v); // v is assumed to be input/output void foo() { VARIANT v; VariantInit(&v); bar(&v); // OK // ...... VariantClear(&v); // OK, assumed to be initialized by bar }
With the understanding of C33005 rule, it should be clearer why C33004 is reported only for an output-only (that is, annotated with
_Out_ SAL annotation) parameter. For an input-only or input-output parameter, passing an uninitialized
VARIANT will be a violation of rule C33005.
Enabling new rules in Visual Studio
You can enable these rules in Visual Studio as follows by selecting different ruleset for your project:
Give us your feedback
Check out these newly added rules and let us know.
So, would you say that SAL is not dead yet? 🙂
Very glad to see that you guys are continuously adding new checks and improving on code analysis. Maybe there is hope in the world for safer programs.
I tried this with VS 2019 Update 8 Preview 3.2 with both native recommended rules and all rules – I didn’t see any warnings…
Am I do something wrong, or is the checker not actually in the Update 8 Preview 3 build?
I can send the solution zipped up if you need to take a look?
Bug raised at:
Can you confirm if I’m right – that the checks don’t actually work? I’ve had no feedback from the bug triage team?
Thanks a lot for trying out the feature and bringing the issue to our attention. It is verified that the feature is still not enabled by default. The change to enable has been missing in the released product. I will come up with a workaround until we have the fix added to the product in an upcoming release.
We are working on enabling VariantClear extension by default. Meanwhile, a workaround for enabling VariantClear extension for build-time, compile-time, and menu-invoked code analysis is added to the body of the blog post, in the introduction section. Please give it a try and let me know if it works for you. Background Code Analysis requires a binary file update, and this workaround won’t enable VariantClear for Background Code Analysis.
The workaround of placing a PropertyGroup entry directly in the .vcxproj file does work for me. Thanks for the workaround.
I can confirm the workaround of using a PropertyGroup in the .vcxproj file does work. Thanks for the workaround.
C33005 appears to have poor support for _variant_t, making it noisy and nearly unusable.
Given the following code:
A C33005 warning is incorrectly issued:
warning C33005: VARIANT ‘&v’ was provided as an _In_ or _InOut_ parameter but was not initialized (expression ‘&v’)
Another case:
results in a C33005 for the line with “return result;”.
Thanks a lot for brining this to our attention. These are very valuable feedback to make our toolset better. To track the issue better, could you please create a feedback ticket in our Developer Community, in the C++ space?
We are having the same issue with _variant_t. I submitted an issue, see C33005 false positive with _variant_t.
I am searching for some good research blog pages. I searched through the search engines and found a website for your blog.
It’s a little bit complicated at first. But, when I read all of it. It was very informative. Good thing my friend from “Airport Service” told me this forum. | https://devblogs.microsoft.com/cppblog/new-safety-rules-in-c-code-analysis/ | CC-MAIN-2022-05 | refinedweb | 1,558 | 55.34 |
Python wrapper for XML output generator for Open Fortran Parser
Project description
XML output generator for Open Fortran Parser
Implementation has 2 parts: the XML generator written in Java, and Python wrapper for the generator.
The implementation is tested on Linux, OS X and Windows.
In this file, first the Java implementation is described and then the Python wrapper.
Java XML generator for OFP
This is an extension of Open Fortran Parser (OFP), which outputs abstract syntaxt tree (AST)
of parsed Fortran file in XML format - to a file or to
System.out.
dependencies
Java 1.7 or later
Open Fortran Parser 0.8.4-2
This is a patched version of OFP. Specifically, FortranParserActionPrint class in OFP could not be properly subclassed due to access levels of members of that class, so for example writing my own printer would introduce a lot of code duplication. Patch resolves this, without affecting any functionality.
The patch also resolves an issue when compiling with recent GCC versions.
ANTRL 3.3 (dependency of Open Fortran Parser)
Apache Commons CLI 1.4 (or later)
how to build
Get dependencies, either manually, or using the provided script:
pip3 install -U -r requirements.txt python3 -m open_fortran_parser --dev-deps export CLASSPATH="${CLASSPATH}:$(pwd)/lib/*"
Build:
ant export CLASSPATH="${CLASSPATH}:$(pwd)/dist/*"
This will create a .jar file in dist directory.
how to run
java fortran.ofp.FrontEnd --class fortran.ofp.XMLPrinter \ --output output.xml --verbosity 0~100 input.f
where:
- The
--verbosityflag controls verbosity of the parse tree. Defaluts to
100when omitted.
- Maximum,
100, means that all details picked up by Open Fortran Parser will be preserved.
- Minimum,
0, means that tree will contain only what is needed to reconstruct the program without changing it’s meaning.
- The
--outputflag controls where the XML should be written. Defaults to standard output when omitted.
and remaining command-line options are exactly as defined in OFP 0.8.4.
To parse
some_fortran_file.f and save XML output in
tree.xml with minimum verbosity:
java fortran.ofp.FrontEnd --class fortran.ofp.XMLPrinter \ --output tree.xml --verbosity 0 some_fortran_file.f
And to dump XML with maximum verbosity to console:
java fortran.ofp.FrontEnd --class fortran.ofp.XMLPrinter \ --verbosity 100 some_fortran_file.f
AST specification
Root node is
<ofp>, it has one subnode
<file>.
Inside the
<file>, there might be one or many of the following nodes:
<program>
<subroutine>
<module>
<interface>
- …
Each of which has
<header> and
<body>.
Additionally,
<module> has
In the body, a special node
<specification>, followed by a collection of statements can be found.
The
<specification> contains a collection of
<declaraion> nodes.
And, each of the statements listed after the specification, can be either compound or simple.
Compound statements, e.g.:
<if>
<loop>
- …
each have
<header> and
<body>.
In the header of the
<loop>, at least one
<index-variable> is present.
It has
<lower-bound>,
<upper-bound> and
<step>.
In the header of
<if>, an expression is present.
Expressions are built from the
<operation> nodes, each of which contains a collection of
<operand> and
<operator> nodes. Each operand can be also an expression,
or a simple node like:
<name>
<literal>
- …
All simple statements are using
<statement> node, which wraps around nodes like:
<assignment>
<call>
<open>
<write>
<return>
<stop>
<continue>
<cycle>
- …
Remaining details of AST are not decided yet. For the time being, to see implementation details, please take a look into src/fortran/ofp/XMLPrinter.java.
Python wrapper for the generator
Using the wrapper should not require any special knowledge about the generator itself, other than knowing the abstract syntax tree (AST) specification.
dependencies
Java XML generator for OFP and all of its dependencies.
Python version >= 3.6.
Python libraries as specified in requirements.txt.
Building and running tests additionally requires packages listed in test_requirements.txt.
how to build
pip3 install -U -r test_requirements.txt python3 setup.py sdist --formats=gztar,zip python3 setup.py bdist_wheel
how to install
You can simply install from PyPI:
pip3 install open_fortran parser
Or using any of below commands, when installing from source:
pip3 install . pip3 install dist/<filename>.whl pip3 install dist/<filename>.tar.gz pip3 install dist/<filename>.zip
how to run
The wrapper can be used as a script, or as a library.
When running any installed version, even if installed from source, dependencies are automatically installed together with the wrapper.
Before running from source (without installation), however, please follow “how to build” section for Java implementation above. You can make sure that dependencies are configured correctly by running:
python3 -m open_fortran_parser --deps
as script
$ python3 -m open_fortran_parser -h usage: open_fortran_parser [-h] [--version] [-v VERBOSITY] [--get-dependencies] [input] [output] Python wrapper around XML generator for Open Fortran Parser positional arguments: input path to Fortran source code file (default: None) output writable path for where to store resulting XML, defaults to stdout if no path provided (default: None) optional arguments: -h, --help show this help message and exit --version show program's version number and exit -v VERBOSITY, --verbosity VERBOSITY level of verbosity, from 0 to 100 (default: 100) --get-dependencies, --deps download dependencies and exit (default: False) Copyright 2017 Mateusz Bysiek, Apache License 2.0
as library
from open_fortran_parser import parse xml = parse('my_legacy_code.f', verbosity=0)
testing
python3 -m pylint --load-plugins=pylint.extensions.mccabe --docstring-min-length 5 \ --no-docstring-rgx "^(test)?_|.*Tests$" --unsafe-load-any-extension y \ --output-format colorized --reports y $(find . -name "*.py") python3 -m coverage run --branch --source . -m unittest discover --verbose python3 -m coverage report --show-missing python3 -m coverage html
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/open-fortran-parser/0.3.0/ | CC-MAIN-2018-30 | refinedweb | 941 | 50.63 |
Details
- Type:
Bug
- Status:
Resolved
- Priority:
Major
- Resolution: Fixed
- Affects Version/s: 2.5.2.Release
-
-
- Labels:
- Patch Submitted:Yes
- Number of attachments :
Description
Seems like the work in
GRECLIPSE-1233 is not complete. Mark occurrences is not correct when there are default parameter references coming from other files. Eg-
class C { def xxx(a, b = 2) {} }
and in another file:
def obj new C().xxx() new C().xxx(obj) new C().xxx(obj, obj) new C().xxx(obj, obj, obj)
Select the first, third or fourth method reference and the first, third, and fourth reference highlights. Select the second, and only the second highlights.
The correct behavior is that selecting any method reference should select all other references. This is the behavior that you see when all are inside the same file.
Issue Links
- is related to
GRECLIPSE-1256 Use a classfile attribute in the classfile to help determine the original method declaration of a method that uses default parameters | http://jira.codehaus.org/browse/GRECLIPSE-1255?page=com.atlassian.jira.plugin.system.issuetabpanels:worklog-tabpanel | CC-MAIN-2014-49 | refinedweb | 161 | 67.55 |
No project description provided
Project description
Another simple ioc framework for python.
Usage
from anyioc import ServiceProvider provider = ServiceProvider() provider.register_singleton('the key', lambda x: 102) # x will be scoped ServiceProvider value = provider.get('the key') assert value == 102
Need global ServiceProvider ? try from anyioc.g import ioc.
There are some predefined key you can use direct, but you still can overwrite it:
- ioc - get current scoped ServiceProvider instance.
- provider - alias of ioc
- service_provider - alias of ioc
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/anyioc/ | CC-MAIN-2019-18 | refinedweb | 104 | 60.41 |
Get the full sample solution from GitHub:
Most applications spend most of their time doing IO operations. Communicating with a database or web service over the network or reading and writing files can take orders of magnitude longer than running instructions on the CPU. Web applications are no different, but have a additional complexity in that they are multi-threaded by nature, each request being served on a new thread. IIS only maintains a certain sized threadpool for handing requests and once all the threads are consumed, requests start to queue. You can mitigate this by doing asynchronous IO.
Using the new Task Parallel Library in .NET 4.0 makes building asynchronous controller actions much easier, and this post will show you how.
Here’s a common scenario. I have a controller action that makes a couple of calls to a service class:
[HttpGet] public ViewResult Index() { var user = userService.GetCurrentUser(); userService.SendUserAMessage(user, "Hi From the MVC TPL experiment"); return View(user); }
The two methods I call on my UserService in turn make calls on two further classes:
public User GetCurrentUser() { const int currentUserId = 10; return userRepository.GetUserById(currentUserId); } public void SendUserAMessage(User user, string message) { emailService.SendEmail(user.Email, message); }
Yes, this is an entirely contrived and simplified example, but the essentials are in place.
The UserRepository in turn uses ADO.NET to make a call to SQL Server to retrieve a row from the database:
public class UserRepository { public User GetUserById(int currentUserId) { using (var connection = new SqlConnection("Data Source=localhost;Initial Catalog=AsncMvcTpl;Integrated Security=SSPI;")) { connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = "select * from [user] where Id = 10"; command.CommandType = CommandType.Text; using (var reader = command.ExecuteReader()) { if (reader.HasRows) { reader.Read(); return new User((int)reader["Id"], (string)reader["Name"], (string)reader["Email"]); } throw new ApplicationException("No row with Id = 10 in user table"); } } } } }
The EmailService sends an email using the Standard System.Net.Mail.SmtpClient:
public void SendEmail(string emailAddress, string message) { var mailMessage = new MailMessage("info@suteki.co.uk", emailAddress) { Subject = "Hello!", Body = "An important message from Nigeria :)" }; var smtpClient = new SmtpClient("smtp.suteki.co.uk"); smtpClient.Send(mailMessage); }
Now, both the call to the database and the email dispatch are IO intensive. Most of the time, the IIS thread that the action executes on will be idle, waiting for first the database and then the email call to return. Even though the thread is mostly idle, it is still not available to process other requests. At some reasonable load, the requests will start to queue and eventually IIS will give up entirely and issue a 503 ‘server busy’ error.
However, both the SqlDataReader.ExecuteReader and the SmtpClient.Send methods have asynchronous versions. Under the bonnet these use operating system IO completion ports which means that the thread handling the request can be returned to the IIS threadpool while the IO operation completes.
The trick is to make sure that the entire stack from the action method down to the BCL call (the BeginExecuteReader and SendAsync calls) knows how to work asynchronously. Prior to the Task Parallel Library, this would have meant implementing BeginXXX and EndXXX methods at every layer (the Asynchronous Programming Model), so we would have had UserService.BeginGetCurrentUser and UserService.EndGetCurrentUser etc, and then on the UserRepository, BeginGetUserById / EndGetUserById. The code starts to look pretty formidable as well.
With the Task Parallel Library, we can represent any async operation as a Task or Task<T>. The first job is to wrap the BCL SqlDataReader and SmtpClient calls as tasks. For BCL classes that implement BeginXXX and EndXXX methods we can just use the task factory’s FromAsync method, and that’s what we do here with the UserRepository’s GetUserById method:
public Task<User> GetUserById(int currentUserId) { var connection = new SqlConnection("Data Source=localhost;Initial Catalog=AsncMvcTpl;Integrated Security=SSPI;Asynchronous Processing=true"); connection.Open(); var command = connection.CreateCommand(); command.CommandText = "select * from [user] where Id = 10"; command.CommandType = CommandType.Text; var readerTask = Task<SqlDataReader>.Factory.FromAsync(command.BeginExecuteReader, command.EndExecuteReader, null); return readerTask.ContinueWith(t => { var reader = t.Result; try { if (reader.HasRows) { reader.Read(); return new User((int)reader["Id"], (string)reader["Name"], (string)reader["Email"]); } throw new ApplicationException("No row with Id = 10 in user table"); } finally { reader.Dispose(); command.Dispose(); connection.Dispose(); } }); }
Now GetUserById returns a Task<User> instead of a User. Effectively we are saying that the caller will get a user at some point in the future.
Once the reader has been wrapped in a task we can consume it with a continuation supplied to the ContinueWith method. The continuation can return a value, in our case a User, that then pops out of the ContinueWith method as the promise of a future user; a Task<User>.
SmtpClient doesn’t use APM, so turning its async operation into a task is a little more tricky, luckily this has already been done for us with the TPL team’s Parallel Extensions Extras library. I’m going to use that library’s SendTask extension method here:
public Task SendEmail(string emailAddress, string message) { var mailMessage = new MailMessage("info@suteki.co.uk", emailAddress) { Subject = "Hello!", Body = "An important message :)" }; var smtpClient = new SmtpClient("smtp.suteki.co.uk"); return smtpClient.SendTask(mailMessage, null); }
Because the synchronous version of this method returned void, we simply return Task here.
Now the power of the TPL really starts to work for us. We hardly have to change our UserService methods at all:
public Task<User> GetCurrentUser() { const int currentUserId = 10; return userRepository.GetUserById(currentUserId); } public Task SendUserAMessage(User user, string message) { return emailService.SendEmail(user.Email, message); }
We are simply passing Task<User> and Task back up the stack, no need to implement Begin/End methods. This is very powerful.
Finally we come to the action method. This is where the code gets gnarly again. We have leave the lovely world of TPL and shoehorn it into the crappy MVC async controller:); } }
Jeff Prosise has a very nice post about the ASP.NET MVC async controller. You’d probably want to read that first. But simply put, you inherit from AsyncController and rather than calling your action ‘Index’ you split it into two and call it IndexAsync and IndexCompleted, the router understands this convention and correctly routes Home/Index to the IndexAsync action.
AsyncController has an AsyncManager that keeps track of async callbacks using its Increment/Decrement methods. When the count gets back to zero IndexCompleted is called. You can marshal state to the completed method using the AsyncManager’s Parameters dictionary as shown.
Once again we are using ContinueWith to supply continuations to grab the result of GetCurrentUser and then wait for the SendUserAMessage to complete.
Note that I haven’t considered exception handling in this example. You need to be very careful that you catch and notify exceptions that happen in async operations.
Now for my gripe. It would have been really slick if the MVC team had used TPL to implement async controller methods. I should be able to keep my single Index action but return a Task<ViewResult> instead. My async Index action would then look like this:
[HttpGet] public Task<ViewResult> Index() { return from user in userService.GetCurrentUser() from _ in userService.SendUserAMessage(user, "Hi From the MVC TPL experiment") select View(user); }
Update: Craig Cav has implemented an async controller that does just this. You can read his post about it here. He’s branched my example and demonstrates the Task based async controller here.
Oh yes, tasks are monadic so you can compose them with Linq. No they are not, but the Linq extensions can be found in the TaksParallelExtensions library. See my post here for more info.
Should I care about this?
As with most scalability optimisations this makes your code more complex, harder to understand and harder to debug. I’ve been happily building web applications without doing this for years. You should only ever use this technique if you have an immediate scalability concern and you know that it is caused by a threadpool full of threads blocked by long running IO operations.
Having said that, if you do have these kinds of issues, then using the TPL like this makes them easier to solve than the older being/end spaghetti that you previously would have had to write.
It’s also worth noting that doing this kind of thing will become easier still with C#5’s new async operator. At that point it might we worth doing this kind of async IO as a matter of course.
10 comments:
I've wanted to take a look at the TPL for awhile. Thanks for the example.
Mike, Thanks for a great intro into using the TPL within a ASP.NET MVC context. I too, am not especially pleased in how polluted the controllers become in this scenario.
The first thing that comes to mind though, is to perhaps inherit from controller and implement the async controller using TPL. Have you looked at this option?
Hi Brad,
That's a good suggestion. I might have a look at the MVC3 source code and see how hard it would be.
Hi, I didn't really get much of it, could you perhaps be more intermediate developer friendly next time and take more time to explain things?
Just a recommendation.
Hi Anonymous,
Your feedback could be very useful here. If you let me know what concepts you are having trouble with, I can try and improve the post.
Great post Mike.
Hi Mike,
I've forked your example on GitHub and have implemented a controller action invoker to support async actions through Tasks.
You can check it out here:
And a quick summary on my blog here:
Hi Craig,
That's excellent work. I had a quick look at doing the same, but was defeated by the spaghetti code in the AsyncController, I didn't realise there was as better implementation in the futures assembly. Thanks for pointing that out.
I'll update the post to point at your post and fork.
Hello.
Stupid question: what happens if BeginExecuteReader throws? that will probably result in a non observable exception, right? in fact, if result (ie, the data reader) hasn't returned yet, your task.Result property might end up throwing. Since it's outside the try/finally, won't you end up with an orphan connection? | http://mikehadlow.blogspot.com/2010/11/using-task-parallel-library-with-aspnet.html?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+CodeRant+%28Code+rant%29 | crawl-003 | refinedweb | 1,736 | 57.37 |
Here are two perfectly good ways to turn
123456789 into
"123,456,789":
import locale def f1(n): locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') return locale.format('%d', n, True) def f2(n): r = [] for i, c in enumerate(reversed(str(n))): if i and (not (i % 3)): r.insert(0, ',') r.insert(0, c) return ''.join(r) assert f1(123456789) == '123,456,789' assert f2(123456789) == '123,456,789'
Which one do you think is the fastest?
Easy, write a benchmark:
from time import time for f in (f1, f2): t0 = time() for i in range(1000000): f(i) t1 = time() print f.func_name, t1 - t0, 'seconds'
And, drumroll, the results are:
peterbe@mpb:~$ python benchmark.py f1 19.4571149349 seconds f2 6.30253100395 seconds
The
f2 one looks very plain and a good candidate for PyPy:
peterbe@mpb:~$ pypy dummy.py f1 14.367814064 seconds f2 0.77246594429 seconds
...which is 800% speed boost which is cute. It's also kinda ridiculous that each iteration of
f2 takes
0.0000008 seconds. What's that!?
An obvious albeit somewhat risky optimization on
f1 is this:
import locale locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') def f1(n): return locale.format('%d', n, True)
...and now we get:
peterbe@mpb:~$ python dummy.py f1 16.3811080456 seconds f2 6.14097189903 seconds
Before you say it, yes I'm aware the locale can do much more but I was just curious and I scratched it.
UPDATE
Dave points out the built in function format (which was added in Python 2.6). So let's add it and kick ass!
def f3(i): return format(i, ',')
And we run the tests again:
peterbe@mpb:~$ python dummy.py f1 16.4227910042 f2 6.13625884056 f3 0.892002105713 peterbe@mpb:~$ pypy dummy.py f1 4.61941003799 f2 0.720993041992 f3 0.26224398613
There's your winner!
Follow @peterbe on Twitter
If we're talking about performance, I wouldn't call f2 a good method for this. While it's fine for small numbers, list.insert is O(n) for each insert, making f2 an O(n^2) operation, while the operation can easily be done in O(n) time since it requires only one pass over the data.
Two simple ways to rewrite f2 for O(n) operation are:
1. Use len() to calculate the offset from the left of the first comma so you can work left to right and use list.append instead of list.insert.
2. Use a collections.deque instead of a list to allow O(1) inserts at the beginning of the deque.
There are also a bunch of good solutions to this problem in inlcuding the beautifully simple "'{:,}'.format(value)". I'd be interested to know how various methods perform on small vs. large numbers.
What about format(n, ',')?
It's new in 2.7 right? I guess it warrents to be included.
I actually didn't know about this one. I'm glad you mentioned it!
+20% speed
def f1(n):
return ''.join(
reversed(
[
c + ','
if i != 0 and i % 3 == 0 else
c
for i, c in enumerate(reversed(str(n)))
]
)
)
That looks like f2() but laid out slightly differently.
There's nothing risky about that "optimization", as it is the right thing to do. The locale settings manged by locale.setlocale() are global. You shouldn't ever be setting them in a locale-using routine like that.
Bruno Renié adds his version which improves on f2() by almost 100% in the CPython benchmark.
I would've used the 2.7 format() for socorro-crashstats but we only have 2.6 on the Mozilla servers (RHEL 6) :( although honestly I care more about readability than perf unless it's shown to be a bottleneck for a use case we care about. However, this is still a very interesting discussion and I don't wish to discourage it :)
I've actually been playing with pypy a bit, even though we're super i/o-bound on Socorro. I think it's be interesting for certain type of analysis that Java is used for now, and also for better alternatives to our approach to threading (e.g. something safer/saner like STM) without having to write in some brutally different style like twisted/tornado/etc
Looking at local.py there's a lot going on there:
This is related to the obvious downside to optimizing this - you are precluding localizing the app so it displays the appropriate digit group separator (note that "thousands" is not always the appropriate group, see)
Performance would only matter if we did a spreadsheet app or something. We don't.
Right, in Swedish for example the price of a chewing gum is: SEK 0,5
Whereas here in the US it's USD 0.5
locale.setlocale(locale.LC_ALL, '')
def f5(n):
return format('n', n)
Works in 2.6 (',' needs 2.7).
See the UPDATE to the post above.
Sorry, but I don't see any reference to the 'n' format in the post, its update, or any of the other comments.
Python 2.6.6 (r266:84292, Dec 5 2011, 09:38:23)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.1.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> format('n', 100000000)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: format expects arg 2 to be string or unicode, not int
My apologies, I was working on two different computers and retyped the code snippet incorrectly. The correct code should of course be:
import locale
locale.setlocale(locale.LC_ALL, '')
def f5(n):
return format(n, 'n') | https://www.peterbe.com/plog/thousands-commafy-large-numbers | CC-MAIN-2019-43 | refinedweb | 950 | 77.23 |
How to use React in Markdown
In this post I 'll talk about how to use React components in Markdown. First of all, why would you want to do that? The reason is I'm writing posts in Markdown and use a static site generator to convert them to HTML pages, so it would be useful if I could insert React components directly in my Markdown writeup. This allows mixing React with Markdown in a single file. For example, if I talk about some data in my posts and want to render a chart with this data, it would be nice if my writeup could look something like this:
## Markdown Title Here is a React component in _Markdown_: <Chart data={[...]} /> Some more **Markdown**.
#Use a custom React Parser
The solution is pretty straight-forward. On top of the Markdown parser, we can create a custom parser that checks for React components.
This parser is triggered after the Markdown parser, so we have to make sure that the way we use React components in Markdown doesn't interfere with it.
For that, we change the syntax to be an
HTML element as the Markdown parser will not alter them. We simply use a
div tag and put the concrete React component
to render in the
class attribute (with a react- prefix) and the data as a JSON string into another attribute which we will call
props.
Using a React component in a Markdown post then looks like this:
## Some Markdown Here is a **React component** in _Markdown_: <div class='react-chart' props='{"data":[1,2,3]}'></div>
We have to use single quotes to surround the attributes, as we will use
JSON.parse later which only supports double quotes in the JSON string.
#Implementing the React Parser
We need a way to access the output of the Markdown parser. I 'm using phenomic as a static site generator which provides the output
as a string property
body to a React component (using Layouts).
The procedure is then as follows:
- Import the React components you want to include in your posts
- Look for
<div class='react-*' props='*'></div>strings and extract the component name and props.
- Call the corresponding React component with the correct props and render it to a string by using
ReactDOMServer.renderToStaticMarkup
- Replace the
<div class='react-*' props='*'></div>code with this string.
- Render the markup and React component content with
dangerouslySetInnerHTML={{ __html: body }}
This is easily doable using
body.replace(RegExp
):
import React, { Component, PropTypes } from 'react' import ReactDOMServer from 'react-dom/server' import { Chart } from '../../components' // matches strings like // <div class='react-chart' props='{"val":5}'></div> // <div class='react-test' > </div> // Make sure to use SINGLE quotes for defining HTML attributes, // as we need double quotes to parse the JSON props attribute const pattern = new RegExp( String.raw`<div\s*class='react-(\S*)'\s*(props='(.*)'\s*)?>\s*</div>`, 'ig') export default class PostWithCharts extends Component { render () { let { body, ...otherProps } = this.props if (body) body = body.replace(pattern, this.replacementBasedOnMatch) return ( <div dangerouslySetInnerHTML={{ __html: body }} {...otherProps}> </div> ) } replacementBasedOnMatch (match, name, propsMatch, props) { props = propsMatch ? JSON.parse(props) : undefined switch (name) { case 'chart': { return ReactDOMServer.renderToStaticMarkup(<Chart {...props} ></Chart>) } default: { console.error(`Cannot replace ${name} with a React component. ${match}`) return '<h1><del>This paragraph should not be here.</del></h1>' } } } } PostWithCharts.propTypes = { body: PropTypes.string.isRequired // Markdown post containing the react-div }
The nice thing is that it works with server-side rendering. So in the final HTML file
there won't be a
<div class='react-*' props='*'></div> element, instead the React component's
render output will be inserted directly. | http://cmichel.io/how-to-use-react-in-markdown/ | CC-MAIN-2017-47 | refinedweb | 604 | 54.32 |
NAME
OpenResty::Handler::Shell - Example Shell API for OpenResty custom handlers
SYNOPSIS
# list all executables in PATH GET /=/shell # get the path of the "ls" program GET /=/shell/ls # call the "ls" program GET /=/shell/ls/~/~ # call "ls -a" GET /=/shell/ls/~/~?a="" # call perl oneliner: perl -e 'hello,world' GET /=/shell/perl/e/print("hello,world") # server returns "hello,world" # or use POST to feed stdin: echo "print 'hello, world'"|perl -w POST /=/shell/perl/~/~?w="" "print 'hello, world'"
DESCRIPTION
This handler is merely served as a simple and also funny sample custom handler for users who want to write their own handlers.
It's not meant to be used in the real world.
To use this Shell handler in your OpenResty setup, set the
frontend.handlers to
Shell in your site_openresty.conf file:
[frontend] handlers=Shell
To simplify things here, this Shell handler bypasses the OpenResty ACL mechansim, just like the Version and Login handler. So take care ;) For handlers requiring login, change the following line
sub requires_acl { undef }
to
sub requires_acl { 1 }
or just comment it out.
Note that this handler does not require a PostgreSQL database to function. You can use the
Empty backend to run this handler. For example, in your site_openresty.conf file:
[backend] type=Empty
Because OpenResty's Role API replies on a working Pg backend, you cannot use
Empty backend if you turns ACL on by returning true in your
requires_acl sub.
Custom handler names must be under the
OpenResty::Handler:: namespace, e.g.,
OpenResty::Handler::Shell. It's not required to be included in the OpenResty source tree, just ensure it's installed into the same perl that OpenResty uses.
AUTHOR
Agent Zhang (agentzh)
<agentzh@yahoo.cn> | https://metacpan.org/pod/OpenResty::Handler::Shell | CC-MAIN-2015-11 | refinedweb | 286 | 62.68 |
In my previous post, I installed Ubuntu 16.04 onto a Raspberry Pi 3 and installed .NET Core 2 as well – finishing the post by creating and deploying a simple hello world application. This time, I’d like to investigate how to interact with the GPIO pins, first using the command line – and then using .NET Core 2.
Changing GPIO pin status
If I wanted to change the status of a pin (let’s say pin 26):
- First I need to write “26” to a file named export at the location /sys/class/gpio
- After this, a folder named gpio26 will be created at /sys/class/gpio/gpio26
- This directory also has some files, including two named direction and value.
- Since I want this pin to be an output, I write the text out to the file named direction.
- Finally to switch the pin on, I write the text 1 to the file named value.
See here and here for more information.
So if I try to run the first step and echo “26” to /sys/class/gpio/export file, I’m denied permission – this is because I can only alter the GPIO status as root.
Instead, I can run this command within its own shell using:
sudo sh -c "echo 26 > /sys/class/gpio/export"
After running this, if I inspect the contents of the /sys/class/gpio folder, there is a new folder called gpio26.
And if I inspect the contents of gpio26, I can see a number of files, including ones named “direction” and “value“.
I can write different values to the “direction” and “value” files to set the direction of the pin and set whether it’s on or off.
# Set Pin 26 as an output pin sudo sh -c "echo 'out' > /sys/class/gpio/gpio26/direction" # Set Pin 26 to a status of 'High' sudo sh -c "echo '1' > /sys/class/gpio/gpio26/value" # Set Pin 26 to a status of 'Low' sudo sh -c "echo '0' > /sys/class/gpio/gpio26/value" # Remove access to GPIO 26 sudo sh -c "echo 26 > /sys/class/gpio/unexport"
Using .NET Core 2 to activate GPIO pins
Given we now know how to switch pins on and off, we can recreate this function in .NET. The code below shows three steps – open pin 26, specify the direction of the pin as out, and switch the pin on or off (depending on the argument passed in, which will be a 1 or 0).
using System; using System.IO; namespace GpioSwitch { class Program { static void Main(string[] args) { if (args.Length != 1) { throw new ArgumentNullException("You must specify a logic level for Pin 26"); } else { if (args[0] != "1" && args[0] != "0") { throw new ArgumentOutOfRangeException("Unknown logic level"); } } // about to open pin 26 - test if it's already open if (!Directory.Exists("/sys/class/gpio/gpio26")) { Console.WriteLine("...about to open pin 26"); File.WriteAllText("/sys/class/gpio/export", "26"); } else { Console.WriteLine("...pin is already open"); } Console.WriteLine("...specifying direction of Pin 26 as OUT"); File.WriteAllText("/sys/class/gpio/gpio26/direction", "out"); Console.WriteLine("...setting output level to " + args[0]); File.WriteAllText("/sys/class/gpio/gpio26/value", args[0]); } } }
This is obviously not an example of clean code – it’s really just to clarify how to use .NET code to interact with the Ubuntu mechanism to control the GPIO pins.
I can compile this code in VS2017, and then from a command prompt I can run the command below to publish the code.
dotnet publish -r ubuntu.16.04-arm
This command publishes to the “\GpioSwitch\bin\Debug\netcoreapp2.0\ubuntu.16.04-arm\publish” directory. Now I can use pscp to move this compiled C# code to my Raspberry Pi 3 (as described in this post) – first I make a project directory on my Raspberry Pi 3 using the command below:
mkdir /home/ubuntu/GpioSwitch
Then I run the command below from the Windows machine that I build the GpioSwitch project on to move it from the Windows machine to the Raspberry Pi 3 (at 192.168.1.110).
pscp -r * ubuntu@192.168.1.110:/home/ubuntu/GpioSwitch
Once the project files are transferred to my Raspberry Pi 3, I change the permissions of the files in this directory to allow them to be executed as root using the command:
sudo chmod u+x,o+x *
Now I can run the command below to switch on an LED connected to Pin 26
sudo /home/ubuntu/GpioSwitch/GpioSwitch 1
And I can run the command below to turn it off again.
sudo /home/ubuntu/GpioSwitch/GpioSwitch 0
Hopefully this is useful to anyone wondering how to control GPIO pins on the Pi 3 with .NET Core. | https://jeremylindsayni.wordpress.com/2017/04/05/turning-gpio-pins-high-and-low-on-a-raspberry-pi-3-using-net-core-2-and-ubuntu/ | CC-MAIN-2017-26 | refinedweb | 789 | 60.14 |
I want to use top box to press down the scattered particles until the particles all be compressed to the bottom of the box. Then, the particles and top box should stop when they firmly fit right at the bottom of the box
And here are some difficulty I have faced;
The particles don’t stop when they all pack at the bottom but rather pop out or break throughout of the box, the top box itself also go out of the wall.
And here is my question;
Are there any function key to make top box stop when the particles is tightly packed at the bottom of the box, how?
Are there any way to stop particles poping out of the box, how?
this is video :
https:/
This is my script :
from yade import pack
O.materials.
# create rectangular box from boxes (maybe there is some library function, but I did not find it quickly)
cx,cy,cz = .5,.5,.5 # center of the box
dx,dy,dz = .5,.5,.5 # half-dimensions of the box
t = 0.025 # half-thickness of walls
topx,topy = 0.2, 0.3 # top box half-dimensions
left = box((cx-
right = box((cx+
front = box((cx,
back = box((cx,
bottom = box((cx,
top = box((cx,
O.bodies.
sp=pack.
# generate randomly spheres with uniform radius distribution
sp.makeCloud(
# add the sphere pack to the simulation
sp.toSimulation()
O.engines=[
ForceResetter(),
InsertionSortCo
InteractionLoop(
[Ig2_Sphere_
[Ip2_FrictMat_
[Law2_ScGeom_
),
NewtonIntegrato
]
O.dt=.5*
top.state.
Question information
- Language:
- English Edit question
- Status:
- Answered
- For:
- Yade Edit question
- Assignee:
- No assignee Edit question
- Last query:
- 2020-03-27
- Last reply:
- 2020-03-28
Dear jan ,
from this video : https:/
Before the particles pop out of all the box, the particles reach its compression peak point then pop out. I want to stop top box before the particles pop out, Do you have any idea how to stop top box?
Dear jan,
so suppose I want compaction of the particles at it’s most tightest stage which volume equal to 1.0*1.0*1.0. How to do it ?
> Do you have any idea how to stop top box?
See answer #1
>> To make the box step, just assign it zero velocity:
>> top.state.vel = Vector3.Zero
> I want compaction ... at ... stage which volume equal to 1.0*1.0*1.0. How to do it ?
use e.g. PyRunner:
###
O.engines = [
...
PyRunner(
]
def stopBoxIfCompac
area = ...
height = ...
volume = area * height
if volume < 1.0*1.0*1.0:
top.state.vel = Vector3.Zero
O.pause() # ?
###
cheers
Jan
Hi,
> Are there any function key to make top box stop when the particles is tightly packed at the bottom of the box, how?
there are several approaches, depending on your specific definition of what "tightly packed" is, e.g.:
- you know desired packing fraction (the resulting box volume), so you can a priori tell when to stop the top box
- based on unbalancedForce, kinetic energy, whatever.. checking it periodically and stop when the desired state is reached
To make the box step, just assign it zero velocity:
top.state.vel = Vector3.Zero
> Are there any way to stop particles poping out of the box, how?
- increase stiffness of the box (use another material for them)
- or stop it before it pushes particles away (see above)
cheers
Jan | https://answers.launchpad.net/yade/+question/689407 | CC-MAIN-2020-40 | refinedweb | 557 | 63.29 |
CRM for a small outgoing call center and sales teams
Budget $250-750 USD
I need a web based CRM for a small call center. the basic functionality is as follows:
ADMIN:
import and manage contact lists (from xls or csv). enter expiry date for contacts (after which they cannot be contacted). note: import function should check for duplicates and report them if any.
prioritise lists or contact groups or individual contacts
manually assign individual contact to users
manage users
statistics
AGENT:
simple screen which shows next number to dial and report status / schedule next call / enter information from client. agent should also have an option to search for a contact based on phone number
CC MANAGER:
statistics
prioritisation
manage users
SALES MANAGER
view only contacts based on specified criteria
assign them to sales agents
SALES Agent
view / edit contacts
ammend contact information
ammend status
the application should be optimised for both PCs and mobile. android app optional.
post-development support required
60 freelancere byder i gennemsnit $651 på dette job
Hello. I can do your task. About me: — 9+ year of experience. — Any tasks — Improve your ideas
Hello. Nice to meet you. CRM(Customer Relationship Management) I know it and Have experience when I worked at the company. Let's discuss more via chat. Regards, Zhang.S | https://www.dk.freelancer.com/projects/android/crm-for-small-outgoing-call/ | CC-MAIN-2019-47 | refinedweb | 218 | 56.05 |
Hello Friends, In this tutorial we are going to learn Events in C#. Events are members of the class that is declared in the class and raised by that class
What are Events?
Events are members of the class that is declared in the class and raised by that class. The Events are declared in the class and associated with the event handlers using the delegates. Events and delegates are tightly coupled because event handling needs a delegate for the invocation of events. Events use the publisher-subscriber model.
Publisher:
A publisher is a class that contains the definition of the event and delegate. The publisher class object is responsible to invoke the event and notifies to other objects.
Subscriber:
A Subscriber is a class that is responsible to provide event handler to the event class.
The delegate in the publisher class invokes the method (event handler) of the subscriber class.
So, In short, the class that raises the event is called publisher class and that receives and
provides a handler for the event is called the subscriber.
Declaring Events:
To Declare an Event inside a Publisher class first we need to declare a delegate type for that event. For Example.
public delegate void MyDelegate; public event MyDelegate evtMyEvent;
Example of Events:
Let’s create an example of Events. Suppose I need to get Employee details Like Name, Address, and Age where Age of Employee should be greater than 18. If the age of Employee is less than 18 then a message should be raised that “You are not eligible to proceed”. We can achieve this requirement using Events.
Create a Console Application called EventDemo.
Write the following code in Program.cs file.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EventDemo { class Program { static void Main(string[] args) { Employee objEmployee = new Employee(); objEmployee.evtValidateAge += new Employee.delValidateAge(AgeValidationMessage); objEmployee.GetEmployeeDetails(); Console.ReadLine(); } public static void AgeValidationMessage(int iAge) { Console.WriteLine("You are not eligible to proceed"); } } public class Employee { public delegate void delValidateAge(int iAge ); public event delValidateAge evtValidateAge; public void GetEmployeeDetails() { Console.WriteLine("Enter Name of Employee"); string sName = Console.ReadLine(); Console.WriteLine("Enter Address of Employee"); string sAddress = Console.ReadLine(); Console.WriteLine("Enter Age of Employee"); int iAge = Convert.ToInt32(Console.ReadLine()); if (iAge < 18 && evtValidateAge != null) evtValidateAge(iAge); else { Console.WriteLine("Welcome {0}", sName); } } } }
In the above program, you can see have declared a delegate delValidateAge that accepts an Age Parameter. In GetEmployeeDetails method we are accepting the Details for the Employee where if the Employee Age is less than 18 the event will be raised.
In the main method, we have associate Deleage with the Event using the following code.
Employee objEmployee = new Employee(); objEmployee.evtValidateAge += new Employee.delValidateAge(AgeValidationMessage);
The Delegate delValidateAge accepts AgeValidationMessage as a parameter.
Now run the application look over the output window.
View More:
Conclusion:
I hope you understand the concept of Events in C#. I would appreciate your Feedback, Comments, and Suggestions.
Thank You. | http://debugonweb.com/2017/12/24/events/ | CC-MAIN-2018-26 | refinedweb | 504 | 51.14 |
How to count the number of commas in a given string in Java
In this tutorial, we will learn how to count the number of commas in the given string in Java.
Now we know that in Java, a string is a combination of alphabets, numbers, special character(like “,” “.” “@” “=” “+” etc.,) alpha-numerics etc., therefore a user can declare any combination of strings in Java
A string is a user-defined combination of the above-mentioned types whereas a character in Java is only a single character i.e user can provide only single character at a time.
Here we want to count the number of commas in a string in Java
Let us understand through a simple example:
let a String s =”one,two,three,alphabet,123@gmail,.com,+code”
we can easily count the number of commas in the given above string.
The number of commas in the above string is: six
Hence we counted the number of commas and we are declaring them. Similarly, this can be achieved in Java as well.
Let us understand it through a Java program:
Java program to count the number of commas in String:
public class Main { public static void main(String args[]) { String s = "one,two,three,alphabet,123@gmail,.com,+code";//user can give any combination int commas = 0; for(int i=0;i<s.length();i++) { if(s.charAt(i)==',') { commas++; } System.out.println(s + "has" + commas + "commas"); } } }
output: one,two,three,alphabet,123@gmail,.com, code has 6 commas
So here we have declared seven strings which are separated by six commas and in order to print the output we have used iteration method i.e., we used “for loop” this for loop helps the user to iterate the values until the user get desired output and we have declared an “if” condition checks whether the given conditions are true or false.
Here “s.length” helps the user to get the number of commas in the given string
Here “s.charAt” will count the number of commas in the above-mentioned program.
Note: Here counting the number of characters can be done in the following ways: iteration, split method, replace the keyword, match the keyword.
Iteration is the most commonly used method to find the number of characters in a string in Java. | https://www.codespeedy.com/count-the-number-of-commas-in-a-string-in-java/ | CC-MAIN-2020-50 | refinedweb | 385 | 60.65 |
Using the same hardware design as in previous post, we can change the software part to a more efficient event driven approach. First, setup the GPIO pin (GPIO 42 in this example) as input:
echo 42 > /sys/class/gpio/export
echo in > /sys/class/gpio/gpio42/direction
echo falling > /sys/class/gpio/gpio42/edge
Note that on UDOO, GPIO pins can be set to trigger interrupt when the value change. Here, we set the "edge" as "falling" to indicate that we want to be notified when the input change from 1 to 0. You can also set it as "rising" or "both" to suit your needs. You can also change the value in the file "active_low" to reverse the order. See the Sysfs document for details.
With the GPIO pin setup properly, we can use a Python script to wait for input using Linux epoll(7):
import sys
import os
import select
import time
import datetime
if len(sys.argv) < 2:
print('Missing gpio')
sys.exit(1)
fd = None
e = None
ignore = True
gpio = sys.argv[1]
try:
fd = os.open("/sys/class/gpio/gpio%s/value" % gpio, os.O_RDONLY)
e = select.epoll()
e.register(fd, select.EPOLLIN | select.EPOLLET)
while True:
events = e.poll()
if not ignore:
for fd, event_type in events:
print(datetime.datetime.now().isoformat() + " event_type " + str(event_type) + " detected on " + str(fd))
break
ignore = False
finally:
if e is not None:
e.close()
if fd is not None:
os.close(fd)
We register the GPIO pin with a epoll object. Since we want to wait till the value change from 1 to 0, we used the flag select.EPOLLET to use edge-triggered instead of the default level-triggered mechanism. Then the program enters an infinite loop to wait for the value change.
Note that the first trigger is ignored as epoll returns immediately on the first call.
Also, you can register multiple GPIO pins with the epoll object. Check the (file descriptor, event type) tuple returned by poll() and you can handle the case differently.
The whole Python script will not return until the GPIO input changed from 1 to 0. To use it to trigger a shutdown, create a shell script similar to the following to setup the GPIO pin and wait for the Python script to return. Run the shell script on every reboot using systemd. For details, refer to the previous post.
#!/bin/sh
GPIO=42
echo $GPIO > /sys/class/gpio/export
echo in > /sys/class/gpio/gpio$GPIO/direction
echo falling > /sys/class/gpio/gpio$GPIO/edge
/usr/bin/python /root/scripts/pwrbtncheck/poll.py $GPIO
if [ $? = 0 ]
then
echo "Shutdown button pressed"
/usr/bin/sync; /usr/bin/sync; /usr/bin/shutdown -h now
fi
Yes. 42 is "The Answer to the Ultimate Question of Life, The Universe, and Everything" :) | https://www.clarenceho.net/2016/05/event-driven-gpio-with-python-on-udoo.html | CC-MAIN-2021-25 | refinedweb | 468 | 66.94 |
After struggling with this problem for a week, I think I know why I'm having trouble. I don't, however, know how to fix it, so I want to troll this list one more time. First, the problem statement: I can run VisAD as an applet, and it works beautifully the first time I hit the page. If I go to another page and then return to the page with the VisAD applet, then my applet appears to hang, no matter how simple I make it. Here's my theory about what's going wrong: Under IE 5.0, using the Java plug-in 1.3, the JVM loads my applet and visad.jar the first time they're needed. The next time around, the browser calls Class.newInstance() (which performs a shallow copy) to generate a new version of my applet class, while keeping the instantiations of any classes that were loaded from the visad.jar. I know that VisAD is still loaded, since I can call ScalarMap.getScalarName("myscalar"), for example. The instance variables in my applet are all new, though my static variables are still the same. Now the trouble starts. That first instance of my class is gone for good, so the garbage collector can start picking it to pieces, and since there are no explicit references to the information stored in VisAD's namespace, I think that the memory VisAD has allocated starts to be picked apart as well. The classloader doesn't bother to reload visad.jar from scratch, since it knows that it loaded visad.jar once already, and assumes that I've kept explicit pointers to any memory I want saved. So now I'm in deep trouble, as I stand on instances of VisAD classes that are dissolving beneath me. Note: I think this IS NOT a VisAD bug (I'd call it instead a browser and/or Java plug-in bug). There may, however, be aspects of VisAD that would allow me to get around the problem. If, for example, I could get a pointer to the root of the data structure that VisAD uses internally, then I could set a static variable within my program to point to it, and everything would be protected from the GC, and I could use the variables I created the first time through. Or, if there were a way for me to tell VisAD to start fresh and give me all new variables, then, while loading would be slower, at least everything would run reliably. Alternatively, if there were a way to tell VisAD to unload everything it has allocated, then that would do it too. Maybe subclassing the classLoader to make it load new versions instead of referencing old versions would work, but I'm not certain. Don't bother suggesting that I simply make every VisAD variable that I use static, since I've tried and that approach doesn't work (perhaps implying that my solution #1 would fail too?). I imagine that there are other approaches, but since I don't know how VisAD stores its internal variables I don't have any other ideas right now. I would really like to use VisAD in our front end, and I feel as if I'm 95% of the way there, with only this last big problem standing in my way. Is there anybody who can shed some light on my troubles? Please contact me offline if you're interested and want to see my source, or if I could perform any work which might then be folded back into somebody else's project (as well as my own). Ben balexander@xxxxxxxxxx 781-994-0428
visadlist information:
visadlist
visadarchives: | https://www.unidata.ucar.edu/mailing_lists/archives/visad/2000/msg00471.html | CC-MAIN-2019-26 | refinedweb | 619 | 77.67 |
#include <hallo.h> Neil Spring wrote on Sat Sep 01, 2001 um 06:39:58PM: > > > As David noted, I'm in favor of turning ECN off-as-default. Good. The problem - it is on by default in our precompiled kernel-image packages. To disable (by default), you have to remove ECN support from kernel or either patch the kernel to make int off-as-default (*) or put in in the template of sysctl.conf. (*) I doubt Herbert Xu would like such modifications. > My point is still that it should be dirt simple to turn it > on again. If you're going to quote the social contract, Okay, why not just put the line into sysctl.conf and present a big warning in the baseconfig? > then you should see the logic in respecting the user's > wishes, and not trying to disable what they've knowingly > enabled in the kernel configuration. Look, we have in general two parts of users: - "administrator" kind, people that _may_ need ECN (but mostly don't though). We can expect them to RTFM and remove the hook from sysctl.conf after reading the baseconfig message. - the "users" - the majority. People that do as less RTFM as possible, that do not need ECN and the should not be bothered with such problems. This people would ignore the warning and have an easier life without getting in touch with sysctl.conf. Is my proposal acceptable now? Gruss/Regards, Eduard. -- Der Wahnsinn hat Methode!
Attachment:
pgp4G3fNM3lEo.pgp
Description: PGP signature | https://lists.debian.org/debian-devel/2001/09/msg00126.html | CC-MAIN-2017-04 | refinedweb | 251 | 74.59 |
Search: Search took 0.02 seconds.
- 27 Feb 2013 2:09 AM
- Replies
- 109
- Views
- 56,768
Hi and thanks for your reply!
Its correct, this only creates my base namespace (com.foo.internal), its when i want to create my app specific namespace that i change ".sencha/app/sencha.cfg"...
- 24 Feb 2013 9:59 AM
- Replies
- 109
- Views
- 56,768
Hi,
Im building apps used in different scenarios (chocking) and uses different namespace as to keep track of who and what the app is used for/by.
For example: ...
- 22 Feb 2013 6:05 AM
- Replies
- 109
- Views
- 56,768
Hi Brice and thanks for an excellent utility,
When using Phonegap 2.4.0 the javascript file is not located in
/lib/ios/ but in
/lib/ios/CordovaLib/
Small fix is to copy the file ...
- 15 Aug 2012 11:29 AM
Found the solution, Phonegap raises an "resume" event.
//Robert
- 13 Aug 2012 10:27 PM
Hi digeridoopoo and thanks for your answer.
Been trying to catch the painted event as well without any luck.
When debugging using XCode when closing the app an event is triggered perhaps...
- 13 Aug 2012 12:49 AM
Hi,
Ive been trying to listen for some sort of event as the application becomes active, initially loaded or when been "minimized" and reopened.
Should i listen for some like "activate" on...
- 8 Jun 2012 1:38 AM
After some fiddling this is what i've come up with.
First of all i've decided to go with the Navigation View.
In the navigation view i added a listener to the push event, fired one event before...
- 7 Jun 2012 11:45 AM
Thanks for your reply aatiis but i can´t get it to work, same result.
The show event in order main does not load my order list.
this.getView().setActiveItem(this.getList());
Could...
- 7 Jun 2012 1:15 AM
Hi,
For the last two days i´ve trying to get this to work.
Have tried with both NavigationView and plain Panels but without any luck!
First of all, i´ve not made up my mind if im going for...
- 1 Mar 2012 3:23 AM
- Replies
- 5
- Views
- 3,788
Fixed it.
Thanks anyway!
//Robert
- 1 Mar 2012 1:39 AM
- Replies
- 5
- Views
- 3,788
Hi,
I´ve been trying for a while to create a wrapper for CloudMade Leaflet API and would be glad for some directions.
This is what im trying to do
Ext.ux.Leaflet
...
- 4 Jan 2012 6:28 AM
- Replies
- 2
- Views
- 1,306
Thanks for your response.
Exactly.
I´ve tried and remove the record by using a lot of different approaches
.setData(null)
.setValue('')
.setValue(0)
.setValue(null)
- 4 Jan 2012 3:24 AM
- Replies
- 2
- Views
- 1,306
Hi,
I´ve been trying for a while now to get this working.
My application contains two models/stores, one REST proxy (items) and one memory proxy (locations).
User search for items, a nested...
Results 1 to 13 of 13 | https://www.sencha.com/forum/search.php?s=fb6bc6ba3bdd7a4b8cdb861c11e06b62&searchid=13303268 | CC-MAIN-2015-48 | refinedweb | 506 | 81.43 |
Humbled...
string:
ref
// ----.
int
float
datetime
enum
struct
And now on to...
// ---- Declaration -----------------------------
public class MyClass
{
public string StrTag;
}
// ----();
Data.StrTag = "AAA";
SetMyClass(Data);
// Data.StrTag is now "BBB"
SetMyClass(ref Data);
// Data.StrTag is now "CCC"
}…i.e., you can make it refer to a completely different object. Inside the function, you can do: myClass = new MyClass() and the old object will be garbage collected and the new object will be returned to the caller.
myClass = new MyClass()
That ends the review. Now let's look at passing strings as parameters.
Strings are reference types. So when you pass a String to a function, you do not need the ref keyword to change the string. Right? Wrong. Wrong, wrong, wrong.
String.
// ---- Functions ----------------------------?
string
I spent hours unsuccessfully researching this anomaly until finally, I had a Eureka moment:
This code:();
myClass.StrTag = "BBB";
}
Now when you call the SetMyClass function without using ref, the parameter is unchanged... just like the string example.
SetMyClass. | https://www.codeproject.com/articles/144771/passing-strings-by-ref.aspx | CC-MAIN-2017-04 | refinedweb | 163 | 69.48 |
From: Darin Adler (darin_at_[hidden])
Date: 2000-07-25 20:43:38
on 7/25/00 2:22 AM, Christian Bach at bach_at_[hidden] wrote:
> i have encountered a problem concerning operator != in the boost
> shared_ptr template.
> it collides with the standard library defined != operator of stl_relops
> when used in the following manner:
I believe this problem is due to a non-standard-conforming library
implementatoin. The relops template functions should only be searched if you
do "using namespace std::rel_ops;" or "using std::rel_ops::operator !=;".
> when commenting out the lines
>
> template<typename T, typename U>
> inline bool operator!=(const shared_ptr<T>& a, const shared_ptr<U>& b)
> { return a.get() != b.get(); }
>
> in the shared_ptr template everthing seems to work just fine (hopefully !)
It's OK to make that change locally as a workaround for the problem, but not
in the master copy of the header.
> what do you think ? is it safe commenting out the above lines ?
Besides the fact that they need to be included explicitly on
standard-conforming compiler/libraries, there are at least two problems with
the std::rel_ops function templates.
1) Since they are not in same namespace as the shared_ptr class
templates, Koenig lookup does not guarantee that they will be found.
2) They work only if the left and right are the same class, so you can't
compare shared_ptr<Derived> with shared_ptr<Base> like you can with the
shared_ptr versoins.
> do we need those lines ? or are there other possibilities to circumvent
> the problem ?
I'm not sure why your library includes the relops function templates
unconditionally, nor am I sure how the multiple applicable function
templates interact in your configuration or even how they are suppose to
interact in a standard-conforming implementation.
Perhaps we can do some conditional compilation to omit the != function
template from smart_ptr.hpp for your broken compiler/library.
-- Darin
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/2000/07/4068.php | CC-MAIN-2019-22 | refinedweb | 335 | 58.89 |
hunt-reflection 0.2.1
Extensions to runtime reflection in D. It's forked from Mihail-K's Witchcraft originally.
To use this package, run the following command in your project's root directory:
Manual usage
Put the following dependency into your project's dependences section:
Witchcraft - Runtime Reflection is Magic
Extensions to runtime reflection in D. It's forked from Mihail-K's Witchcraft originally.
Witchcraft provides enhanced runtime reflection facilities for D classes. It provides a means to interact with fields, functions, constructors, classes, and user-defined attributes at runtime (features D is sadly lacking). All of this happens through a simple and familiar API inspired by Java's
java.reflect package.
Mix in some Witchcraft
Start with a simple class, mix in some Witchcraft,
import witchcraft; class User { mixin Witchcraft; string username; string password; this(string username, string password) { this.username = username; this.password = password; } }
And now you have some amazing new runtime reflection powers to play with.
void main() { Class c = User.metaof; // ... or new User().getMetaType; // Create a new user object, User user = cast(User) c.create; // Iterate over fields . . . foreach(field; c.getFields) { // Get value on instance 'user' field.get(user).writeln; } }
Aggressive Mode!
Witchcraft also comes with an option to enable 'Aggressive Mode'. Normally, only types that have
mixin Witchcraft; can be reflected on, and any types that these may reference (ie. A method return type) must also have Witchcraft in to support reflection.
In Aggressive Mode, Witchcraft will generate meta information for all types that are referenced reflectively (and any types that those types may reference, and so on...). However, for any types that don't mixin Witchcraft, only public members will be accessible. You can test if an element is accessible with the
isAccessible property.
Fields, Methods, and Constructors
Witchcraft grants runtime access to all fields, methods, and constructors of any type it is mixed into. Fields and methods alike are easily accessible en-masse (returned as an array), or individually given by name. Methods and constructors are both also accessible based on their overloads.
// Access to fields and methods. Field[] fields = c.getFields; Method[] method = c.getMethods; // Access to a field by name. Field field = c.getField("username"); // Access all overloads of a method by name. Method[] overloads = c.getMethods("updatePassword"); // Access the updateEmail(string) method. Method method = c.getMethod!(string)("updatePassword");
Once you have your fields and methods, you are free to read, write, and call them. They also provide some useful properties like their types, attributes, parameters types, declaring types, etc. This includes useful properties like
isStatic, to check if a method is static or bound to and instance of a class.
// Fetch a variant holding the value of user.email Variant email = c.getField("email").get(user); // Or... Use a template argument to convert the result. string email = as c.getField("email").get!(string)(user); // And now call user.updateEmail(email) c.getMethod!(string)("updatePassword").invoke(user, email); // Or... Use a TypeInfo object instead of template argument. c.getMethod("updatePassword", typeid(string)).invoke(user, email);
Templates not Required
Witchcraft provides templated methods for convenience for every method that might accept or return a
Variant, or any method that accepts D's
TypeInfo or Witchcraft's
Type objects. For example, if you were looking for a constructor that might accept behave like
this(string, string),
// You'd have the option using templates, Constructor ctor = c.getConstructor!(string, string); // Or you can find it with runtime parameters. Constructor ctor = c.getConstructor(typeid(string), typeid(string));
Similarly, for returned values, you could do,
// With templates, you can get a User object, User user = ctor.create!(User)("John Smith", "secret"); // Without templates, Variants go in, Variants come out. Variant user = ctor.create(Variant("John Smith"), Variant("secret"));
Attributes
Witchcraft can also do some neat magic with User-Defined Attributes. You can inspect and access UDAs on any field, method, constructor, or type that has reflective capabilities. (That is to say, any type that has
mixin Witchcraft;, or, keep reading for 'Aggressive Mode'!) Consider,
struct Column { string name; } struct User { mixin Witchcraft; @Column string username; @Column("pass_word") string password; }
Witchcraft breaks up attributes into 2 types; Type attributes and Expression attributes. Expression attributes are any attributes that can produce a value at runtime, whereas Type attributes are attributes that cannot. Essentially,
Struct s = User.metaof; // @Column on username cannot produce a value; it's a Type attribute. Attribute uAttr = s.getField("username").getAttributes!(Column)[0]; assert(uAttr.isType == true); // @Column("pass_word") produces a value at runtime; it's an Expression attribute. Attribute pAttr = s.getField("password").getAttributes!(Column)[0]; assert(pAttr.isExpression == true);
getAttributes may also be called without a parameter to get all attributes on an element, or it can be given either a D
TypeInfo or Witchcraft
Type object in place of a template argument.
Caveats
- Every class that needs reflective capabilities must mixin
Witchcraft. This includes children of classes that already do!
- Witchcraft reflection completely ignores protection attributes. Private fields and functions are accessible from everywhere through reflection. (although this may be a benefit in some cases!)
- Aggressive Mode is very aggressive! Compile times can take quite a while since meta information will be constructed for every reachable type through any type that is referenced reflectively. (Fields, return types, parameter types, attributes, etc.)
License
MIT
- Registered by zoujiaqing
- 0.2.1 released 3 years ago
- huntlabs/hunt-reflection
- MIT
- Authors:
-
- Dependencies:
- none
- Versions:
- Show all 3 versions
- Download Stats:
0 downloads today
0 downloads this week
1 downloads this month
59 downloads total
- Score:
- 0.7
- Short URL:
- hunt-reflection.dub.pm | https://code.dlang.org/packages/hunt-reflection | CC-MAIN-2022-05 | refinedweb | 933 | 51.55 |
Forum:Deletion policy, again
From Uncyclopedia, the content-free encyclopedia
I hate to do this, but I have an issue.
Recently, I was looking over the recent changes, and noticed "swiss navy." I thought this was funny, so I decided to try editing it. I was surprised to find that when my edit was done, the only content in the article was my edit, and not the material already there. I thought I'd accidentally overwritten the previous material, but in fact what had happened was another user (probably an admin) had summarily deleted the article while I was editing it. And then, predictably, they deleted my edit as well.
So, no NRV, no VFD, no QVFD, just into the memory hole. Last time I checked, it's not Forest Fire Week. I'd like to have a serious policy discussion on this, because it's one thing to tag and later delete abandoned stubs, it's quite another to wipe them out summarily seconds after their creation, while other people are trying to edit them into articles.
--RudolfRadna 21:53, 27 April 2006 (UTC)
- Content was:
(Deleted revision as of 27 April 2006)
Not surprisingly for an island nation, Switzerland has a long and proud maritime tradition.
==Ships== *the S. S. Crouton, which patrols the Sea of Fondue
{{stub}}
(Deleted revision as of 27 April 2006)
==Knife==
The swiss navy knife is just a handle with no knives since switzerland is a landlocked:04, 27 April 2006 (UTC)
Right. Is it site policy to delete stubs like this that clearly have comedic value, instead of using NRV? I thought Wikis were supposed to be based on consensus, not anarchy, which is what a lot of users running around deleting things is.
--RudolfRadna 22:06, 27 April 2006 (UTC)
- There aren't a lot of users running around deleting things, theres a lot of admins doing it. :) To be honest I would have probably deleted it too. The idea behind Uncyclopedia is to make spoof encyclopedic style articles rather than oneliners. If something has promise, and it can only come down to a judgement call, then we'll NRV it. We have so many new entries like this every minute of every hour of every day that if we didn't just huff mercilessly the site would be full of cruft and we'd all need big wellies..... -- Sir Mhaille
(talk to me)
- Were I an admin, I too would have deleted those articles. Why? Because they are so short, that even if the author got a fantastic idea and came back to add it, rewriting what was deleted would be really easy for them to do. And aswell, niether of the revisions above are funny. --Brigadier General Sir Zombiebaron 22:26, 27 April 2006 (UTC)
- It is, however, not your issue to judge the fun factor of a particular article. Every article has been written by somebody investing their time and ideas into it. Even if in Uncyclopedia the standards are slightly different and writings ofter hastier, the articles that seem lacking in content should be rather enhanced than deleted. This should be clear to a (wiki-)thinking person. --Sigmundur
- Actually, it is the job of admins to ultimately determine whether the quality of an article is acceptable. As for clear wikithinking, it is generally not possible to enhance a stub on Uncyclopedia; Wikipedia stubs are easily enhanced because there is one right answer but here there isn't. On Uncyclopedia, to expand an article, one must expand on the existing joke so when a mediocre one-liner exists, the article has effectively been monopolized and drained of potential. Think of it like a forest fire that destroys old-growth trees and underbrush creating potential for fresh foliage. --Sir gwax (talk) 15:17, 1 November 2006 (UTC)
I'm going to add some advise to the how to page on this (if I can find one), because what's happening here is n00bs are falling into a trap where they create a page not knowing any better what will happen, and it tends to be short, because we're not all the most creative fertile literary minds, and it's all getting zapped to oblivion and obviously this isn't working.
--RudolfRadna 22:36, 27 April 2006 (UTC)
- If you want to try to save it I've put a copy at User:RudolfRadna/Swiss Navy Knife for your viewing pleasure. If you can expand it into a decent article feel free to move it back once you have)
- Yah, thats the best thing to do...I do it...yah...--Brigadier General Sir Zombiebaron 22:43, 27 April 2006 (UTC)
I wrote a n00b how to pretty much advocating that: Uncyclopedia:How To Get Started Editing. Any comments? I think that this is a good outcome in terms of policy, just try to educate the n00bs more about the facts of uncyclopedia life . . . .
--RudolfRadna 22:47, 27 April 2006 (UTC)
And thanks for the sub-page, I'd actually already put it under my NRV rescue page. Subdividing it is a good idea, but I was refraining from doing that because I was concerned I'd eat up server space by making multiple subpages or something. --RudolfRadna 22:49, 27 April 2006 (UTC)
- Nah, screw it.....fill yer boots! --, thanks for the advice. About the howto page, I'm going to see if I can link to the howto page in such a way that people who want to can find it, but I don't know enough about the site structure to realize the best way to do it immediately, so I'll think it over and work it out when I figure out what to do. --RudolfRadna 23:10, 27 April 2006 (UTC)
- I'd just like to take a second and let you know I fully support a page telling n00bs how to keep their content alive at Uncyclopedia. It's very true that
adminspeople will kill a sick, weak article on sight regardless of it's potential humor content, 9 times out of 10. The main problem you'll run into is that no n00bs will read a "how to" get started policy, 9 times out of 10, but I think we should have a clear path to show them, just the same. That said, if this is your first article, read the Beginner's Guide first. Be funny and not just stupid. Thank you.--<<
>> 23:25, 27 April 2006 (UTC)
- I'm glad you think the page is a worthy addition, and I'd appreciate any advice on how to try to give n00bs an easy way to find it. Maybe where this belongs is in the beginner's guide (the HowTo page), but that page is protected. Any thoughts on how to approach this? Should I create a new VD forum about changing the beginner's guide to include the content of the HowTo page somewhere? Or just link to the HowTo page from somplace else? --RudolfRadna 23:27, 27 April 2006 (UTC)
And it's not my first article, but it may be my first article that won't eventually be deleted, lol. I think some aspects are funny in a weird way, some of the similes, maybe. --RudolfRadna 23:30, 27 April 2006 (UTC)
- Actually, I was referring to the link that is between the edit space and the "save page" link, but I didn't realize those pages were protected. That would make sense. Those are the most visible places on the site, and highlighting that no one looks at them. That's all I was saying with that sentence. Sorry, I meant no offense.--<<
>> 23:34, 27 April 2006 (UTC)
- None taken. I make a deliberate effort to take nothing anyone says here personally, even if it is deliberately directed against me in an offensive way. It's just not worth getting angry at a person you don't even really know. Of course the site basics are still vital, but they're about how to write contentwise. This is more about how to develop ideas without having your work deleted every step of the way by using your userpage instead of just going into the main space. Different issue, and I think the way this has emerged, its an important one. --RudolfRadna 03:35, 28 April 2006 (UTC)
I found a way, I linked it from [[1]]. That should be good enough so at least people who want to read it can find it. --RudolfRadna 03:42, 28 April 2006 (UTC)
I was able to do this because the 'broken up' version of the beginner's guide was unprotected for some reason. The one big page version of the guide was protected, so I couldn't link from there. This will have to do, at least for now. Anyone here who wants to mess around with this if they think they can make it work better is free to try.
Btw, the text I added was "For some unofficial, but useful, advice on how to develop ideas on uncyclopedia without having to worry about your work in progress being deleted, check out Uncyclopedia:How To Get Started Editing"
--RudolfRadna 03:48, 28 April 2006 (UTC)
- I've also been trying to give some advice to people who are having problems, so now that this "how to" page is up, I'm just going to refer them there, so even if people don't browse to it en masse, it has a reason to exist as a time-saving device. --RudolfRadna 13:57, 28 April 2006 (UTC)
- Made some improvements, mainly adding the HowTo template and doing a better job explaining how to register and how to create a user page. I know that stretched the subject of the how to a little bit, but it seemed important because the message of the page was to register and create a user page to compose articles on, and I realized that a lot of n00bs probably don't know how to do those things, and the easiest way to deal with it was to just add it to the page. Besides, since registering and having a user page is part of the article creation process as recommended by this page, registering and creating a user page is properly part of this particular "how to" piece, since they're steps in the process. --RudolfRadna 14:38, 28 April 2006 (UTC)
How about we start a conversation on UnMeta about possibly starting a seperate wiki for one-liners. Those can be funny sometimes. --Nerd42eMailTalkUnMetaWPediah2g2 14:34, 28 April 2006 (UTC)
- I don't know what UnMeta is, but you can start one on the forum by creating an article called "Forum:Let's start a seperate wiki for one-liners. Those can be funny sometimes" or something to that effect, and then putting the template
{{Forumheader|Village Dump}}at the top of the page so it shows up in the village dump index. --RudolfRadna 14:39, 28 April 2006 (UTC)
- Also, I'm not sure, but wouldn't that overlap with undictionary a bit? --RudolfRadna 14:41, 28 April 2006 (UTC)
- Yeah....thats essentially what UNDictionary)
- Does UNDictionary still exist? I never really tried looking for it. --RudolfRadna 14:52, 28 April 2006 (UTC)
And Nerd42, did you mean this: UnMeta Village Dump ? Or is it this one: Other UnMeta Village Dump (confusing) --RudolfRadna 16:33, 28 April 2006 (UTC)
Alright, sorry to come in so late, but our policy is that if something has close to one line, it's huffed on sight. Granted, some admins believe in Undictionary... and some will NRV. One line is not an encyclopedia entry, as Brad or so said. We are "Uncyclopedia" like in "encyclopedia." Encyclopedia Brittannica does not have any entries that are one line. That's just not good form. And trust me, stubs do not get expanded. Ever. Cause nobody cares. --KATIE!! 07:56, 29 April 2006 (UTC)
- Yes, but at least now there's a HowTo article that gets that message across to n00bs in an quick, easy to find, and clear way. That didn't exist before, to my knowledge. I'm referring to Uncyclopedia:How To Get Started Editing of course. --RudolfRadna 12:52, 29 April 2006 (UTC)
- Yep, perhaps letting newer users know how to create articles in their own namespace would make them take a bit more time over them before moving them to the 'main' Uncyc. May also help cut down on NRV'd articles, perhaps? --Hindleyite Talk 18:22, 29 April 2006 (UTC)
- That's the idea in a nutshell :D --RudolfRadna 22:51, 29 April 2006 (UTC)
- This is another situation where having a new user log would be useful (hint, hint, wikia) so we could place {{welcome}} on new users talk pages (BTW I'd add your howto it if it hasn't already).--The Right Honourable Maj Sir Elvis UmP KUN FIC MDA VFH Bur. CM and bars UGM F@H (Petition) 18:31, 1 May 2006 (UTC)
- I would encourage people to make whatever use of the HowTo article they see best. It's there to be useful. I was going to just mention it to people who might be interested in reading it on their talk pages, but that won't reach the ips who havn't registered. It's going to probably take more than this to communicate meaningfully with the ips that aren't vandals and really want to be involved. --Hrodulf 22:22, 1 May 2006 (UTC)
I think that the content of Uncyclopedia:How To Get Started Editing would be best improved by replacing it with, "Read and perform minor edits on existing articles for a while. After you're confident that you understand what passes for quality on Uncyclopedia, start making more substantial contributions. Eventually, if you feel you have the understanding and wit to compose a feature-worthy article, feel free to start a new article." --Sir gwax (talk) 19:39, 8 May 2006 (UTC)
- That would probably work better as another paragraph in the Beginner's Guide, rather than its own page. If as a policy issue, you don't want people to work on drafts on userpage subpages, which is the main thrust of the piece, feel free to take it down. The piece was just a response to what seems to be an ongoing problem with new users believing they can just drop an idea into the main space without developing it on the first try, which obviously isn't working. --Hrodulf 09:52, 9 May 2006 (UTC)
- I totally and utterly agree with rampant deletionism. I would much rather have admins who, instead of deleting an article and yell at you for "giving them a hard time" when you ask about it (tm)jtaylor1, would actually attempt to improve upon an article or at least put NRV on it. We must remember that all good articles were crappy one-liners and ideas at first. Swiss Navy Knife is a very promising-sounding atricle. If the joke of the landlocked country's navy was expanded upon, then it could even get featured. However, some rampant BURNiNATORs seem to think that if it isn't perfect the first five seconds it exists, then it will never be any good. Have you no patience? Flameviper12 20:03, 19 May 2006 (UTC)
- At the risk of getting caught in this discussion (which I haven't really followed up to now), I'd like to clarify something related to what Flameviper said. Uncyclopedia is not Wikipedia. The concept of gradually accumulating facts for an article, beginning with a stub and adding content until it's a fully fleshed-out article, is not always applicable here as it is at WP, because many of our articles are standalone comedy pieces from the get-go. Look at an article like an older version of George W. Bush - popular subjects often get terribly uneven and scattershot articles because people add sections irrelevant to the "idea" of the article, which isn't an issue on Wikipedia because their pages are not based on themes as ours often are. That is not to say that collaboration is discouraged - there have been excellent group articles in the past and there are benefits to collaboration even aside from article quality - but the fact is that many of our best articles were never bad one-liners. It's much harder to take a short article that someone else created and expand it into a hilarious page while staying true to the original idea than it is to build up a factual encyclopedia article. —rc (t) 00:21, 20 May 2006 (UTC)
- The version RC is referring to can be found at George Dubya Bush, though it has been fixed up from its ugliest stages.--<<
>> 00:34, 20 May 2006 (UTC)
- Yeah, I realized awhile ago after the fact that jtaylor1 wasn't an admin. I personally think the issue has been more or less resolved to my satisfaction via the HowTo page. This way if people follow the plan, they can develop articles, and the main space isn't cluttered with hundreds of stubs. Everybody wins. Except the donuts. --Hrodulf 02:17, 20 May 2006 (UTC) | http://uncyclopedia.wikia.com/wiki/Forum:Deletion_policy%2C_again | CC-MAIN-2015-48 | refinedweb | 2,893 | 66.88 |
Using the GIS¶
The
GIS object in the
gis module is the most important object when working with the ArcGIS API for Python.. This object becomes your entry point in your Python script when using the API.
To use the GIS object, import GIS from the
arcgis.gis module:
from arcgis.gis import GIS
To create the GIS object, we pass in the url and our login credentials as shown below:
gis = GIS("", "arcgis_python", "P@ssword123")
If connecting to an ArcGIS Enterprise in your premises, your URL becomes. Your GIS can support a number of authentication schemes, refer to this section of the guide to know how to authenticate your scripts and notebooks for various such schemes.
Below, we're connecting to ArcGIS Online (the default GIS used when the url is not provided) as an anonymous user:
gis = GIS()
Adding a '?' mark after an object and querying it brings up help for that object in the notebook:
gis?
The notebook provides intellisense and code-completion. Typing a dot after an object and hitting tab brings up a drop-down with its properties and methods:
Helper objects¶
The
GIS object provides helper objects to manage the GIS resources, i.e. the users, groups, content and datastores. These helper utilities are in the form of helper objects named:
users,
groups,
content and
datastore respectively. The helper utility for managing user roles named
roles is available as a property on the helper object
users.
Each such helper object has similar patterns of usage: there are methods to
get(),
search() and
create() the respective resources.
The prescribed programming pattern is to not create the GIS resources (user, group, item, role, datastore) directly using their constructor, but to access them through their corresponding helper objects described above.
Thus, to access a user, you would use the
users property of your
gis object which gives you an instance of
UserManager class. You would then call the
get() method of the
UserManager object and pass the user name of the user you are interested in.
user = gis.users.get('john.smith')
user
The resources are implemented as Python dictionaries. You can query for the resource properties using the
resource['property'] notation:
user['firstName']
'John'
The properties are also available as properties on the resource object, so you can use the dot notation to access them:
user.lastName
'Smith'
The resources provide methods to
update(),
delete() and use the object. The reminder of topics in this module talk in detail about using the various helper objects and resource objects.
map1 = gis.map("Palm Springs, CA") map1
We can search for content in our GIS. Let's search for Hiking Trails in the Palm Springs region. We do that by calling
gis.content.search() and for each web map or web layers that gets returned, we can display its rich representation within the notebook:
from IPython.display import display items = gis.content.search('Palm Springs Trails') for item in items: display(item)
We can then add the returned web layers to our map. To add the last layer returned above, we call the
add_layer() method and pass in the layer for Palm Springs Trail:
# Let us filter out the item with title 'Trails' that we want to add item_to_add = [temp_item for temp_item in items if temp_item.title == "Trails"] map1.add_layer(item_to_add[0])
The above cell updated the map widget, if you scroll to the top, you can notice a new trail layer being rendered on the map.
Feedback on this topic? | https://developers.arcgis.com/python/guide/using-the-gis/ | CC-MAIN-2021-17 | refinedweb | 583 | 61.77 |
Extend django-admin to create apps that are easier to set
Project description
This is a django app that trys to simplify using django. Currently it has features that do the following:
- An easy_app script that allows for creating new django projects that are set up with the djang0-easy-app functionality.
- A django-easy-app django app has the following functionality that simplify using django.
- The ability to specify the url routing using a new “route” attribute on django class based view classes. This akes it possible to write and use class based views without needing to understand regular expressions and seperately update the urls.py.
- Adds a starteasyapp command to manage.py to allow for easily creating additional django-easy-app enabled django apps.
Quickstart
Here are some steps for getting things going
Install django-easy-app
Once django-easy-app has been packaged it will be installable using pip as follows:
pip install django-easy-app
Set up a new django project
Create a new python project using the django_easy command like this:
django_easy startproject project_name app_name
Example:
$ django_easy startproject foo_project foo_app Creating easyapp named: foo_app $ tree foo_project foo_project ├── foo_app │ ├── admin.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── foo_project │ ├── __init__.py │ ├── __init__.pyc │ ├── settings.py │ ├── settings.pyc │ ├── urls.py │ └── wsgi.py └── manage.py 3 directories, 14 files
Create views
In the views.py file define a variable named “easydjango” and set the value to true.
Make sure each view that should be accessible from the web has a *route* attribute that contains the part of the url that should be associated with the view. This should not include any other part of the url.
So for example foo_app.view.ExampleView below has a route value of ‘’ which will cause it to be accessible at
from django.http import HttpResponse from django.views.generic import View easydjango = True class NameView(View): route = '' def get(self, request): name = request.GET.get('name', 'World!') return HttpResponse('Hello %s' % name)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/django-easy-app/ | CC-MAIN-2022-27 | refinedweb | 365 | 55.03 |
51194/how-to-install-and-use-myql-connector-in-python
You can use pip to search if the connector is already installed using following code -
$ pip search mysql-connector | grep --color mysql-connector-python
If it is not available then you can download it using following code -
$ pip install mysql-connector-python-rf
Once downloaded you can verify it by typing import mysql.connector. If there is no error displayed then you can use it.
it is a python sequency which stores ...READ MORE
Thread is the smallest unit of processing that ...READ MORE
You can use it to raise errors ...READ MORE
replace() is a method of <class 'str'> ...READ MORE
Sorted!!!! just found the solution,
1 - apparently ...READ MORE
connect mysql database with python
import MySQLdb
db = ...READ MORE
Very similar to mysqldb but better than ...READ MORE
If you are using Python 3.x then ...READ MORE
If you are using Anaconda then you ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/51194/how-to-install-and-use-myql-connector-in-python | CC-MAIN-2019-47 | refinedweb | 166 | 68.26 |
Related
Tutorial
Styling React Native ever used React Native, you probably realized it doesn’t use normal HTML & CSS like a web application. In this guide, we will discuss the differences. And one of the main differences you will see is everything is automatically styled based on Flexbox.
Now if you wanted, you could simply import the
styled-components library and use normal CSS like that. That is a great library and I would recommend it. But, if you want to get used to styling in a Native app, let’s see how to do that.
StyleSheet
The first thing to know about React Native styling, is to use the
StyleSheet component. Import it like this:
import { StyleSheet } from 'react-native';
After that, you can use it like this:
const styles = StyleSheet.create({ container: { height: 100 } })
Then, add it to style your component appropriately, like this:
<View style={styles.container}></View>
You could go the inline road, like the following and you would end up with the same thing:
<View style={{height: 100}}></View>
Pixels?
Looks pretty similar to CSS, right? It is, in general, named the same, to reflect CSS, but you may notice we did not indicate any unit to the “100” in
height: 100. You may be used to writing “px”, “vm”, etc. And the question is, what units are used by default in React Native?
That is a pretty complex question, which has taken more than one article to answer. For iOS, they are “logical points”, and Android uses DIP. There is a lot of reasoning behind this, as well as the logic as to why this was chosen. The short of it is, there are many different screen sizes and different resolutions on the same screen size. So, if we used normal pixels, it would look pixelated on some phones; but the idea behind “points” is to make things look relatively the same on a pixel-dense, high-resolution screen, as it does on an low-resolution screen.
The good thing is, this will handle most of the styling for you, from iOS to Android. Though it isn’t perfect, it will look roughly the same from one platform to the other. There is a calculation that goes on behind the scenes to determine what your height, width, borderWidth, etc, would look like on the screen.
You can also use ‘auto’ or percentages, but you wrap it in quotes, like this:
<View style={{ height: '100%' }}></View>
Wrap Entire Screen
Now, one thing to know about setting a
<View> to fill the entire screen, is a phone like the iPhoneX has part of the screen covered. Normally, part of your screen which you put your elements in, will be hidden under the covered part of the screen. For this, simply use the React Native component
<SafeAreaView> to wrap the rest of your components and you can be sure you will see all of your screen.
Another way is simply styling with
flex: 1. Remember, React Native uses Flexbox by default so you don’t need to worry about applying
display: flex to anything. But why would adding
flex: 1 fill the height of the screen?
Well in React Native the default
flexDirection is
column, unlike in the web version. You could set the
flexDirection, but if not,
flex: 1 stretches down the main axis, which is by default column. And if you know Flexbox, you know that if there is no other element,
flex: 1 fills the entire main-axis of the parent container.
Margins and Padding
One of the nice things about styling in React Native is the added styles to margin and padding. Both of them come with a way to set top and bottom in one line, as well as left and right in one line. Both of them use the words,
Horizontal and
Vertical.
For instance, to give an element a top and bottom margin of 20 you could set in like this:
<View style={{marginVertical: 20}}></View>. You could also give it padding of top and bottom with
paddingVertical: 20. The other is like this
paddingHorizontal and
marginHorizontal.
Now these are nice, but you may notice you cannot do what you would do in the web, like this:
margin: '20 0 20 0'. That won’t work in React Native.
There is also “Start” and “End” you can tag on the end of margin and padding. Whenever you see “start” and “end” in styles, you can know these depend on the flexDirection of the container - if the direction is
row then
marginStart is equal to
marginLeft. If the flexDirection is
row-reverse then
marginStart would be equal to
marginRight. Also, keep in mind, “start” and “end” override
marginLeft and
marginRight,
paddingLeft and
paddingRight.
Shadows and Borders
The normal
border style in CSS is not available in React Native styles. You have to break it down into
borderColor and
borderWidth. With those two indicated, you have enough for a border. Also, you can pick which side receives which color/width.
There’s also
borderRadius, as you may be used to, that gives a radius to each corner. You can pick each individual radius with
top-start,
top-end,
bottom-start, or
bottom-end, like this:
borderTopStartRadius: 20, or you can use the easier
top-left,
top-right, and so on. Finally, you can use
borderStyle to pick from dashed, dotted, or solid borders.
As for shadows in React Native, you won’t be using the
box-shadow you might be familiar with. Instead, React Native has styles that only work in iOS. Use these three styles:
shadowOffset: { height: 3, width: 3 }, shadowColor: '#0000', shadowOpacity: 0.5, shadowRadius: 5 }. These shadows work pretty well and if you are familiar with box-shadow from the web, these will be a cinch.
But, in Android, there isn’t a great, built-in solution with React Native. You can set the
elevation property, but this isn’t customizable and won’t work well with other styles - such as border and background colors. For Android I would suggest react-native-shadow.
Platform-Specific
In the last section, we saw the first major difference between platforms: one has shadow styles, but the other doesn’t. Now the good thing is, in the example above, Android will simply ignore the styles it doesn’t support. It won’t work, but at least you won’t receive any errors. That’s true for the most part with all styles you’ll find that aren’t supported by a platform - it will be ignored.
However, you’ll find quite a lot of difference in appearance from one platform to the other, even with perfect, clean styles. It’s simply bound to happen. To make the styling look similar across platforms, let’s import the
Platform component from React Native. Once imported you can set up your styles to be dynamic, platform dependent.
import { View, StyleSheet, Platform } from 'react-native'; {/* ... */} <View style={styles.container}></View> {/* ... */} const styles = StyleSheet.create({ container: { height: Platform.OS === 'android' ? 100 : 20, backgroundColor: Platform.OS === 'ios' ? 'yellow' : 'blue', ...Platform.select({ ios: { width: 100 } }) } })
Notice the two different ways here to set platform-specific styles. One way comes after the style prop, using a ternary operator,
height: Platform.OS === 'ios' ? 100, 20. This works well in most situations, but what if you don’t even want to set a style in one platform? That’s where
...Platform.select() comes in. This allows you to specify a style on one platform only, or both:
...Platform.select({ ios { width: 100 }, android: { width: 75 } }).
Other
Now styling gets much more deep and complex than this article can cover. You’ll notice in React Native that styles are different from component to component, unlike the web where basically every element can use every style. If you look at the official React Native docs (this is the style prop in the Text component), you will see a list of the components, and under each one, a list of styles you can use to design the component. You’ll find these a bit limited compared to the web, and some, like the Button component, don’t even have a style prop.
Much of the time, you can use components like
<TouchableOpacity> and of course,
<View>, which have most of the styling props available. | https://www.digitalocean.com/community/tutorials/react-styling-react-native | CC-MAIN-2020-34 | refinedweb | 1,388 | 71.85 |
Lora not working on 1.8.0
Hello,
The below example from Daniel (that previously was running fine) is not working between 2 Lopy with the same code.
Do we need special configuration for Lora initialization ?
from network import LoRa import socket import machine import time # initialize LoRa in LORA mode # more params can also be given, like frequency, tx power and spreading factor lora = LoRa(mode=LoRa.LORA) # create a raw LoRa socket s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) while True: # send some data s.setblocking(True) s.send('Hello 1') # get any data received... s.setblocking(False) data = s.recv(64) print(data) time.sleep(1)
@jmarcelino Thanks. There is a way to enable some C/C++ traces to see why is not working on this 6 new LopYs?
- jmarcelino last edited by
@colateral
There no hardware difference between 868 and 915. Just depends which country you selected when using the Pycom upgrade tool
@husigeza Thanks. We opened 6 brand new devices .... using pair of 2, none is receiving Lora raw. Here we are using 868Mhz.
Can be problem if we got 915 LoPy? How can we check if a device is 915Lopy or 868 LopY?
@colateral
For me your code works on 2 LoPys on version 1.8.0.b1.
I copy-pasted your code to the devices, it works out of the box without any modification.
This post is deleted!
Nope. Still not working.
We took 4 new LopY and 4 new expansion boards (from the last received lot), upgraded them with PyCom firmware software.
>>> uos.uname() (sysname='LoPy', nodename='LoPy', release='1.8.0.b1', version='v1.8.6-760-g90b72952 on 2017-09-01', machine='LoPy with ESP32', lorawan='1.0.0')
... and with default configuration nothing received during 10min.
Frequency: 868000000 Spreading Factor: 7 Power: 13 Coding Rate: 1 Preamble: 8 Bandwidth: 0 MAC: b'p\xb3\xd5I\x98\xacd\x9e'
Try leaving this running for awhile (5-10min) and see if something comes across. Could be related to the intermittent issue I am encountering here: | https://forum.pycom.io/topic/1793/lora-not-working-on-1-8-0 | CC-MAIN-2019-13 | refinedweb | 344 | 69.28 |
We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello everyone.
I was trying to create a detecting system for a project, and by far I was testing only on a MacBookPro, where I attached 2 USB web cam (same brand/model) while using the built-in InSight Camera as the 3rd Camera.
On MacMini, I have 3 web cams (same brand/model) but when I run the code, only one Camera shows its output. A second camera will turn on its led, but shows a black output. The third camera doesn't even turn its indication led on. I have tested each camera separately, or in pairs, but no good news. Still on MacMini system Information window, I can see it recognises those 3 cameras at same time.
Any one would have a similar problem before, or any suggestion please? Thanks!!
The prototype was working on a MacBookPro (with its built-in camera). This is the code:
import gab.opencv.*; import java.awt.Rectangle; import processing.video.*; Capture camL, camM, camR; OpenCV opencvL, opencvM, opencvR; Rectangle[] facesL, facesM, facesR; PImage srcL, srcM, srcR; void setup() { size(960,180); frameRate(15); //L for left Camera camL = new Capture(this,320,180,"Logitech カメラ",30); camL.start(); opencvL = new OpenCV(this, camL.width,camL.height); opencvL.loadCascade(OpenCV.CASCADE_FRONTALFACE); //M for Center Camera camM = new Capture(this,320,180,"FaceTime HD カメラ(内蔵)",30); //on MacMini, change name: Logitech カメラ #2 camM.start(); opencvM = new OpenCV(this, camM.width,camM.height); opencvM.loadCascade(OpenCV.CASCADE_FRONTALFACE); //R for Right Camera camR = new Capture(this,320,180,"Logitech カメラ #2",30); //on MacMini, change name: Logitech カメラ #3 camR.start(); opencvR = new OpenCV(this, camR.width,camR.height); opencvR.loadCascade(OpenCV.CASCADE_FRONTALFACE); } void draw() { if(camL.available()){ camL.read(); srcL = camL.get(); opencvL.loadImage(srcL); image(opencvL.getInput(), 0, 0); facesL = opencvL.detect(); noFill(); stroke(0, 255, 0); strokeWeight(3); for (int i = 0; i < facesL.length; i++) { rect(facesL[i].x, facesL[i].y, facesL[i].width, facesL[i].height); } } if(camM.available()){ camM.read(); srcM = camM.get(); opencvM.loadImage(srcM); image(opencvM.getInput(), 320, 0); facesM = opencvM.detect(); //image(cam, 0, 0); //set(0,0,cam); noFill(); stroke(0, 255, 0); strokeWeight(3); for (int i = 0; i < facesM.length; i++) { rect(320 + facesM[i].x, facesM[i].y, facesM[i].width, facesM[i].height); } } if(camR.available()){ camR.read(); srcR = camR.get(); opencvR.loadImage(srcR); image(opencvR.getInput(), 640, 0); facesR = opencvR.detect(); noFill(); stroke(0, 255, 0); strokeWeight(3); for (int i = 0; i < facesR.length; i++) { rect(640 + facesR[i].x, facesR[i].y, facesR[i].width, facesR[i].height); } } } | https://forum.processing.org/two/discussion/7216/3-webcams-work-on-macbookpro-not-on-macmini | CC-MAIN-2019-47 | refinedweb | 453 | 60.51 |
Paige Jones17,985 Points
Anyone willing to look at my Sinatra Wiki App Code? I have some bugs in my code and could use some help
Hi treehouse! Ive just finished the ruby wiki app lessons. However, I did all my code on my local environment using atom. I have some bugs in my code as my stylesheet isn't loading and i get an error when clicking to connected pages.
Would be so appreciative of anyone willing to take a look at my code and give me a hand.
thanks! Paige
Paige Jones17,985 Points
@stevehunter yes thats all for files! thanks so much - i really appreciate it.
Steve HunterTreehouse Moderator 56,129 Points
I'm not sure I have an environment set up for Sinatra. Is it Ruby on Rails based? If so, which Ruby version and which Rails version? I can create that in Cloud9.
Paige Jones17,985 Points
@stevehunter unfortunately i believe they are different frameworks.
5 Answers
yk721,002 Points
Hello ; disclaimer, I m ruby on rails fun. sinatra is not installed on my computer,
CSS
but I looked at your code; I found that href to reference css file in the layout file,
<link rel="stylesheet" href="/style.css">
I think the path should be folder/file.css CSS/style.css the only time that we don't add the folder /. it is when it's public folder >> you see that in challenges practicing with Sinatra ;(see guide (1) on the bottom of the page )
Pages
sorry I could not help with the second issue, of getting an error when clicking on connected pages. But in the File wiki.rb you got some method declared with 1 parameter, like ;
def save_content(title) File.read("pages/#{title}.txt", "w") do |file| file.print(content) end end
but in the bottom when you call them, you call them with 2 arguments; like this
post "/create" do #setting up post request save_content(params["title"], params["content"]) redirect URI.escape("/#{params["title"]}") end
I think you understand the issue, right?! anyway here is the teacher note link:
I hope that helps, and correct me if I m wrong, thx
(1)
(*)
Paige Jones17,985 Points
Hi
thanks everyone in a combined effort for the help!
Jay McGavrenTreehouse Teacher
Paige Jones17,985 Points
Hi Jay
Hi All Thanks SO much for the help. Ive since implemented all the changes you guys suggested, but i'm still not able to get my stylesheet to load and my pages are blank. Any other ideas where my mistake might be?
thank you!
Jay McGavrenTreehouse Teacher
I downloaded the latest version of your code.
I confirmed that the wiki pages are blank. So the first step was to figure out why. I added a couple debug calls to
p:
def page_content(title) p title p File.read("pages/#{title}.txt") rescue Errno::ENOENT return nil end
Then I tried to reload the page, and got this output:
nil ""
So
page_content is receiving a
title parameter of
nil. That led me to look at your call to
page_content on line 31:
get "/:title" do #setting up get request @title = params[:title] #instance variables @content = page_content(params[@title]) erb :show #render erb template end
There's the problem! If you're loading a path of
/foo, then
params[:title] will contain
"foo". You set
@title = params[:title], as you should. But then you access
params[@title], which in this case is the same as accessing
params["foo"]. There is no key of
"foo" in the
params hash, and so you get
nil back.
page_content(nil) will always return an empty string. And that's why the result is a blank page.
You should try changing line 31 to read like this:
@content = page_content(@title)
Or this:
@content = page_content(params[:title])
yk721,002 Points
Hello,
<link rel="stylesheet" href="/CSS/style.css">
For CSS; the href is correctly written, But Sinatra looks for the path in ./public/CSS/style.css So you need to create a folder called public and move the CSS folder to it.
so the real path is different from the path on the layout.erb. Sinatra looks for static files like CSS in the folder ./public, ("." is the root ) but on the layout.erb, you don't to mention the public folder because Sinatra knows where to look for href
reference : > look under section of Static Files
I did test it, and the CSS loads fine, Nice design by the way.
I hope that helps :)
Steve HunterTreehouse Moderator 56,129 Points
Steve HunterTreehouse Moderator 56,129 Points
Hi Paige,
Happy to try to help - I've never used Sinatra but know Ruby on Rails well.
Does your Github repo have all your folders? I can see three; CSS, pages and views. Is that everything?
Steve. | https://teamtreehouse.com/community/anyone-willing-to-look-at-my-sinatra-wiki-app-code-i-have-some-bugs-in-my-code-and-could-use-some-help | CC-MAIN-2019-30 | refinedweb | 802 | 73.47 |
Write some Software -- 9
Budget R$30-150 BRL
The project is an data generator that uses a XSD to describe the XML structure that have to be generated. This XSD are builded using some namespaces, some optional elements composition, various enumarations and string fields.
The code project uses Java 1.8 with Maven and JAX-B. It already have the Java classes generated by XJC and a validated XML file as example.
The main goal is generate some random compositions that are included the a optional and mandatory XSD blocks. It is mandatory that some elements have to consume a domain inclued on a text field. It will be described after the start of project.
The second goal is implement an command line argument menu options to execute the project.
We use Git and Gif Flow. It is important that all progress are versioned using this structure. The code have to be reviewed.
On the attachments there are an example from the XSD used the be generated. | https://www.fr.freelancer.com/projects/software-architecture/write-some-software-14846855/ | CC-MAIN-2018-13 | refinedweb | 168 | 67.15 |
WebKit Bugzilla
bug 10709 is about parsing CSS stylesheets in UTF-16/32. For html/xml documents, UTF-16 is detected and supported, but UTF-32 (BE and LE) is not.
Created attachment 14103 [details]
a preliminary patch
Patch looks good to me.
test cases. Not all test cases work because some of them rely on a 'psuedo-BOM for HTML', which is not supported by WebKit, perhaps intentionally (HTML standard does not have such a provision while XML has that in the appendix). Test cases for 'pseudo-BOM for XML' (supported by WebKit) need to be added.
Comment on attachment 14103 [details]
a preliminary patch
Per Comment #2, the basic patch is good, but it needs a ChangeLog entry and test cases.
Please include layout test cases (with the patch) when you resumit the patch.
More information on creating a ChangeLog entry and a patch is here:
Scripts are in the WebKitTools/Scripts directory. Thanks!
David, according to the document you mentioned, I'm not supposed to use fonts that don't come with Mac OS X. Is there any Mac OS X standard font supporting non-BMP characters? Because WebKit renders 'U+0000' with zero-width glyph, it's impossible to tell whether UTF-32LE is interpreted as UTF-32LE or as UTF-16LE unless I include some non-BMP characters.
A Japanese font (to support JIS X 213 characters) may cover some CJK ideographs in plane 2. I have to check that out.
Alternatively, I might be able to use a Javascript to tell which is the case.
(In reply to comment #5)
> Alternatively, I might be able to use a Javascript to tell which is the case.
That looks like the easiest alternative - document.inputEncoding will contain the detected encoding name.
Created attachment 14218 [details]
patch with test cases and changelog entries
Added test cases for UTF-32BE (html with BOM and xml without BOM) and UTF-32LE (html with BOM and xml without BOM). I can't make a xml test case for UTF-32LE that prints out document.inputEncoding. I tried document.write() and a few DOM-based methods to add a node, "<p>{the value of document.inputEncoding}</p>", but I couldn't make it work in Safari.
For UTF-32BE, just comparing the output (without document.inputEncoding) is sufficient because it cannot be mistaken for UTF-16BE or other encodings. For UTF-32LE, we'd better print out the value of document.inputEncoding.
To dynamically create a <p> element, be sure to use createElementNS with XHTML namespace (unlike Firefox, WebKit does not try to guess what namespace to use with createElement; we have a bug tracking this).
Alternatively, the following should work:
---------------------
<div id="result">FAILURE: script did't run</div>
<script>document.getElementById("result").firstChild.nodeValue = document.inputEncoding;</script>
---------------------
Comment on attachment 14218 [details]
patch with test cases and changelog entries
r- for now to consider Alexey's comment, please flag for review with new patch.
Created attachment 14220 [details]
a new patch with updated test cases
Modified test cases per ap's suggestion. Both XML and HTML print out the encoding determined.
> ---------------------
> <div id="result">FAILURE: script did't run</div>
> <script>document.getElementById("result").firstChild.nodeValue =
> document.inputEncoding;</script>
> ---------------------
Actually, I tried the above as well. However, I forgot that I had to make it run after the loading is complete (the script was put in the <head> without an onload triggering.). As a result, it didn't run even in Firefox.
Thanks to your suggestion, I realized that :-)
Alexey (or anyone else), can you review the latest patch?
Comment on attachment 14220 [details]
a new patch with updated test cases
r- for now, but the patch looks really good to me!
+ unsigned char c3 = buf1Len ? (--buf1Len, *buf1++) : buf2Len ? (--buf2Len, *buf2++) : 0;
+ unsigned char c4 = buf2Len ? (--buf2Len, *buf2++) : 0;
...
+ if (c1 == 0xFF && c2 == 0xFE) {
+ if (c3 != 0 || c4 != 0)
+ encodingConsideringBOM = &UTF16LittleEndianEncoding();
+ else
+ encodingConsideringBOM = &UTF32LittleEndianEncoding();
+ }
You need to check why c3 and c4 are zero - if there are only two bytes available yet, it may be too early to assume UTF-32.
else if (numBufferedBytes + length <= sizeof(m_bufferedBytes) && !flush) {
// Continue to look for the BOM.
I believe m_bufferedBytes size should be increased to three bytes, now that we deal with 4-byte BOMs.
Created attachment 15303 [details]
patch updated
patch updated per comments.
Comment on attachment 15303 [details]
patch updated
It seems that the change to html4.css does not belong to this patch.
+ setEncoding(((ptr - m_buffer.data()) % 4) ? "UTF-32LE" : "UTF-32BE", AutoDetectedEncoding);
Since you've replaced encoding names with function calls in several places, I suggest using those here, as well.
+ //else if (numBufferedBytes >= 3 || length >= 3)
We really do not like commented-out code in sources, please remove this line.
Coming to more important issues: I don't think I understand the algorithm in TextDecoder::checkForBOM(). Why did you change m_bufferedBytes size to 4 bytes? If we have already seen 4 bytes of the input, then we are done with BOM detection, so only 3 bytes need be buffered. And the "encodingConsideringBOM != &m_encoding" check looks wrong, comparing TextEncoding by address is not a good way to detect that we have successfully found a BOM.
This is extremely close to an r+, but I think that another iteration is needed to iron out these issues.
Created attachment 15320 [details]
patch updated once more
thanks for the review. pls, take another look
Comment on attachment 15320 [details]
patch updated once more
Looks great, r=me!
Attention committer: there is a tab character in the patch.
Comment on attachment 15320 [details]
patch updated once more
I went to land this patch but the tabs in the various UTF-32 files made it rather tricky. After futzing around for a few minutes trying to find an editor that'd handle all four UTF-32 variations, I gave up. Can you please fix the four UTF-32 files, and the tab that's in the source file while you're at it :)
It's also unclear to me why the some of the tests are .xml and others are .html. Is there some reason for this?
What do you mean by tabs in 4 UTF-32 files? They're NOT ASCII-compatible and they should be treated as binary.
As for xml vs html, WebKit currently use different encoding sniffing rules for html and xml, which is why I have separate test cases for html and xml. The same is true of UTF-16 test cases.
I'll get rid of tabs in the source code and upload a new patch.
Ahah. If it's required that even html/xml files for test are tab-free (in whatever encoding), I'll get rid of them in 4 UTF-32 files.
Created attachment 15413 [details]
patch without tabs
tabs are removed in the source code as well as in UTF-32 files.
Comment on attachment 15413 [details]
patch without tabs
Thanks for removing the tabs.
My question about HTML vs XML was that you have only four test cases -- UTF-32BE with and without BOM, UTF-32LE with and without BOM. The BOM-less cases are both XML, the ones with BOM are both HTML. What about BOM-less HTML? Or XML with a BOM?
Landed in r24052. | https://bugs.webkit.org/show_bug.cgi?id=13415 | CC-MAIN-2016-50 | refinedweb | 1,215 | 65.22 |
The new Splunk Infrastructure Monitoring plugin brings the SaaS formerly known as SignalFx to your Grafana dashboards
Greetings! This is Mike reporting from the Solutions Engineering team at Grafana Labs. In previous posts, you might have read our beginner’s guide to distributed tracing and how it can help to increase your application’s performance. In this post, we are back to talk about metrics and showcase another one of our newest favorite Enterprise plugins: Splunk Infrastructure Monitoring (formerly known as SignalFx)!
If you have a “four nines'' SLA for your business-critical application, time is of the essence. Supporting a 99.99% availability target means that there are only 4.38 minutes of downtime to spare on a monthly basis. Even worse, maintaining those SLAs is becoming even harder when your application resides on Kubernetes, where the workloads perhaps live only a few minutes and the interactions between the application’s microservices are complex. To top it off, your mission-critical application may even rely upon third-party APIs! From an observability perspective, the timeliness of metrics and analytics is critical, and automated triage and remediation is a must. That is where SignalFx came into play.
SignalFx provides real-time monitoring and metrics for cloud infrastructure, microservices, and applications.
To help speed time-to-resolution, SignalFx promotes:
- Metrics at high resolution, down to one second.
- Real-time analytics, so you can create composite metrics to model your KPIs and alert on those composite metrics in real time.
Back in August 2019, Splunk acquired SignalFx, and today, SignalFx is an integral part of the Splunk Observability suite, rolled into the Splunk Infrastructure Monitoring product. We’ve officially renamed the plugin to reflect this, but please note that some references to SignalFx remain in the product and in this blog. :-)
With the Splunk Infrastructure Monitoring plugin for Grafana, which is available with an Enterprise license, you can leverage everything you love about SignalFx/Splunk Infrastructure Monitoring while still centrally visualizing your other data sources side-by-side. The outcome? That flexible, single-pane view of the underlying metrics that measure the health of your systems and applications to quickly correlate and debug for reduced MTTR.
Plugin basics
Setup
Setup is very simple and straightforward. First, you will need to download and install the plugin itself from our plugins page.
Next, you will create your Splunk Infrastructure Monitoring data source in Grafana by going to Configuration > Data Sources > Add data source. In order to configure your data source, you need your realm name and your SignalFx access token. Your realm can be found as a component of your SignalFx URL. Since my URL is, my realm name is
us1. There are others, such as
eu0. You can find your SignalFx access token by clicking on your avatar in the upper right of the SignalFx UI, then Organization Settings, and then Access Tokens. Under token Default, you will see a link that says Show Token.
In the end, your plugin configuration should look as simple as this:
You are now ready to go!
SignalFx sample dashboard
To start learning how SignalFlow has been implemented in this plugin, I first took a look at the SignalFlow queries within the example dashboard.
To populate data on the example dashboard, you need to be monitoring one or more hosts. In my test, I leveraged SignalFx’s one-line install (URL for the setup page on realm
us1 is here). The single command auto-detects your OS, installs a collectd agent, and leverages your SFx access token so that the metrics automagically start flowing to the SFx SaaS service. My dashboard looks like this:
Opening up the Total Memory graph, I see that the query is a traditional, multi-line SignalFlow query.
Bringing Kubernetes-centric SignalFlow queries into Grafana
Earlier today, I had wanted to see some metrics on my Kubernetes cluster using SignalFx. So I followed the SignalFx helm chart instructions (on realm
us1, they are here). It was quite straightforward and took only a couple of steps to complete.
Now, I would like to see those metrics in Grafana. Instead of browsing SignalFx’s metrics search capability, I decided to take the easy route and copy-paste the SignalFlow queries that the SignalFx team has already built. To see the SignalFlow query for one of the graph panels in the SignalFx UI, I clicked on the title of the graph. This brings you to the Plot Editor, where you choose the metric and add filters for your graph. To the far right on the plot editor is a View SignalFlow button. I copied each of these SignalFlow queries and pasted them into separate Grafana panels.
Next, I wanted to add a variable so that I could filter on a particular namespace. I found the variable definition setup could not have been easier, because all you have to do is click on the Dimensions button, and the plugin returns the available data dimensions, including
kubernetes_name. The final dashboard looked like this:
Going forward, I plan to create a “mixed estate” dashboard showing Prometheus and SignalFx metrics from Kubernetes clusters side-by-side — or even in the same graph, like I discussed in the Wavefront plugin blog. But I thought it’d be repetitive; i.e., check out the Wavefront blog if you are interested, as the technique would be identical. Just swap out the data source
Wavefront for
Splunk Infrastructure Monitoring, and you are good to go.
Well, that’s all for today, but please tweet at us to let us know the next plugin you’d like us to write about or support. Until next time!
The Splunk Infrastructure Monitoring plugin is available with a Grafana Enterprise license. Find out more about Grafana Enterprise here. | https://grafana.com/blog/2021/02/22/the-new-splunk-infrastructure-monitoring-plugin-brings-the-saas-formerly-known-as-signalfx-to-your-grafana-dashboards/ | CC-MAIN-2021-10 | refinedweb | 960 | 62.17 |
Created on 2015-05-27 08:06 by njs, last changed 2018-10-18 12:46 by serhiy.storchaka. This issue is now closed.
DeprecationWarning and PendingDeprecationWarning are invisible by default. The rationale for this is that they are only useful to people who are writing code, so they should not be shown to end-users who are merely running code.
If someone is typing stuff into the interactive REPL, though, and the code they type uses some deprecated functionality, then we should actually show them this warning. We know that the author is sitting right there. And they're probably going to take whatever they tested interactively and move it into a more permanent form and ugh.
This problem is particularly acute for packages that are primarily used through the interactive prompt, like numpy. I am tired of getting bugs like this:
The solution is simple: when entering interactive mode, the REPL should do something like:
warnings.filterwarnings("default", category=DeprecationWarning, module="__main__")
warnings.filterwarnings("default", category=PendingDeprecationWarning, module="__main__")
I also filed a similar bug with ipython:
I have learnt to run the interactive interpeter (and also most of my own scripts) with the -b -Wall options. But having these switched on automatically may not be a bad thing.
See discussion on Python-Ideas [1].
[1]
+1 for showing DeprecationWarning by default (as these features may be going away in the next X.Y release of Python)
-0 for showing PendingDeprecationWarning by default (as these won't be going away until X.Y+1 at the earliest)
*cough* You know, there's more to life than Python-X.Y.tar.gz :-). Not that I know how PendingDeprecationWarning is used in the wild. I've been thinking maybe we (numpy) should start using it for stuff that we want to discourage people from using (we know it was a bad idea or intrinsically broken or whatever), but don't yet have a full replacement to offer. It would help if there were some official guidance on what these things mean -- I can't find anything written down anywhere that even documents what you just said about how CPython proper uses them, so I imagine people have come up with all kinds of interpretations.
Anyway, my logic would be: when I am trying something out at the REPL, usually it is because I want to check how it works, to figure out what I should be doing in the real module code that I'm writing in the next window. When doing this, I definitely appreciate knowing that it will be removed and is being replaced -- it won't necessarily stop me from putting it into my code, but at least it's information that I can take into account.
I don't care a huge amount either way, though; if we decided to hide PendingDeprecationWarnings by default while showing DeprecationWarnings then numpy would just define a NumPyPendingDeprecationWarning subclass of DeprecationWarning and use that instead of PendingDeprecationWarning and all would work out fine :-).
The difference between the two used to be clearer: prior to Python 2.7, PendingDeprecationWarning was hidden by default (and thus mainly only visible to folks testing with -Wall), while DeprecationWarning was visible by default.
We blurred the line between the two thoroughly when DeprecationWarning also became hidden by default, giving the status quo:
Test frameworks: both visible by default
Interactive REPL: both hidden by default
Non-interactive execution: both hidden by default
Splitting them in the interactive REPL case would restore a meaningful behavioural difference that can help pragmatically guide decisions as to which is more appropriate to use:
Test frameworks: both visible by default
Interactive REPL: DW visible by default, PendingDW hidden by default
Non-interactive execution: both hidden by default
The current unanswerable "How do my users interpret the difference between DW and PendingDW?" question would be replaced by the much simpler "Do I want folks using the interactive REPL to see this warning or not?"
Okay, that sounds reasonable to me.
For Idle, the addition could be made in current versions. Idle compiles user code in the idle process and ships it to the user process for execution. In particular, idlelib.run.Executive.runcode, line 351, is
exec(code, self.locals)
Am I to presume that a) the warnings that you want to display will escape the exec call and that b) they are currently being caught at the module level and c) that the filterwarnings line or lines would do what you want if added to run.main, such as at line 104? Do warnings from python code and user code get treated the same?
Please post test cases to enter by hand, both at the prompt and in the editor, to get system warnings for 2.7 and 3.4 or 3.5. Also, please copy the positive and negative examples you posted to python-ideas.
There isn't really any magic in how warnings work. Basically someone calls warnings.warn(...), which is a regular Python function, and it gathers up some information about the specific warning message and calling context, checks a global variable ("warnings.filters") to decide how this message in this context should be handled, and then either does nothing, prints something to stderr, or raises an exception.
There are lots of warnings that are printed by default, and I'm sure IDLE is handling them fine already. It's just (Pending)DeprecationWarnings in particular that have an entry stuck into warnings.filters saying "please ignore these" (unless it gets overridden by something else).
So you just need to make sure that a filter is added to warnings.filters that says to treat DeprecationWarnings generated by the __main__ module using the "default" action. ("default" is the name of a specific way of handling warnings; for most types of warnings, the default handler is the one named "default", but for DeprecationWarning, the default handler is the one named "ignore". Obvious, right?)
So you just need to make sure to run the following line of code somewhere in the user process:
warnings.filterwarnings("default", category=DeprecationWarning, module="__main__")
Adjust as necessary if (a) you want to apply similar handling to PendingDeprecationWarning, (b) your user namespace has some value of __name__ that is different from "__main__".
Then to test, you can just type
warnings.warn("foo", DeprecationWarning)
at the prompt, and it should be printed.
Note that because the warnings module tries to suppress duplicate warnings (which is good), and it has a bug where it can't tell the difference between different lines of code at the REPL (this is bad -- see , and there should probably be a python bug too but I haven't gotten around to filing it), then the *second* time you run that line of code in the same REPL, nothing will be printed. So the moral is just, when testing this, make sure you use a different warning message each time, or you'll get very confused.
Recording this here so it doesn't get lost: Marc-Andre Lemberg suggested on python-ideas that for the builtin REPL, this should be enabled iff sys.stdin.isatty(). (I guess he is worried about 'cat script.py | python'.) I'm not really sure whether this falls on the useful or confusing side of the line myself.
I gave that a shot.
Doing it "cleanly" in C as the warning module is initialized much earlier.
Though I'm not super used to CPython internals.
Doing just before the repl by using `PyRun_SimpleString` make the patch relatively small.
For whatever it's worth as a non-core-developer, the patch looks good to me.
Ping.
I know this is pretty trivial and everyone's focused on 3.5-related stuff, but it would be nice to get this finalized soon b/c the sooner CPython commits to some standard behavior here, the sooner all the other (faster-moving) python REPLs will converge to match.
Note that I've signed the CLA, and it has been taken into account, as now I have a small star agains my name (if it was the limiting factor, we never know).
I've changed the stage to "test needed".
At a minimum, an interactive test should be written and added to the documentation. Better would be an automated test (perhaps via subprocess).
The documentation should also be updated; at a minimum, there should be a versionchanged to say when the default changed. Ideally, also some clarification on the intended differences between DeprecationWarning and PendingDeprecationWarning, and whether there are any behavioral differences.
Hum, working on the automated test. It is slightly annoying as with subprocess python is not in a tty, so there will be no change in behavior. I'm not sure how to proceed.
> At a minimum, an interactive test should be written and added to the documentation
Where would that be ? In the warnings docs, or is there a specific place for "Manual tests" ?
Instead of using python directly in a subprocess, try calling a shell command that in turns calls python. (Admittedly, this may look like the pipe scenario...)
In theory, you could even drive another python interactively, using a GUI runner, but I'm not sure how much new infrastructure that would add to the test suite, so it might not be worth it.
I'm not aware of a list of manual tests (though perhaps there *should* be one...); I would put it under the DeprecationWarning docs, sort of like an example. Others may have better ideas.
I don't see how any of those suggestions help for writing an automated test. Spawning a shell is irrelevant; the problem is to get a tty, which is much harder. There only way I can see that might work for an automated test is to use
which is Linux only, but I suppose that's better than nothing.
(isatty(sys.stdin) does do something sensible on Windows, right? I hope?)
Would `pty` even work on CI where the terminal itself might not be a TTY ?
>>> subprocess.Popen(['bash', '-c', '''./python.exe -c "import sys; print(sys.stdin.isatty())"'''], stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
False
Otherwise, I can also (try to) implement a debug flag "--FakeTTYYesIMReallySure" that make `.isatty()` lie.
If pty is going to work at all then it should work regardless of whether the tests themselves are being run under a tty, yes.
I personally would not want to merge a test based on making isatty lie, because the point of tests is to increase confidence that things work, and that test sounds more complicated and error prone than the original code being tested. I'm not a cpython committer though...
I am more concerned that isatty might actually just not work on windows, since it is actually strictly speaking true that you never have a "try" on Windows, even if you might have a gui console window open. It would be a good idea to check this quickly...
The other option would be to just remove the isatty check from the patch entirely -- it wasn't something that had strong consensus in the first place.
Astonishingly isatty appear to work on windows:
Up to core python for istty().
On windows, when python is started from the command line without a GUI, os.isatty(sys.stdin) raises an error, but os.isatty(sys.stdin.fileno()) returns true.
Within IDLE, os.isatty(sys.stdin.fileno()) also raises an error, but os.isatty(0), os.isatty(1), and os.isatty(2) all return true.
I'm not sure exactly when you want which warning to show, let alone whether the above tests are relevant, but I'm happy to run some tests if you can tell me what you're looking for.
Hi, just to say - I'm happy to help steer this through. I think its an important ecosystem fixup.
On testing this - I don't think subprocess tests are necessarily needed.
The scenarios are these (from Nick's comment):
Test frameworks.
- there are two in the standard library. unittest and doctest.
- unittest's code paths end up going through 'TestProgram'.
- doctest via 'testmod'.
- so alter the warning configuration in those APIs to enable both DeprecationWarning and PendingDeprecationWarning. I don't think (right now anyhow :)) that we need a 'do not do this' flag in them..
Interactive REPL. This includes IDLE in my opinion.
- there are three here IIRC - IDLE and the cPython and a helper module (which may or may not be the REPL for ./python - I haven't climbed through that code in ---ages---).
- Again here I'd just enable DW in those code paths. Don't worry about whether its a tty or not: thats irrelevant. If the REPL enters, its the REPL and we should treat it like a user. If someone is driving the REPL programattically its likely one of: a remote session - so they should see it - or its a test harness - so they should see it.
Everything else.
Don't change anything here.
On docs: yes, we should update the docs for:
- each changed module
- the warnings module itself.
As Robert suggests, I think it's OK to issue the deprecation warnings for code run via "python < script.py" or "cat script.py | python". Reverting to the current behaviour if folks actually want that would just be a matter of passing the file in directly, rather than piping it via stdin: "python script.py".
That eliminates any need to care about whether the input is a tty or not, and we can just focus on the code paths. If you grep the CPython code base for "ps1" you're likely to find most of the relevant places ("sys.ps1" hold the interactive prompt, while "sys.ps2" holds the continuation prompt)
ok, thanks. I'll remove the is tty ans push docs changes on a new patch.
I'll see if I can figure out how to enable DW by default in unittest and doctest.
Thanks !
I'm not sure that is acceptable. "Just changing it to a file" could break an application's structure that is depending on being able to use stdin to run scripts. As one example, vim scripts can embed python code...now, what VIM does behind the scenes with that I don't know, and it might be able to write it out to a file or put somewhere in memory for the embedded interpreter to run, but the point is that here is a an application whose API is embedded scripts that get fed into python, not independent files that python gets called on. I'm guessing there are other applications out there that *would* be affected by this, even if vim itself isn't (and I don't know if it is or not).
# unittest
(Pending)DeprecationWarning are already enabled if no -W flags are given.
# doctest
We enable the DW in REPL only if originate from `__main__`, this seem to be painful to do in doctest, as each doctest execute in a module that have the name of the file it is executed in. Should I enable globally regardless of where the DW comes from, or explore more ?
Should the doctest fail if such a warning is raised, or actually just print it to the output, letting the doctest pass ?
The only way for this change to *break* something is if:
1. They're turning warnings into errors, or are otherwise sensitive to a deprecation warning being emitted
2. They're running code programmatically by way of an interactive REPL path
I think we're far more likely to break something else messing about with TTY detection, than we are keeping things as simple as we can and saying that if folks are running code as if they're a human rather than like a computer, then they're going to get the same deprecation warnings we want a human to see. *If* we get significant bug reports about that during the 3.6 alpha/beta cycle, *then* we can potentially consider limiting it to cases with an actual TTY. I just don't want us to borrow trouble and make this unnecessarily hard to test in the process.
Matthias: just print it and let the doctest pass. That's consistent with how unittest works (unless warnings have been turned into errors, in which case it should fail, but I don't think you have to do anything to make that happen).
Nick: OK. It is true that we aren't going to break anything if we get this wrong, just mildly annoy people :)
> It would help if there were some official guidance on what these things
> mean -- I can't find anything written down anywhere that even documents
> what you just said about how CPython proper uses them, so I imagine
> people have come up with all kinds of interpretations.
A while ago I proposed to document our deprecation process and the use of PDW/DW in a PEP:
There I suggest that we (CPython) stop using PDW but leave it around for other projects to use as they see fit. I'm not sure CPython should do anything special to distinguish PDW from DW.
@mbussonn - I don't see an updated non-tty-checking patch from you?
> @mbussonn - I don't see an updated non-tty-checking patch from you?
Sorry for the delay, trying to get back on this.
Please find attached a new patch that does not check whether is is a tty.
Still struggling a bit with HG (looking fwd to migration to GH)
See also PEP 565.
If you consider that the REPL is designed for developers, I would also suggest to show ResourceWarning by default.
I'm not sure of that since I like to write crappy code of REPL (and I hope that nobody logs my keyboard)! Example:
haypo@selma$ python3
Python 3.6.2 (default, Oct 2 2017, 16:51:32)
>>> open("/etc/issue").read()
'\\S\nKernel \\r on an \\m (\\l)\n\n'
I may be annoyed by a ResourceWarning warning here, since it's a oneliner written to be only run once. I know that my code is crappy, but I also know that it works well and it's much shorter to write than "with open(..) as fp: fp.read()" :-)
Yet another approach: I proposed to add a "developer mode", -X dev option:
I don't think anybody consistently does proper resource management in the REPL, so the trade-offs involved there are quite different from those for deprecation warnings.
Assuming PEP 565 gets accepted, we'll end up with once-per-session warnings for use of deprecated APIs (due to the REPL's perpetually reset line counter, as per issue 1539925), and that seems like a good level of notification to me (not too noisy, not so unobtrusive as to never be seen at all)
If it's of any interest to this discussion, for SymPy (for some time) we have used a custom subclass of DeprecationWarning that we enable by default. I don't know if there are major libraries that do something similar.
Our reasoning is that we really do want everybody to see the warnings. Obviously direct users of SymPy (both interactive users and library developers) need to see them so they can fix their code. But also if library X uses a deprecated behavior and a user of library X sees a deprecation warning for SymPy inside of library X, that incentivises them to bug the library X developers to fix the behavior (or PR it). The whole point of warnings as we see it is to be as loud as possible while still keeping things working, to avoid the situation where things stop working (when the deprecated behavior is removed).
And +<however many points I'm allowed to have> to Nathaniel's point that DeprecationWarnings are about more than just the standard library. Tons of libraries use the built in warnings, and the default warnings behavior makes no distinction between warnings coming from the standard library and warnings coming from other places.
After implementing PEP 565, are there reasons to keep this issue open? | https://bugs.python.org/issue24294 | CC-MAIN-2019-09 | refinedweb | 3,367 | 61.26 |
Cable cell labels¶
- class arbor.label_dict¶
Stores labels and their associated expressions as key-value pairs.
- label_dict(dictionary)¶
Initialize a label dictionary from a
dictionarywith string labels as keys, and corresponding string definitions as values.
labels = arbor.label_dict({'soma': '(tag 1)', # region 'midpoint': '(location 0 0.5)'}) # locset
The
arbor.label_dict type is used for creating and manipulating label dictionaries,
which can be initialised with a dictionary that defines (label, expression)
pairs. For example, a dictionary that uses tags that correspond to SWC
structure identifiers
to label soma, axon, dendrite and apical dendrites is:
import arbor labels = {'soma': '(tag 1)', 'axon': '(tag 2)', 'dend': '(tag 3)', 'apic': '(tag 4)'} d = arbor.label_dict(labels)
The same
label_dict can be created by starting with an empty label dictionary and adding the labels and their definitions one by one:
import arbor d = arbor.label_dict() d['soma'] = '(tag 1)' d['axon'] = '(tag 2)' d['dend'] = '(tag 3)' d['apic'] = '(tag 4)'
The square bracket operator is used above to add label definitions. It can be used to modify existing definitions, so long as the new new definition has the same type (region or locset):
import arbor # A label dictionary that defines the label "dend" that defines a region. d = arbor.label_dict({'dend': '(tag 3)') # The definition of a label can be overwritten with a definition of the # same type, in this case a region. d['dend'] = '(join (tag 3) (tag 4))' # However, a region can't be overwritten by a locset, or vice-versa. d['dend'] = '(terminal)' # error: '(terminal)' defines a locset. # New labels can be added to the dictionary. d['soma'] = '(tag 1)' d['axon'] = '(tag 2)' # Square brackets can also be used to get a label's definition. assert(d['soma'] == '(tag 1)')
Expressions can refer to other regions and locsets in a label dictionary. In the example below, we define a region labeled ‘tree’ that is the union of both the ‘dend’ and ‘apic’ regions.
import arbor d = arbor.label_dict({ 'soma': '(tag 1)', 'axon': '(tag 2)', 'dend': '(tag 3)', 'apic': '(tag 4)', # equivalent to (join (tag 3) (tag 4)) 'tree': '(join (region "dend") (region "apic"))'})
The order that labels are defined does not matter, so an expression can refer to a label that has not yet been defined:
import arbor d = arbor.label_dict() # 'reg' refers d['reg'] = '(distal_interval (locset "loc"))' d['loc'] = '(location 3 0.5)' # If d was applied to a morphology, 'reg' would refer to the region: # '(distal_interval (location 3 0.5))' # Which is the sub-tree of the matrix starting at '(location 3 0.5)' # The locset 'loc' can be redefined d['loc'] = '(proximal (tag 3))' # Now if d was applied to a morphology, 'reg' would refer to: # '(distal_interval (proximal (tag 3))' # Which is the subtrees that start at the proximal locations of # the region '(tag 3)'
Cyclic dependencies are not permitted, as in the following example where two labels refer to one another:
import arbor d = arbor.label_dict() d['reg'] = '(distal_interval (locset "loc"))' d['loc'] = '(proximal (region "reg"))' # Error: 'reg' needs the definition of 'loc', which in turn needs the # definition of 'reg'.
Note
In the example above there will be no error when the label dictionary is defined. Instead, there will be an error later when the label dictionary is applied to a morphology, and the cyclic dependency is detected when thingifying the locations in the locsets and the cable segments in the regions.
The type of an expression, locset or region, is inferred automatically when it is input into a label dictionary. Lists of the labels for regions and locsets are available as attributes:
import arbor d = arbor.label_dict({ 'soma': '(tag 1)', 'axon': '(tag 2)', 'dend': '(tag 3)', 'apic': '(tag 4)', 'site': '(location 2 0.5)', 'term': '(terminal)'}) | https://docs.arbor-sim.org/en/latest/python/labels.html | CC-MAIN-2022-40 | refinedweb | 623 | 51.68 |
I've tried to run software spi by using XIO pins and little confusing about performance. I've used libsoc library to manipulate with GPIO, which uses sysfs for GPIO, so as I understand it is bottleneck in performance GPIO manipulation. Is there exists other methods to direct access to GPIO instead sysfs?
For example, this code will stuck my program for a long time
void spi_send(char data)
{
int i;
for (i = 0; i < 8; ++i)
{
char value = (0x01 & (data >> i));
libsoc_gpio_set_level(LCDPort.mosi, value ? HIGH : LOW);
nsleep(16);
libsoc_gpio_set_level(LCDPort.sck, HIGH);
nsleep(16);
libsoc_gpio_set_level(LCDPort.sck, LOW);
nsleep(16);
}
}
int main()
{
int j;
for (j = 0; j < SCREEN_WIDTH * SCREEN_HEIGHT; j++)
{
spi_send(0x00)
spi_send(0x00);
}
return 0;
}
A couple of points. First, I think you will find that "nsleep(16)" does not in fact sleep for anything like 16 nanoseconds on a typical Linux machine. I did some timing measurements which I have yet to publish (needs some touching-up), but it sleeps for much longer.
Second, the XIO lines are slow because they are off-CPU. There's a serial communication (I2C) that happens between the CPU and the device which controls the XIO lines. You want to use the CSI lines, which are driven directly by the CPU. I am not familiar with the libsoc library, and did my testing by directly using the sysfs driver. But even using that, the CSI lines gave MUCH higher performance.
I'll try to put the finishing touches on my measurements and post them later today.
Thank you for your reply.nsleep it is my custom implementation of nanosleep, it looks like
void nsleep(long nanosec)
{
struct timespec tw = {0, nanosec};
struct timespec tr;
nanosleep (&tw, &tr);
}
but I've also tried GPIO without any sleeps - same results. So, I2C communication XIO with the proccessor might be reason for a low performance. I will try to use pins from CSI, as I understand from this topic there are pins from 128 to 139?
If you're trying to bitbang SPI, I believe the SPI code in my Adafruit_GPIO port will work:
I've never done SPI, nor do I have any SPI devices, so I am unable to test.
I believe that you will want to stick to using the following ports for general purpose GPIO, but I could be wrong.
CSID0 132CSID1 133CSID2 134CSID3 135CSID4 136CSID5 137CSID6 138CSID7 139
From the CHIP layout diagrams 128 to 131 have names other than CSI-Dx, like CSI-PCLK, CSI-MCLK, CSI-HSYNC, and CSI-VSYNC.
Please post how this works out as I'm interested in doing bit-banging to read the temperature from a DHT22 temperature sensor using code based on Adafruit's code for the raspberry pi.
The Adafruit code uses routines called bcm2835_gpio_write(), bcm2835_gpio_fsel(), bcm2835_gpio_lev(), and bcm2835_init(). I need to convert those calls to something equivalent for CHIP.
bcm2835_gpio_write()
bcm2835_gpio_fsel()
bcm2835_gpio_lev()
bcm2835_init()
@infrapro: Can you post a sample of any working code you have using GPIO 132? It appears that you are using libsoc from.
libsoc
I've tested bitbanging with CSI port (pin 132), and it works much faster than via XIO, but for me is not enough. Below you can find speed comparision I made by logic analizer. So, max frequency through XIO (pin 408) is 4KHz, CSI (pin 132) - 166Khz.
XIO
CSI
This is example GPIO manipulation through libsoc, I've tested with -O3 optimization flag
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include "libsoc_gpio.h"
#define GPIO_OUT 408 // 132
int main()
{
int ret = -1;
gpio *gpio_output = libsoc_gpio_request(GPIO_OUT, LS_SHARED);
if (gpio_output == NULL)
{
printf("Faile to open GPIO %d\n", GPIO_OUT);
goto fail;
}
libsoc_gpio_set_direction(gpio_output, OUTPUT);
if (libsoc_gpio_get_direction(gpio_output) != OUTPUT)
{
printf("Failed to set direction to OUTPUT\n");
goto fail;
}
int i;
for (i = 0; i < 1000; ++i)
{
libsoc_gpio_set_level(gpio_output, HIGH);
libsoc_gpio_set_level(gpio_output, LOW);
}
ret = 0;
fail:
if (gpio_output)
{
libsoc_gpio_free(gpio_output);
}
return ret;
}
compile:gcc -lsoc -O3 main.c -o main
You can do the exact same memory mapped I/O thing that the bcm2835 functions do but you need to convert the memory address. The base address for the gpio pins on the the A13 is 0x01C20800 but I think the register layouts are somewhat similar so just adjust the bitfield calculations. See the Port Register List / Port Register Description chapters in the A13 User Manual for their layout.
I used the CSI pins to bitbang avrdude, results were 450 bits per second effective throughput on XIO, 13,150 bits effective throughput per second on the CSI. I couldn't get 129 (CSI_MCLK/SPI2_CLK) to switch to output so I had to move down to CSID* pins.
I have look to sunxi-tools sources and found there GPIO manipulation via memory mapping in pio.c file. I've used some parts of code and made performance test and I've surprised with wonderful speed. With -O3 optimization my logic analyzer can't capture frame on top sample rate (24MHz)! It means that speed more faster, I can see it only if set sleep in loop or without optimizationBelow example code listing. Pin 132 is equivalent for port PE4, so we use 2nd and 3+rd letters to port access
pio_get(buff, 'E', 4, &pio);
Example:
#define _DEFAULT_SOURCE
#define _BSD_SOURCE
#include <errno.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "endian_compat.h"
#define PIO_REG_SIZE 0x228 /*0x300*/
#define PIO_PORT_SIZE 0x24
struct pio_status {
int mul_sel;
int pull;
int drv_level;
int data;
};
#define PIO_REG_CFG(B, N, I) ((B) + (N)*0x24 + ((I)<<2) + 0x00)
#define PIO_REG_DLEVEL(B, N, I) ((B) + (N)*0x24 + ((I)<<2) + 0x14)
#define PIO_REG_PULL(B, N, I) ((B) + (N)*0x24 + ((I)<<2) + 0x1C)
#define PIO_REG_DATA(B, N) ((B) + (N)*0x24 + 0x10)
#define PIO_NR_PORTS 9 /* A-I */
#define LE32TOH(X) le32toh(*((uint32_t*)(X)))
static int pio_get(const char *buf, char port_name, uint32_t port_num, struct pio_status *pio)
{
uint32_t port = port_name - 'A';
uint32_t val;
uint32_t port_num_func, port_num_pull;
uint32_t offset_func, offset_pull;
port_num_func = port_num >> 3;
offset_func = ((port_num & 0x07) << 2);
port_num_pull = port_num >> 4;
offset_pull = ((port_num & 0x0f) << 1);
/* func */
val = LE32TOH(PIO_REG_CFG(buf, port, port_num_func));
pio->mul_sel = (val>>offset_func) & 0x07;
/* pull */
val = LE32TOH(PIO_REG_PULL(buf, port, port_num_pull));
pio->pull = (val>>offset_pull) & 0x03;
/* dlevel */
val = LE32TOH(PIO_REG_DLEVEL(buf, port, port_num_pull));
pio->drv_level = (val>>offset_pull) & 0x03;
/* i/o data */
if (pio->mul_sel > 1)
pio->data = -1;
else {
val = LE32TOH(PIO_REG_DATA(buf, port));
pio->data = (val >> port_num) & 0x01;
}
return 1;
}
static int pio_set(char *buf, char port_name, uint32_t port_num, struct pio_status *pio)
{
uint32_t port = port_name - 'A';
uint32_t *addr, val;
uint32_t port_num_func, port_num_pull;
uint32_t offset_func, offset_pull;
port_num_func = port_num >> 3;
offset_func = ((port_num & 0x07) << 2);
port_num_pull = port_num >> 4;
offset_pull = ((port_num & 0x0f) << 1);
/* func */
if (pio->mul_sel >= 0) {
addr = (uint32_t*)PIO_REG_CFG(buf, port, port_num_func);
val = le32toh(*addr);
val &= ~(0x07 << offset_func);
val |= (pio->mul_sel & 0x07) << offset_func;
*addr = htole32(val);
}
/* pull */
if (pio->pull >= 0) {
addr = (uint32_t*)PIO_REG_PULL(buf, port, port_num_pull);
val = le32toh(*addr);
val &= ~(0x03 << offset_pull);
val |= (pio->pull & 0x03) << offset_pull;
*addr = htole32(val);
}
/* dlevel */
if (pio->drv_level >= 0) {
addr = (uint32_t*)PIO_REG_DLEVEL(buf, port, port_num_pull);
val = le32toh(*addr);
val &= ~(0x03 << offset_pull);
val |= (pio->drv_level & 0x03) << offset_pull;
*addr = htole32(val);
}
/* data */
if (pio->data >= 0) {
addr = (uint32_t*)PIO_REG_DATA(buf, port);
val = le32toh(*addr);
if (pio->data)
val |= (0x01 << port_num);
else
val &= ~(0x01 << port_num);
*addr = htole32(val);
}
return 1;
}
int main()
{
char *buff = malloc(PIO_REG_SIZE);
int pagesize = sysconf(_SC_PAGESIZE);
int addr = 0x01c20800 & ~(pagesize - 1);
int offset = 0x01c20800 & (pagesize - 1);
int fd = open("/dev/mem",O_RDWR);
if (fd == -1) {
perror("open /dev/mem");
exit(1);
}
buff = mmap(NULL, (0x800 + pagesize - 1) & ~(pagesize - 1), PROT_WRITE | PROT_READ, MAP_SHARED, fd, addr);
if (!buff) {
perror("mmap PIO");
exit(1);
}
close(fd);
buff += offset;
struct pio_status pio;
pio_get(buff, 'E', 4, &pio);
pio.mul_sel = 1;
pio.data = 0;
pio.drv_level = 0;
while(1)
{
pio.data = !pio.data;
pio_set(buff, 'E', 4, &pio);
//usleep(1);
}
return 0;
}
Excellent! I'll start experimenting with it pretty soon.
I've been doing more experimentation with bit-banging CSI GPIO pins using "/sys/class/gpio" driver, producing a steady square wave using clock_gettime() and busy waiting. With CSI pins, I can get a pretty uniform square wave. But from time to time, Linux will steal the CPU away for periods of time on the order 10 ms. I think the kernel decides that the process thread has exhausted its time quantum and it lets other processes a chance to run.
This makes sense since the CPU only as a single core. Linux doesn't need much, but it needs some.
Basically, a single core Linux system isn't going to be a reliable source of long-running, bit-banged signalling.
@infrapro - Yev, congratulations, you've surpassed the speed of light ... well, as far as your logic analyzer can tell
@fordsfords - Steve, "You're gonna need a bigger boat ... " and it's called the M/V (Merchant Vessel) Real-Time
And finally, there is libsoc fork with implementation for direct GPIO, it is not finished yet, but generally works. Example how to use you can find here
If you mean a "Linux Real-Time" kernel, that still won't help when the important thread (the one doing the time-critical timing) is 100% CPU bound. For any kind of multi-threading to work requires that high-priority threads spend at least some amount of time asleep (in the operating system sense). If a high-priority thread is alseep, it needs something to wake it up. The normal Unix sleep functions (including nanosleep) are VERY inaccurate at small sleep times since they depend on the periodic Unix clock interrupt, which typically has a 1 ms period.
One interesting question which has been asked a few times is whether one of the header pins can be used as an interrupt. This could allow running a MUCH higher rate clock, although there are limits there as well. Server grade processors start to sweat at interrupt rates above 100,000 per second. Another barrier to easy use would be that an interrupt automatically puts Linux into Kernel mode, and kernel programming is a horse of a different color. The transition between kernel and user space represents a large overhead, and is a major reason for the current speed limit of CSI access via the "/sys/class/gpio" driver. The best way to implement high-accuracy, high-rate timing would be to write most of the code in the form of a kernel module and use interrupts. Not being a kernel wonk, it would take me quite a while to figure that out.
Alternatively, the use of a microcontroller is conceptually the same as adding a core to CHIP, and has the advantage that it doesn't have Linux. A CHIP/microcontroller combo gives you CHIP for WIFI, SSL, Bluetooth, graphics, USB, user interface work, and the microcontroller for busy-looping pulse generation, etc. (Although I must admit that I've never programmed a microcontroller either.)
@fordsfords - Steve, who said anything about Linux? There are real real-time OSes Out There that are used by the embedded and industrial controller sectors (Rockwell Automation, Allen-Bradley, National Instruments, etc.) in every domain, such as manufacturing, assembly lines, chemical/biological processing, food processing, vehicle control ... even semiconductor fabrication (the controllers control fabbing of the devices used to make the controllers ... whoa, how meta, man!).
Of course, we need something that will run on ARM, so our choices are narrowed, and if we want open-source, they're even more limited, but surprisingly, here's that list of options: uKOS, Atomthreads, BeRTOS, BRTOS, CapROS, ChibiOS/RT, ChronOS, CoActionOS, Contiki, distortos, dnx, eCos, Embox, ERIKA Enterprise, EUROS, FreeOSEK, FreeRTOS, FunkOS, Fusion, FX, ISIX, ISIX, iRTOS, Lepton, Milos, mipOS, MMLite, MQX, Neutrino, nOS, Nucleus OS, Nut/OS, NuttX, OpenEPOS, OS21, OpenRTOS, picoOS, QP, RIOT, RTAI, RTEMS, RT-Thread, RTX Keil, scm, SDPOS, sil, T-Kernel, TI-RTOS Kernel, Trampoline, TNKernel, TNeo, TUD:OS, Unison, Xenomai, Y@SOS, and uOS (some of these may be based on real-time Linux kernels, so downloader beware).
Also, many only run on certain ARM architectures, mostly v7 and Cortex M3, and many may not be compatible with drivers for some/all of the peripherals that the C.H.I.P. has, so a lot of ferreting through docs and source would be needed. Since they are open-source though, one could theoretically stitch together a Frankenstein (C.H.I.P.enstein?) of the features needed from code that is compatible with the R8, if none of these fulfills all of your needs. It sure beats starting from scratch at the bare-metal level in assembly, unless you're already an expert or you want to learn to become one, and there's certainly nothing wrong with that.
@infrapro I've been testing this, and I would say this is not going so fast... In my 2GS/s scope there is no squared signal. To me this means that -O3 (also -O2 and -O) optimization, are being too clever and not performing the actual code. If you make a change and instantly make the change back, the optimizer takes the code away. It is not the first time this happens to me, so be careful with -OX...
Is anyone able to confirm this?
Consider also to memlock and set the linux schedule to fifo.Has seen this on raspberry pi.Something like this. if you address to the register in direct memory access.And seen they also include the rt (real time library) -L rt
-L rt
C++#include <sys/mman.h>using namespace std;
#include <sys/mman.h>
using namespace std;
int main() {// Set the maximum possible priority and switch from regular Linux// round-robin to FIFO fixed-priority scheduling.struct sched_param sp;sp.sched_priority = sched_get_priority_max(SCHED_FIFO);if (sched_setscheduler(0, SCHED_FIFO, &sp)<0) { // change schedulingcout << "Failed to switch from SCHED_RR to SCHED_FIFO" << endl;return 1;}// lock the process' memory into RAM, preventing page swapping.if (mlockall(MCL_CURRENT|MCL_FUTURE)<0) { // lock cur & future pagesstd::cout << "Failed to lock the memory." << std::endl;return 1;}...munlockall(); // unlock the process memory
int main() {
// Set the maximum possible priority and switch from regular Linux
// round-robin to FIFO fixed-priority scheduling.
struct sched_param sp;
sp.sched_priority = sched_get_priority_max(SCHED_FIFO);
if (sched_setscheduler(0, SCHED_FIFO, &sp)<0) { // change scheduling
cout << "Failed to switch from SCHED_RR to SCHED_FIFO" << endl;
return 1;
}
// lock the process' memory into RAM, preventing page swapping.
if (mlockall(MCL_CURRENT|MCL_FUTURE)<0) { // lock cur & future pages
std::cout << "Failed to lock the memory." << std::endl;
.
munlockall(); // unlock the process memory
Cstruct sched_param sp;memset(&sp, 0, sizeof(sp));sp.sched_priority = sched_get_priority_max(SCHED_FIFO);sched_setscheduler(0, SCHED_FIFO, &sp);mlockall(MCL_CURRENT | MCL_FUTURE);
memset(&sp, 0, sizeof(sp));
sched_setscheduler(0, SCHED_FIFO, &sp);
mlockall(MCL_CURRENT | MCL_FUTURE); | https://bbs.nextthing.co/t/solved-gpio-direct-access/2971 | CC-MAIN-2017-43 | refinedweb | 2,462 | 53.21 |
The Technical Preview of Flutter Web was just announced at Google I/O 2019. To celebrate, I've ported the hangman app from our previous tutorial from Flutter to Flutter Web. We had to move things around a little bit, but it was actually quite easy.
Download
Visit the GitHub Repository to clone the source for this application.
This code was tested with Flutter Web Technical Preview (webdev 2.0.4) and Flutter 1.5.4
The Approach
We're going to make a new dart project (not flutter) for our flutter web app, copy/paste our source around, add "_web" to some imports, then build our application. It's pretty straight forward.
Setup
Install the flutter_web build tools:
flutter packages pub global activate webdev. If you run into issues building additional setup instructions can be found on the Flutter Web GitHub Repository, but this command the core of what you need.
Install the dart tools:
pub global activate stagehand
Create a new directory for the project and navigate to that directory in your favorite terminal app. Now, use stagehand to create our basic project files:
stagehand flutter-web-preview.
Lastly, the hardest part. Run
pub get in your project directory to install the dependencies.
NOTE: We can't currently use Android Studio to create a flutter_web app since the dart plugin doesn't have "New Project" support. We can use IntelliJ or VS Code to create a dart project, but it's easier to use
stagehandin this instance.
ANOTHER NOTE: We can't use flutter to create a flutter_web app yet, either. The flutter team is currently developing flutter_web on a fork, and are working on consolidating the two code bases. At this point, we have to make a few modifications to our code to get it to work with flutter_web. In the future, it'll be the same code that will work for both.
The Code
Step 1: Copy the "App" code
We're going to just copy the app code directly from our hangman app (which, if you will recall, has the engine code copied directly from Monty's Hangman Repo). Copy everything from the app's /lib directory into our new project's
/lib folder.
That was easy. Next.
Step 2: Copy the assets
Create a new directory at
/web/assets in our project. Copy the
/img directory from the app's /data_rep directory into the new
/web/assets directory we just created.
All the code and assets are currently broken, let's fix them up.
Step 3: Make it build
Errors suck. It's time to hit the project with the Fix-It Felix hammer.
Step 3.1: Add the assets to our
pubspec.yaml file
flutter: assets: - img/
It should be noted that the paths in the
assets array are all relative to our project's
/web/assets directory. Missing assets currently don't throw an error, they just silently fail and never show up.
Step 3.2: Update our imports
Update the
flutter/material.dart import in
main.dart and
ui/hangman_page.dart as follows:
import 'package:flutter_web/material.dart';
Yep, we're just adding the
_web there.
Lastly... change the remaining imports at the top of
main.dart to be local imports instead of fully qualified package imports.
import './engine/hangman.dart'; import './ui/hangman_page.dart';
It was silly that these were fully qualified imports to begin with, so let's pretend this never happened...
Step 4: Test and Build
Now all that's left is to actually build and serve the app and test it out.
If you followed the additional setup instructions (that I said you didn't need to) and added webdev to your path, then you can simply use
webdev serve from the project's directory to start the local test server.
If that gives you errors, or it is not on your path, you'll have to use the longer
pub global run webdev serve.
Now you can visit and play hangman just like we used to do together on our phone.
You can use
webdev build to compile everything for deployment on the web. The compiled files can be found in the newly created
/build directory.
NOTE: flutter_web, in its current Technical Preview state, isn't ready for prime time, yet. Have fun with it, but please reconsider using it for a production app until it's at least in beta.
Summary
As you can see, with very minimal code changes we were able to get our existing flutter app running on the web using flutter_web. Look forward with excitement to more updates to this platform. | https://flutter.institute/simple-games-with-flutter-web-hangman/ | CC-MAIN-2019-39 | refinedweb | 770 | 65.12 |
postwait_post, postwait_postn, postwait_post_deferred - Post user events to a key to notify one or more waiters.
#include <port.h>
int postwait_post(postwkey_t key, int uevents, uintptr_t udata);
int postwait_postn( postwkey_t klist[], postwkey_uevdata_t userd[], int errors[], uint_t nent);
int postwait_post_deferred( postwkey_t key, int flags, int uevents, uintptr_t udata);
The postwait_post(), postwait_postn(), and postwait_post_deferred() functions allow threads to post events as part of a post-wait mechanism. Threads can wait and retrieve these events via event ports.
Post events consist of an user defined integer type event and an unsigned long item of opaque user data. Both fields are available to the receiving threads.
The post-wait mechanism can be used between threads in the same or different processes. A key is used as the rendezvous point for posting and waiting; these 64 bit keys are generated by postwait_genkey(3C) call and shared with other processes using any desired form of IPC. No limitations are placed on which processes may use which keys.
The postwait_post() function causes an event of type PORT_SOURCE_POSTWAIT and the associated user values to be delivered to any event ports that are associated with the specified key. For more information, see port_associate(3C).
The postwait_postn() function posts multiple post events to multiple keys with one system call. Passing NULL for the errors argument could cause this function to post asynchronously with the help of background worker threads. The list of keys to be posted to are passed in the klist array argument. The corresponding user events and user data are passed in the array of struct postwkey_uevdata_t. The number of elements of this array is specified in nent argument. Passing NULL for userd causes 0 to be used as the value of uevents and udata.
The postwkey_uevdata_t structure contains the following members:
int pwev_uevents; uintptr_t pwev_udata;
The postwait_post_deferred() function is for registering a deferred post. With PWPOST_ATEXIT specified in flags, the deferred post is delivered when the thread that registered the post exits the containing process exits or is killed. Calling postwait_post_deferred() with PWPOST_CANCEL flag will cancel any outstanding deferred post registered for the key by this thread. There can be only one deferred post registered by a thread per key.
If PWPOST_VALIDATE_KEY is or'd with PWPOST_ATEXIT , it checks if the key specified is associated with an event port or not. If not, the deferred post registration for that key will fail.
To receive post events, the key needs to be associated with an event port. Threads collect the post events from the event port. Delivery of the post event and user values is determined by the associating type of key. Two types of association are permitted: counting and queuing. For more information, see port_associate(3C).
For a counting type association, multiple posts that occur before the event is retrieved will be combined resulting in just one event delivery to the event port. A count indicating how many times the key was posted since the last time that an event for that key was collected is returned along with the event. Both the user event and the user data submitted with the post will be ignored for this type of association.
For a queuing type association, one event for each post will be queued on the event port. The user event and user data passed are delivered with the posted event. The number of events that can get queued on an event port is subject to the process.max-port-events resource limit. For more information, see the rctladm(8) man page.
The count and the user values are delivered in the port_event_t structure. The events from an event port are collected using port_get(3C) or port_getn(3C) calls.
If a key is associated with more then one event port, a post to that key will result in delivery of the same event to each of those ports.
Upon successful completion, postwait_post() will return 0. Otherwise, it will return -1 and sets errno to indicate the error.
In the synchronous mode, the postwait_postn() function returns the number of successfully submitted events. A non-negative return value less than the nent argument indicates that at least one error has occurred. In this case, each element of the errors[] array is filled in. An element of the errors[] array is set to 0 if the post event was successfully sent to the corresponding key in the klist[] array, or is set to indicate the error if not successful.
In the asynchronous mode, postwait_postn() function returns the number of successfully handed-off events. If an error occurs with the postwait_postn() call, it returns -1 and sets errno to indicate the error.
The postwait_post_deferred() function returns 0, if the deferred post is registered or cancelled successfully. Otherwise it returns -1 and the errno is set to indicate the error.
The postwait_post() and synchronous mode postwait_postn() functions will fail if:
The maximum number of events per port is exceeded. The maximum allowable number of events per port is the minimum value of the process.max-port-events resource control at the time port_create(3C) was called to create the event port to which the key is associated.
The event cannot be delivered as the specified key currently is not associated with any event ports.
The postwait_post() and postwait_postn() functions will fail if:
There is not enough memory available to satisfy the request.
The postwait_postn() function will fail if:
The klist[] or userd[] or errors[] pointer is invalid.
The postwait_post_deferred() function will fail if:
If there is already a deferred post registered for the specified key.
If the PWPOST_CANCEL flag is passed and there is no deferred post registered for the specified key or the value passed in flags argument are invalid.
If the thread has already registered maximum number of allowed deferred posts defined by process.max-deferred-posts resource control.
If PWPOST_VALIDATE_KEY flag was or'd with PWPOST_ATEXIT, and the key specified is currently not associated with any port. Note that after the key has been validated here, it is possible that the process that has associated the key can exit or get killed. As a result, the key may no longer be associate with any event port. However, a different process can subsequently associate the same key with an event port.
See attributes(7) for descriptions of the following attributes:
port_create(3C), port_sendn(3C), postwait_genkey(3C), resource-controls(7) | https://docs.oracle.com/cd/E88353_01/html/E37843/postwait-postn-3c.html | CC-MAIN-2019-35 | refinedweb | 1,058 | 54.93 |
[
]
Weiwei Yang commented on HDFS-11781:
------------------------------------
I am a bit hesitated on when is the right time to remove the key from KSM database, that is
to say the time a key becomes to be invisible for a client. We might want to take a look at
HDFS-11886, similar problem. Delete a key generally took 2 steps
# Delete a key from KSM namespace
# Delete the key data (object value) from datanodes via SCM
the second step may fail on some sanity checks before actual jobs, such as
# Node is in chill mode
# FAILED_TO_FIND_BLOCK
# ...
in such cases, we cannot reach the point that SCM sends async delete command to datanodes,
which means it becomes to be an orphan block and will not be removed forever. Unless we have
a background thread to scan orphan blocks and cleanup them periodically. Or since SCM layer
state is not changed, we can try-catch such exceptions and make the deleteKey fail, do not
commit that to KSM (or a simply rollback). We may want another JIRA to track this issue, similar
to HDFS-11886. [~yuanbo], [~xyao], [~anu], what's your position?
> Ozone: KSM: Add deleteKey
> -------------------------
>
> Key: HDFS-11781
> URL:
> Project: Hadoop HDFS
> Issue Type: Sub-task
> Components: ozone
> Affects Versions: HDFS-7240
> Reporter: Anu Engineer
> Assignee: Yuanbo Liu
> Attachments: HDFS-11781-HDFS-7240.001.patch, HDFS-11781-HDFS-7240.002.patch
>
>
> Add support for removing a key.
--
This message was sent by Atlassian JIRA
(v6.3.15#6346)
---------------------------------------------------------------------
To unsubscribe, e-mail: hdfs-issues-unsubscribe@hadoop.apache.org
For additional commands, e-mail: hdfs-issues-help@hadoop.apache.org | http://mail-archives.apache.org/mod_mbox/hadoop-hdfs-issues/201706.mbox/%3CJIRA.13070277.1494307572000.342616.1496332924379@Atlassian.JIRA%3E | CC-MAIN-2018-30 | refinedweb | 266 | 61.77 |
This article explains how to quickly setup Cloudera Security/Governance/GDPR (Worldwide Bank) demo using Cloudera Data Platform - Private Cloud Base (formerly known as CDP-Data Center). It can be deployed either on AWS using AMI or on your own setup via provided script
yum install -y git #setup KDC curl -sSL | sudo -E sh git clone cd SingleNodeCDPCluster ./setup_krb.sh gcp templates/wwbank_krb.json #Setup worldwide bank demo using script curl -sSL | sudo -E bash
ssh -i ~/.ssh/mykey.pem centos@<publicIP>
tail -f /var/log/cdp_startup.log
CDP urls
hive.execute("SELECT surname, streetaddress, country, age, password, nationalid, ccnumber, mrn, birthday FROM worldwidebank.us_customers").show(10) hive.execute("select zipcode, insuranceid, bloodtype from worldwidebank.ww_customers").show(10) hive.execute("select * from cost_savings.claim_savings").show(10)
Similarly, you can log in to Zeppelin as etl_user and run his notebook as well
This notebook shows how an admin would handle GDPR scenarios like the following using Hive ACID capabilities:
Alternatively, you can log in to Hue as joe_analyst and select Query > Editor > Hive and click Saved queries to run Joe's sample queries via Hive:
You can also switch the editor to Impala to run Joe's sample queries via Impala to show tag-based access policy working for Impala:
In CDP 7.1.1, Impala also supports column-based masking:
Alternatively, you can log in to Hue as ivanna_eu_hr and click Saved queries to run Ivanna's sample queries via Hive:
To run secure SparkSQL queries (using Hive Warehouse Connector):
kinit -kt /etc/security/keytabs/joe_analyst.keytab joe_analyst/$(hostname -f)@CLOUDERA.COM
spark-shell --jars /opt/cloudera/parcels/CDH/jars/hive-warehouse-connector-assembly*.jar --conf spark.sql.hive.hiveserver2.jdbc.url="jdbc:hive2://$(hostname -f):10000/default;" --conf "spark.sql.hive.hiveserver2.jdbc.url.principal=hive/$(hostname -f)@CLOUDERA.COM" --conf spark.security.credentials.hiveserver2.enabled=false
import com.hortonworks.hwc.HiveWarehouseSession import com.hortonworks.hwc.HiveWarehouseSession._ val hive = HiveWarehouseSession.session(spark).build()
hive.execute("select * from cost_savings.claim_savings").show(10)
/tmp/masterclass/ranger-atlas/HortoniaMunichSetup/run_spark_sql.sh
In case you encounter Thrift Exception like the following, it's likely the session was expired:
Just scroll to the top and click the gears icon (near top right) to display the interpreters and restart the JDBC one:
Appendix:
The following are some older AMI links (for HDP releases):
@abajwa , I have tried to use the given AMI trail version added to the given AMI file?
Thanks in advance
@AkhilTech thanks for your question. We just updated the article to include a link to a new AMI based on CDP 7.1.3. Alternatively, you can also use the script to deploy instead, which will give you a new trial license each time. To request a permanent license you can contact our sales team:
I have a problem with the AMI
I'm using 0b3b57b9fa9a742ee so the: CDP-DC 7.1.3 with WorldWideBank demo v4
The machine has started but it is showing:
Are those images obsolete?
Trying to get this working in a VMWare VM on an on-premise server. Running into a number of issues which I will try to troubleshoot but one thing that would help a lot, I think, is stating how much disk space is required at the outset. I have tried a couple of times and run into issues that seem to be related to not enough space on root or some other file system. I did find in a README that I probably need at least 100GB -- would have been useful to know that before I created the VM.
Sorry to complain but eager to get this working, finally, after a failed attempt about six months ago.
@boulder the AMI comes with trial license of CM which expires after 90 days. At that point, the services are all up but in order to open CM you would need to add a license.
Note: We just updated the article with an updated 7.1.4 AMI which has a fresh trial.
You can also use the script option to spin up a fresh cluster which gives a new trial license each time
@antonio_r thanks yes you'd need a VM with roughly the same specs as an m4.4xlarge would. Have updated the article with to include specs for option #1 as well
Thanks for the clarification and for your efforts overall.
I tried the self-install on a Centos EC2 instance and that mostly worked. A number of the services report health issues-- HDFS shows up in CM as not starting, for example-- but surprisingly things seem to work anyway. I can run queries in the notebooks, for example, and the Ranger permissions apply.
I will revisit my home environment VM and see if I have better luck. (I give it ample resources -- 24 virtual CPUs and 96GB RAM and 150GB storage-- but I still seemed to hit issues.)
Are there any unusual features that the networking in EC2 provides vs. a vanilla VM? For example, the EC2 env answers at an internal AWS IP address as well as the public facing one. Do the services communicate with each other in some way that may require that? Do I need to reproduce that for my self-hosted VM to work? Do I, for example, need more than one virtual NIC?
@antonio_r after running the script, I noticed some services show weird state (even though they are up). You can restart "Cloudera Management Service" (scroll down to the bottom of the list of services, under Zookeeper)...that usually fixes it for me
Vanilla VM should work the same way...I have installed using the script on our internal Openstack env w/o issues. You should not require both internal/public IP. Just make sure the networking is setup as required by Hadoop:...
thanks for the suggestion, I will investigate at next opportunity (probably over the weekend).
I am QUITE sure that I did not have the "Configure Network Names" steps done correctly when I tried several months ago, but I just couldn't figure out how to fix it. This should help quite a bit.
Just make sure the networking is setup as required by Hadoop:...
That was the missing detail! For anyone else who tries this in VMWare
a) Do the network setup as described above on your host before you start the steps in this document
b) At the end of the networking instructions I struggled with
"Run host -v -t A $(hostname) and verify that the output matches the hostname command. The IP address should be the same as reported by ifconfig for eth0 (or bond0)..."
I found that I needed my own DNS server within the environment to make the networking stuff finally behave as described. I set up an instance of "dnsmasq" in my Centos Linux environment -- it's compact, lightweight, included with CentOS, and took about 3 minutes to configure, following the instructions here:
About five lines of config and I was off to the races
@antonio_r Glad to hear it! Thanks for providing the details to help the next person. Have updated the article with the link to the networking prereqs. Enjoy your new cluster!
Created on 02-23-2021 04:09 AM
@Rajesh2622 you can find the CSV files containing the data under (e.g. ww_customers_data.csv)
@abajwa I have tried to use the given AMI 7.3/7.4 trial version added to the given AMI file?
Thanks in advance
@abajwa Hi, thanks for your help in the past.
Now I have a new question: I want to try adding the Amundsen open source data catalog to the environment to see how it exposes all the datasets that you've populated. It depends on the availability of LDAP or similar to recognize the user who's viewing the data in the system.
Is there some local LDAP or other identity service included in this demo environment?
Thanks for any pointers, -Antonio | https://community.cloudera.com/t5/Community-Articles/How-to-setup-Cloudera-Security-Governance-GDPR-Worldwide/tac-p/311030 | CC-MAIN-2021-21 | refinedweb | 1,328 | 63.49 |
Introduction
The linked list is one of the most important concepts and data structures to learn while preparing for interviews. Having a good grasp of Linked Lists can be a huge plus point in a coding interview.
Problem Statement
In this question, we are given a binary tree. We have to extract all the leaves of it in a Doubly Linked List. We should note that the Doubly Linked List should be created in place.
Problem Statement Understanding
We should assume that the node structure of the doubly linked list and the binary tree is the same. What changes is the meaning of left and right pointers. In the Doubly linked list, left means the previous pointer and right means the next pointer.
A leaf node is a node which has no children. So, we have to traverse through the tree and whenever we find a leaf node, we will add it to our Doubly Linked List.
Input:
Input Binary Tree
Output:
Doubly Linked List
Modified Binary Tree
Explanation:
As the leaf nodes of the binary tree are 4, 5 and 3, they will be inserted in a doubly-linked list.
We are going to traverse through the given binary tree and whenever we reach a leaf node, we will add it to our doubly linked list. Let us have a look at the approach.
Approach
We are going to use recursion to solve this problem. If the root of the tree is NULL, then we will simply return NULL. This is going to be our base case. If the base case fails, then we will check if the current node is a leaf node or not.
If the current node is a leaf node, then we will change pointers and remove that node from the binary tree and add it to our doubly linked list. If the current node is not a leaf node, we will recur for the right and left subtrees of the node. In the end, we will simply return the root.
Algorithm
- Base case - If the root is NULL, return NULL
- If the root is a leaf node, then we will set the root’s right pointer as the previous head of the doubly linked list. We don’t need to set the left pointer as the left is already NULL
- Now, change the left pointer of the previous head I.e. the left of the head will point to root.
- Make root the new head.
- Return NULL
- If the above condition fails, then recur for the left and right subtrees.
- In the end, return root.
Dry Run
Code Implementation
Extract the leaves of a Binary Tree in a Doubly Linked List
#include
using namespace std; class Node { public: int data; Node *left, *right; }; Node* extractLeafList(Node *root, Node **head_ref) { // Base case] if (root == NULL) return NULL; if (root->left == NULL && root->right == NULL) { // The right of the root is going to point to the previous head root->right = *head_ref; // Changing the left pointer of previous head to root if (*head_ref != NULL) (*head_ref)->left = root; // Making root our new head *head_ref = root; return NULL; // } // Recur for right and left subtrees root->right = extractLeafList(root->right, head_ref); root->left = extractLeafList(root->left, head_ref); return root; } Node* newNode(int data) { Node* node = new Node(); node->data = data; node->left = node->right = NULL; return node; } void print(Node *root) { if (root != NULL) { print(root->left); cout< data<<" "; print(root->right); } } void printList(Node *head) { while (head) { cout< data<<" "; head = head->right; } } int main() { Node *head = NULL; Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << "Inorder Trvaersal of given Tree is:\n"; print(root); root = extractLeafList(root, &head); cout << "\nExtracted Double Linked list is:\n"; printList(head); cout << "\nInorder traversal of modified tree is:\n"; print(root); return 0; }
class Node { int data; Node left, right; Node(int item) { data = item; right = left = null; } } public class BinaryTree { Node root; Node head; Node prev; public Node extractLeafList(Node root) { if (root == null) return null; if (root.left == null && root.right == null) { if (head == null) { head = root; prev = root; } else { prev.right = root; root.left = prev; prev = root; } return null; } root.left = extractLeafList(root.left); root.right = extractLeafList(root.right); return root; } public void printDLL(Node head) { Node last = null; while (head != null) { System.out.print(head.data + " "); last = head; head = head.right; } } void inorder(Node node) { if (node == null) return; inorder(node.left); System.out.print(node.data + " "); inorder(node.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(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); System.out.println("Inorder traversal of given tree is : "); tree.inorder(tree.root); tree.extractLeafList(tree.root); System.out.println(""); System.out.println("Extracted double link list is : "); tree.printDLL(tree.head); System.out.println(""); System.out.println("Inorder traversal of modified tree is : "); tree.inorder(tree.root); } }
Output:
Inorder Traversal of given Tree is:
4 2 5 1 3
Extracted Double Linked list is:
4 5 3
In order traversal of the modified tree is:
2 1
[forminator_quiz id="3529"]
Space Complexity: O(number of leaf nodes), as the doubly linked list will contain the leaf nodes.
So, in this article, we have tried to explain the most efficient approach to extract leaves of a binary tree in a doubly-linked list. If you want to solve more questions on Linked List, which are curated by our expert mentors at PrepBytes, you can follow this link Linked List. | https://www.prepbytes.com/blog/linked-list/extract-the-leaves-of-a-binary-tree-in-a-doubly-linked-list/ | CC-MAIN-2022-21 | refinedweb | 946 | 70.84 |
Spoiler Alert
You should go and check this out, git-game.
It’s a nice little complete-a-task-and-upgrade-level type of game layered on top of Git.
It is a terminal game designed to test your knowledge of git commands. Each level in the game is a task to perform on this repo. Once you perform that task, you will be given your next task. There are a total of ten levels, each one harder than last!
I saw the reference to this game floating around in my GitHub feed yesterday. The concept is awesome as there are already many online tutorial courses on the Internet that uses interactive learning-with-doing methods for Git.
According to the repository, I started the adventure with cloning the repository using
git clone [email protected]:hgarc014/git-game.git command.
The default branch was master and there were only two files in repository’s working directory, README.md and LICENSE.
I started with the README.md file and
cat README.md revealed all its content.
You should always check the README.md file for your next clue!
Your first task is to checkout the commit whose commit message is the answer to this question:
When a programmer is born, what is the first thing he/she learns to say?
Well! a programmer is also a boy/girl, so first thing they do is cry but in the current context that thing will be Hello, World! :grinning:
Now I had to find the commit whose commit message was Hello World, so the command
git log --graph --online resulted this commit history.
* 25bfa08 added information for people that don’t know git
* 27e9786 Merge pull request #6 from riqpe/master
|
| * 3893960 Corrected description of difficulty progression
|/
* bc9641f updated README
* 9b9380b Hello World!
* 8cafb7c Initial commit
Can you see the Hello World! commit now? Yeah! we can represent it by HEAD~3. As that commit is directly at level 3 or we can say great-grandparent of the HEAD commit.
So all I needed to do was the command
git checkout HEAD~3, doing so we’re now done with the first task.
After completing the first task when the HEAD is at that particular commit, the README.md file was ready with its new task.
git-game
========
Hello World!
It looks like you have some knowledge about traversing commits!
Well, let’s get this party started!
We want to get to a branch whose name is the answer to this riddle:
I am a creature that is smaller than man, but many times more in number.
In code, my appearance can be subtle and no matter where I am found, I am unwanted.
What am I?
Easy Peasy? Yeah, the answer is bug obviously, so lets fly to same branch using the
git checkout bug command.
In this branch’s working directory there were two extra files, cool.cpp and remember and the README.md was saying that :
git-game
========
Congratulations, it looks like you found the “bug.”
When you work with other programmers on the same project, bugs are bound to appear.
One way to create bugs is by changing code that you did not write without understanding what the code is doing.
Sometimes we like to blame others for introducing bugs in our code.
Think you can find out who introduced a bug into our file cool.cpp?
We think he had something to do with the development of git.
And from what we hear he also made a branch under his name.
Checkout to that branch after you find out who the culprit is.
It says that there is a bug in the file cool.cpp, lets see.
#include <iostream> using namespace std; int main() { string mesg = "Hello! Who are you?"; string input; cout << mesg << endl; cin >> input; cout << "Loops are fun!" << endl; while(1); string reply = "Well, " + input + ", we hope you are having fun with our git-game!"; cout << reply << endl; }
Yeah! there is one; the while loop will refuse the program from terminating.
So, who did this? Well! that’s what we have to answer now.
git blame - Helps you finding who committed what.
Show what revision and author last modified each line of a file
git blame cool.cpp is here for our rescue. It says that :
ce59bbfd (Henry Garcia 2014-12-08 18:22:35 -0800 10) cin >> input; 3922a6d8 (LinusTorvalds2014 2014-12-09 12:37:10 -0800 11) cout << "Loops are fun!" << endl; 3922a6d8 (LinusTorvalds2014 2014-12-09 12:37:10 -0800 12) while(1); ce59bbfd (Henry Garcia 2014-12-08 18:22:35 -0800 13) string reply = "Well, " + input + ", ...
Damn! someone with a similar name to the great Linus Torvalds is the culprit, he wrote that buggy line in the file. OK, lets move to his branch as the README says, using
git checkout LinusTorvalds2014 command.
This time the README.md file was not explicitly directing anywhere.
git-game ======== Looks like you found the branch of the evil Mastermind. Things may start to get a little more challenging... The next clue you are looking for -- is in a file you choose to ignore!
When I was doing this I thought may be it’s pointing to that useless file named remember which was back there in the branch bug.
So I checked-out again to the branch bug and tried to find any clue in the file remember. Its content looked like RSA Public keys to me.
cweJIY8GOo18Usi5ykA4nmhBR0h 6mMpyy4nFY71IhgjGGr0rkY3uE tVTo j5XlwgLZZ PpRK Pwbnd7Z4bpQWc6sU700xfLTI63FbD DsKCQbUKG KS02qfurxMJ3mHHD8f6VhFUmY2rPD NjznQ8mnQvlNwAR1QsLDK Zjl1kGbWQBeGoOBwVMfa790ATCNg fR OLPA0hi7OW N4jUN26mBIwQVhVtteDSDSr OVfhvUwb7ydODX7R2no xxTmrD5IFUXIB8dDhR lpSFaRcbF2up wrWA J2acmA28c2 NhE Bqj7ntV67GTHpVBSwO
I gave up after scrolling through the lengthy remember file and checked-out again to the branch LinusTorvalds2014.
I have a strange habit to use
ls -a instead of
ls to list content of a directory so I did it and Boy! there it was, hiding all this time.
Guess what? there was a file named .gitignore and it said :
# welcome to the ignore file!! # This file is hidden by default, # but did you know you have some branches that aren't shown to you, # when you check the list of branches? # # For your next clue... # Which abstract data type tends to implement sets and maps?? # The answer is the same answer to this riddle: # # I am both mother and father. # I am seldom still # yet I never wander. # I never birth nor nurse. # # What am I? # # Afterwards... well, you # know, checkout to the answer. *.rem a.out
This time the answer of riddle is Tree, simple. Don’t you know? You can google it any time, I did the same. :wink:
So the next thing to do was,
git checkout tree and the README.md file there said :
git-game ======== Welcome to the "tree" branch. Looks like good ol' Linus modified the "nextclue_input.cpp" file. Normally, when ran with the shell script "outputclue.sh", the "nextclue_input.cpp" file would give us the next hint. Maybe, you should try running the shell script with the "nextclue_input.cpp" file and see what happens... You can run the script by running the command "./outputclue.sh FILE" . If you are on Windows, it's okey to use `git-bash` that is installed with [msysgit]().
On executing the shell script with the nextclue_input.cpp, printed something on the STDOUT.
Linus has been here... I love messing with these amateur programmers!! If you want some real fun, then you should try resolving a conflict between this branch (tree) and code4life. I introduced a little bug that you should fix in the conflict. >:) After you merge these 2 files you should run the shell script again!! Good Luck!!!
The file outputclue.sh is a bash source file and matches the md5sum of each word in the nextclue_input.cpp to a local checksum variable named bug. It keeps asking to fix merge conflicts until the word matching that checksum is present in the file.
#!/bin/bash if [ -z $1 ]; then echo "well, someone didn't want to run the script with a file..."; exit; fi file=$1 bug=7c85d987a917c2a555d1391426978f05 mesg="Linus has been here...\nI love messing with these amateur programmers!!\nIf you want some real fun, then you should try resolving a conflict between this branch (tree) and code4life.\nI introduced a little bug that you should fix in the conflict. >:)\nAfter you merge these 2 files you should run the shell script again!!\n\nGood Luck!!!" merges=$(git log --format=%h --merges | head -1) csum="md5sum" if [ $(echo "$OSTYPE" | grep darwin) ];then csum="md5" fi if [ "$file" = "nextclue_input.cpp" ];then if [ ${merges} ]; then while read p; do for w in $p;do if [ `echo $w | $csum | awk '{print $1}'` = $bug ];then echo -e $mesg; exit; fi; done; done < $file ; echo -e "Well, congratulations!! You fixed my conflict!!\nIf you would like to continue, then you should checkout to the $(echo 90mP8ouQHsNe | tr -d '0-9A-Z') branch!!\n" ; else echo -e $mesg; exit; fi; else echo "Looks like you passed in the wrong file"; fi
I saw that the nextclue_input.cpp file was having a line with an infinite while loop and my guess was right, the checksum variable matched the md5sum of the term while(1);
So to fix the merge conflict, I did
git merge code4life and removed the faulty line; It worked like a charm.
Well, congratulations!! You fixed my conflict!! If you would like to continue, then you should checkout to the mouse branch!!
BTW! It was way more easy. As the answer branch was, mouse.
$ echo 90mP8ouQHsNe | tr -d '0-9A-Z'
When I checked-out to the branch mouse, it said :
nextclue_input.cpp: needs merge error: you need to resolve your current index first
But you can get away without merging by stashing the changes, I did this with
git add nextclue_input.cpp && git stash. Now the README.md file in branch mouse said :
```
git-game
Looks like you resolved your conflict and found our branch, congrats!!
Hmm…it seems this branch has a file that was seen before in another branch. Do you “remember” what it is? I think this file has something to do with the next clue, but it seems to be very ugly looking. Maybe if we compare the “diff”erences between this file and the file from before we’ll know where to go next…
Yeah! I do remember that the file *remember* was there in the branch *bug* as I wasted 10 minutes on it. I did ```git diff mouse bug -- remember``` to see the difference between these two files accross branches and the difference in the files was this one line :
-Sn The next clue is:IPGJVci +Sn In a branch named: Henry
So, the next *branch* to move was *Henry*, but ```git checkout Henry``` was a trap. On *checking-out* it said, *You are in 'detached HEAD' state*; means we were not in a *branch* but *tag*. The README.md file was saying the same.
Welcome to my Tag!!!
If you’re looking for my branch then you have gone the wrong way!!
How do you checkout to a branch that has the same name as a tag??? Deal with the tag first!!
The problem was that there was a *branch* with exactly same name as a tag, *Henry*. So I *renamed* the *tag*, because *who knows when you're gonna need something?* ```git tag Henry-v0.1 Henry && git tag -d Henry``` made a new tag pointing to old's commit and deleted the old one. Now after *checking-out* to the branch *Henry*, the README said :
Welcome!! It looks like you made it to my Branch!!! Generally you want to refrain from making tags the same name as branches, unless you have a good reason. The tag is more like the stable release. While the branch is more like the in progress feature, which will be added soon.
You’re almost done!! Excited?? Hope you are! You have one more thing to do!
Now its time to update the master branch, updating is really useful when you fork a repository and your forked repo starts to get behind on commits. The repository to update from is:
Don’t cheat!!
So, according to the task, to update the *master branch* I *checked-out* to it. With ```git remote add updater [email protected]:drami025/git-game.git``` command, I added the new *remote* to update from, as the README.md said. Then a simple ```git pull updater master``` did rest of the work and the *master branch* was equal with the new *remote*, all updated. \o/.
However, if you did, then great Job!! You completed our Git Game! ```
They have also implemented an Open-Badge for this, I got one.
Finally, it’s complete. And this Write-up too.
I’m feeling pain in my fingers now. | https://hackpravj.com/blog/the-git-game-writeup/ | CC-MAIN-2018-34 | refinedweb | 2,140 | 84.27 |
I recently bought a photon maker kit for a school project. I am new to the photon and programming in general. I have a project for school. I would like to adapt a thermocouple to the photon, publish the data to the cloud to record for iot and read the temperature in fahrenheit on the OLED screen that comes in the kit. I have done some small projects such as leds and hooked the OLED display up with the “hello world” code. I have also used code that turned it into a clock. Both display projects were in SPI I believe. I was wondering what I would need for coding and hardware. I saw that adafruit has a MAX31855 opamp circuit. Would this work with the photon for what I need?
Photon Thermocouple Project
@jhypes, Particle provides both the web IDE and a local Particle CLI for developing your code in C++. If you are familiar with Arduino, you will have no problems programming for the Photon. The IDE provides the editor and compiler and lets you program your device wirelessly (OTA). With the CLI you use your own editor but you can program wirelessly or directly via USB. I suggest you start with the web IDE.
The MAX31855 thermocouple interface is great for K-type thermocouples. There is also a new MAX31856 board with internal linearization for any thermocouple type. Both boards use 3-wire SPI and are super simple to use. There is already a MAX31855 library available for the photon on the IDE. I have used both boards and they work very well.
As for the OLED, you will need to tell us which model you intend to use. Some are SPI, others are I2C. There are a number of OLED display libraries on the IDE.
This project will be very simple and fun to put together. This community will be more than happy to assist you.
Thanks for your quick reply. The kit contents dont give a model # on the display. It just says: This is a 128x64 pixel graphic OLED screen that can be either controlled via the SPI (default) or I2C. I saw a few codes that are for the MAX31855 but wasnt sure which one I needed. One published to the cloud and the other looked like it was for a core and just went to a display. Im going to order my a 31855 or 31856 later today. Should be a fun project. I hope to learn alot.
@jhypes, I missed the “photon maker kit” part! Kind of funny that one of the suggested library is from my github repo! I’ll be publishing a new library for the display in the next few days. The existing ones are more than suitable as well. The libraries for both the MAX31855 and MAX31856 on the IDE are all good as well.
With the Photon, you will be able to display and publish your temperatures. You could use Blynk with your mobile device or send data to Ubidots. Your biggest problem will be having so many choices!
So I found the code below and was trying to get it to compile. It has the serial.prints turned off. But im getting the errors pictured below.
// This #include statement was automatically added by the Particle IDE. #include "Adafruit_MAX31855/Adafruit_MAX31855.h" #include "math.h" int thermoCLK = D2; int thermoCS = D3; int thermoDO = D4; Adafruit_MAX31855 thermocouple(thermoCLK, thermoCS, thermoDO); void setup() { while(!Serial); Serial.begin(9600); // wait for MAX chip to stabilize delay(500); } void loop() { // basic readout test, just print the current temp double temp = thermocouple.readCelsius(); double int_temp = thermocouple.readInternal(); //double c = thermocouple_0.readCelsius(); // Serial.print("Internal Temp = "); // Serial.println(thermocouple.readInternal()); //Serial.print("Internal Temp 0= "); //Serial.println(int_temp0); //Serial.print("Internal Temp 1= "); //Serial.println(int_temp1); Particle.publish("internaltemperature", String(int_temp), 1, PRIVATE); if (isnan(temp)) { //Serial.println("Something wrong with thermocouple 0!"); Particle.publish("thermocouple0", "Something wrong with thermocouple!", 1, PRIVATE); } else { //Serial.print("C 0= "); //Serial.println(temp0); Particle.publish("thermocouple0", String(temp), 1, PRIVATE); } //Serial.print("F = "); //Serial.println(thermocouple.readFarenheit()); delay(2000); }
Try this code that builds as is on my Web IDE
#include <Adafruit_MAX31855.h> #include "math.h" int thermoCLK = D2; int thermoCS = D3; int thermoDO = D4; Adafruit_MAX31855 thermocouple(thermoCLK, thermoCS, thermoDO); void setup() { Serial.begin(9600); delay(500); } void loop() { double temp = thermocouple.readCelsius(); double int_temp = thermocouple.readInternal(); Particle.publish("internaltemperature", String(int_temp), 1, PRIVATE); if (isnan(temp)) { Particle.publish("thermocouple0", "Something wrong with thermocouple!", 1, PRIVATE); } else { Particle.publish("thermocouple0", String(temp), 1, PRIVATE); } delay(2000); }
@jhypes, if you want to use one of the examples, it will automatically add the library. Otherwise, with your own app, you will need to add it to the project (after which you chose your application and confirm).
I found the max31855 library and included them in the project but it still gave the same errors.
What system version are you targeting?
There are two MAX31855 libraries. You need to import the one with the higher usage count (
Adafruit_MAX31855 and not
Adafruit-MAX31855) for the code I provided to build.
Could you also provide a screenshot of your Web IDE with the code drawer (
<>) open? | https://community.particle.io/t/photon-thermocouple-project/29031 | CC-MAIN-2019-22 | refinedweb | 865 | 69.18 |
Hi fellows, how are you? I'm stuck here with this. Perhaps you will suggest me to learn some more abstracted JS framework but by now I'm trying to learn the deeps of raw JS. I have 2 files, one is app/javascript/file_1.js and the other is app/javascript/namespace/file_2.js . Both of them do: window.onload = function() { // something } Both gets required by the application.js manifest, I've tested it putting an alert('Eyaa') on both files, alert gets executed twice, so working, good. Here comes the issue: just one window.onload get listened, the other not. The one listened is the first required(first file required). I wonder why does this happen? One file is for one view, and the other file is for another view, I want to have the code splitted, for order. Don't have a clue. Can you help me?
on 2014-06-22 02:35
on 2014-06-22 02:45
Okay, I've found why!!! But this arise another question. I've tested this: erased one of the files, in the other I've added a window.onload below the first window.onload and a strange thing happened: the last window.onload gets executed, but not the first. So this takes me to the conclusion: I can't "monkeypatch" window.onload, can be called just once, not only once in one *.js, even in the whole JS filesystem. Why works this way?
on 2014-06-22 05:20
Been doing some little more stuff. If I put the code of both *.js on the corresponding views(inside <script></script>) works like a charm. So why?
on 2014-06-22 18:27
On Sat, Jun 21, 2014 at 5:45 PM, Damián M. González <lists@ruby-forum.com> wrote: > Okay, I've found why!!! But this arise another question. > I've tested this: erased one of the files, in the other I've added a > window.onload below the first window.onload and a strange thing > happened: the last window.onload gets executed. > So this takes me to the conclusion: I can't "monkeypatch" > window.onload, can be called just once, not only once in one JS, even in > the whole JS filesystem. Why works this way? If you open a JS console and enter: > x what value does `x` have? Hint: it's not 'foobar' :-) Now try the same thing with `window.onload`. If you want to avoid using libraries like jQuery for now, look at native JS methods like e.g. window.addEventListener() HTH, -- Hassan Schroeder ------------------------ hassan.schroeder@gmail.com twitter: @hassan
on 2014-06-22 22:15
Yes, I've realized that onload is an attribute of window, so if I do window.onload = something twice I'm overwriting the value of the attribute. Thanks. | https://www.ruby-forum.com/topic/4997476 | CC-MAIN-2017-34 | refinedweb | 469 | 87.52 |
Should you choose Java or Python for your next project? Are you fortunate enough to have a choice? Are one of these languages a better option?
According to GitHub’s annual Octoverse report, Java and Python are the second and third most popular languages for the fourth year in a row. According to the same story, Python is one of the top ten fastest growing languages. Most of the other fast-gainers are new languages, while Python has been around longer than Java.
At the time of writing, the TIOBE index places Java at the top of their list and Python at number three. Python moved up a spot this month (December 2018), after sitting at number four for over a year.
Digital Ocean’s recent language survey places Python at number two on their list of languages for open source projects. Java is in fourth place, with only half the adoption of Python.
So, the two languages are popular and aren’t going anywhere. Which one is your best choice?
Raygun lets you detect and diagnose errors and performance issues in your codebase with ease
Java vs. Python in 2019.
Support for Python 2.x will end on January 1, 2020. For a long time, Python development has fragmented between version 2.7 and the regular releases of new 3.x versions. But, with the end-of-life date for Python 2 a year away, the question over which version to use is settled. The community has centered on Python 3.
Meanwhile, Oracle’s new release model for Java created a lot of fear, uncertainty, and doubt in the software community. Even though the announcement provided a free (as in beer) option and a clear upgrade path, confusion continues to reign. Several platforms providers, such as Red Hat and Amazon, have stepped in to support OpenJDK. But the once unified Java community is more fragmented than Python ever was. Let’s take a closer look at the similarities and differences between Java vs. Python.
Java vs. Python typing
Python and Java are both object-oriented languages, but Java uses static types, while Python is dynamic. This is the most significant difference and affects how you design, write, and troubleshoot programs in a fundamental way. Let’s look at two code examples.
First, in Python, we’ll create an array with some data in it, and print it to the console.
stuff = ["Hello, World!", "Hi there, Everyone!", 6] for i in stuff: print(i)
Next, let’s try it in Java.
public class Test { public static void main(String args[]) { String array[] = {"Hello, World", "Hi there, Everyone", "6"}; for (String i : array) { System.out.println(i); } } }
In Python, we put two strings and an integer in the same array, and then printed the contents. For Java, we declared a List of Strings and put three string values in it.
We can’t mix types in a Java array. The code won’t compile.
String array[] = {"Hello, World", "Hi there, Everyone", 6};
We could declare the array as containing Object instead of String, and override Java’s type system. But, that’s not how any experienced Java developer uses the language.
In Python, we don’t have to provide a type when we declare the array and can put whatever we want in it. It’s up to us to make sure we don’t try to misuse the contents.
For example, what if we modified the code above to do this?
stuff = ["Hello, World!", "Hi there, Everyone!", 6] for i in stuff: print(i + " Foobar!")
The above code will throw an error when we try to run it since we can’t append an integer with a string. What are advantages and disadvantages to dynamic typing and static typing?
Static typing catches type errors at compile time. So, if mixing strings and integers weren’t what you wanted to do, the Java compiler catches the mistake. How much of an advantage compile-time checks is up for debate in some circles. But, static typing does enforce a discipline that some developers appreciate.
Whether static typing prevents errors or not, it does make code run faster. A compiler working on statically-typed code can optimize better for the target platform. Also, you avoid runtime type errors, adding another performance boost.
Code that’s written with dynamic types tends to be less verbose than static languages. Variables aren’t declared with types, and the type can change. This saves a copy or type conversion to new variable declarations.
The question of code readability comes up often when debating Java vs. Python. Let’s take a look at that next.
Code readability and formatting
Let’s take an example from Java and Python and compare them. In this example, we need to open a large text file and collect each line into sets of 50 comma-separated records. Here is the Python code:
def get_symbols(file_name): with open(file_name, "r") as in_file: records = [] count = 0 symbol_set = "" for line in in_file: symbol_set = symbol_set + line[:-1] + ',' count = count + 1 if count % 50 == 0: records.append(symbol_set) symbol_set = "" symbols.append(symbol_set) return records
Here’s the % 50) == 0) { records.add(symbol_set.toString()); symbol_set.setLength(0); } } records.add(symbol_set.toString()); return records; } }
Whitespace
Whitespace is part of Python’s syntax, while Java ignores it. whitespace ends debates over how to format code. The only option you have left is how to use blank lines.
The Python snippet is a few lines shorter than the Java snippet, a difference that adds up in larger programs. Much of the difference is because there are no closing braces. But Python’s brevity—when compared to Java —goes deeper.
Brevity
Let’s look at how the two languages handle files.
Here’s Python again:
with open(file_name, "r") as in_file:
Here’s Java:
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
In both cases, the declaration creates a block. The file resource remains in scope, and the languages close it when the code exits the block.
In Python, we’re opening a file and reading from it. When the loop reaches the end of the file, the loop exits.
for line in in_file:
Java is more complicated. We’re opening a BufferedReader by passing it a FileReader. We consume lines from the reader. It’s our responsibility to check for null when the file ends.
while ((line = reader.readLine()) != null) {
This only demonstrates that it’s easier to handle text files in Python. But, it demonstrates how Java tends to be more verbose than Python. “Pythonic” constructs are more concise and less demanding. Java has evolved over the past few releases, with the introduction of try-with-resources in Java 7 and lambdas in Java 8, but it’s still a verbose language.
Let’s revisit our first example.
Here’s the Python again:
stuff = ["Hello, World!", "Hi there, Everyone!", 6] for i in stuff: print(i)
Here is the Java:
public class Test { public static void main(String args[]) { String array[] = {"Hello, World", "Hi there, Everyone", "6"}; for (String i : array) { System.out.println(i); } } }
Both of these snippets will build and run as is. Python will run a script from beginning to end of a file. Java requires at least one entry point, a static method named main. The JVM (Java virtual machine) runs this method in the class passed to it on the command line.
Putting together a Python program tends to be faster and easier than in Java. This is especially true of utility programs for manipulating files or retrieving data from web resources.
Performance
Both Java and Python compile to bytecode and run in virtual machines. This isolates code from differences between operating systems, making the languages cross-platform. But there’s a critical difference. Python usually compiles code at runtime, while Java compiles it in advance, and distributes the bytecode.
Most JVMs perform just-in-time compilation to all or part of programs to native code, which significantly improves performance. Mainstream Python doesn’t do this, but a few variants such as PyPy do.
The difference in performance between Java and Python is sometimes significant in some cases. A simple binary tree test runs ten times faster in Java than in Python.
Final thoughts on Java vs. Python
So, which language is your best choice?
Oracle’s new support model changes the Java landscape. While there is still a free option, the new release schedule and support model gives developers a reason to take stock. Java clients will need to pay Oracle for support, change OpenJDK versions on a regular basis, or rely on third parties like Red Hat or Amazon for fixes and security updates.
At the same time, Python has cleared a significant hurdle with Python 3. Python has a more unified support model than Java for the first time, and open source developers are focusing their efforts on the latest version of the language. I have to give Python the edge here.
Whether Python’s dynamic typing is better than Java’s static approach is subjective. The debate between the two models predates both of them, and it’s a question of what’s best for you and your team.
After working on large projects in both languages, I feel secure saying that Python’s syntax is more concise than Java’s. It’s easier to get up and running quickly with a new project in Python than it is in Java. Python wins again.
Performance is where Java has a substantial advantage over Python. Java’s just-in-time compilation gives it an advantage over Python’s interpreted performance. While neither language is suitable for latency-sensitive applications, Java is still a great deal faster than Python.
All things considered, Python’s advantages outweigh the disadvantages. If you’re not already considering it, give it another look.
In any project, whether you choose Python or Java make sure it’s error free with the Raygun Platform. Raygun automatically detects errors and performance problems with sophisticated Error Monitoring, Real User Monitoring, and Application Performance Monitoring. Learn more. | https://raygun.com/blog/java-vs-python/ | CC-MAIN-2019-13 | refinedweb | 1,685 | 66.74 |
Oops... should have said this... pyForge.promptForge.prompt() TypeError: unbound method prompt() must be called with promptForge instance as first argument (got nothing instead) ^ Thats why... I have to use : import pyForge pyForge.promptForge().prompt() On 11/11/06, Chris Hengge <pyro9219 at gmail.com> wrote: > > >So why did you use two sets of parenthesis here? > >Are you completely sure you understand everything that's happening here? > > pyForge.promptForge.prompt() > TypeError: unbound method prompt() must be called with promptForge > instance as first argument (got nothing instead) > > ^ Thats why... I have to use : > import pyForge > pyForge.promptForge().prompt > > ? > > Because I was trying to get a grip on classes and OOP... =P > pyForge for lack of a better description is kinda like my own > mini-framework. It's basically all the methods(functions?) that I've > basically rewritten in each of my python files that I grouped together into > classes by functionality. For example, pyForge has class fileforge which has > two methods, one for writing, and one for reading files. Each takes a few > different parameters but it makes an entire block of code transparent so > that when I'm trying to show someone my code at work its less to look at. > There is a class for a "console based splashscreen" called promptForge which > has a "EULA" mode enabled by bool and takes a few parameters. I've also got > zipForge which is very similar to my fileForge, but zips/unzips. I might add > a few more things that I've repeated... It was mainly an attempt at learning > classes, and I wanted all my re-usable code to be centralized so I didn't > keep opening scripts and cutting and pasting. > > > > On 11/10/06, Luke Paireepinart <rabidpoobear at gmail.com> wrote: > > > > Chris Hengge wrote: > > > As for saving memory.. I'm not particularily concerned since all my > > > systems have 2gb... > > > Also, before python I was writing C# database front ends (nothing > > > amazing) and I'm not even going to compare python's 10mb overhead to > > > .net's 45mb+. I was mostly just curious if it would save the memory in > > > the same manner. > > > > > > As for using modules... I'm actually looking at my real code right > > > now.. (need to not reply to these emails while at work when I can't > > > really see the code) > > > in my pyForge module (simple script to hold my common used objects > > > basically) there is a class promptForge, that contains a method prompt > > > <-- I know this is a great name =P.... > > > To call it: > > > import pyForge # module name > > > promptForge.prompt() # Class.method > > > will tell me promptForge is undefined. > > > so I use: > > > promptForge().prompt() > > > will tell me promptForge is undefined > > Yeah, it's unidentified because it only exists in the imported module's > > namespace. > > > so I use: > > > pyForge.promptForge().prompt() # module.class.method > > So why did you use two sets of parenthesis here? > > Are you completely sure you understand everything that's happening here? > > > > pyForge. -> now we're working in the module's namespace. > > promptForge -> the class you're targeting in the pyForge namespace > > () -> create an instance of the class using the __init__ method. > > .prompt -> get the method 'prompt' from the instance of the class you > > just created. > > () -> execute this method. > > > > So why are you creating an instance of promptForge here? > > > this works. (I just did all this while writing this email.) > > Yeah, it works, but is it necessary? > > > When I use: > > > import random > > > random.random () #This does its thing... most modules only have > > > module.whateverThisIs(params) > > > in my code I've got module.class().method(params)... Am I not > > > conforming to some sort of module standard? > > You're just creating an instance when you probably don't mean to. > > > Are modules supposed to only be filled with methods, > > No. > > Then they would be called functions :) > > methods are functions inside classes that act upon the class' data > > members (I.E. variables) > > They're different terms so that people will know what you're talking > > about. > > > using the module file itself as the seperation layer in place of using > > > a class? > > Yeah, do that if you want just functions. > >? > > You can have a module of functions if you want. > > You can have a module of variables if you want. > > a module is just the same as having all the stuff declared in your > > program, except you refer to it all by module name. > > > > #----- config.py > > a = 1 > > #----- > > #---- test.py > > import config > > print config.a > > #------ > > etc. > > > > > > FYI... I dont know where it happened, but these last few e-mails are > > > off tutor. > > Oops, yeah. This one is forwarded to tutor and if anyone wants to see > > the previous discussion you can check the reply-stuff below. > > > > HTH, > > -Luke > > > > > > On 11/10/06, *Luke Paireepinart* <rabidpoobear at gmail.com > > > <mailto: rabidpoobear at gmail.com>> wrote: > > > > > > Chris Hengge wrote: > > > > Alright, that all makes sense other then one part... > > > > > > > Okay! I'm shivering with anticipation :) > > > > I'm all for you saying to just use: > > > > import module > > > > module.class.method () > > > > I agree this code is easier on the eyes down the road... > > > > > > > > but...( And this might be old world C++ coming in and shading my > > > > > view) > > > > In c++ you would be specific aka from module import class so > > > that you > > > > could conserve memory by not importing the entire library. Is > > this > > > > also true for python? > > > Ah, well, now we step into sacred territory. > > > >_>. > > > The long and short of it is, yes, importing the whole module uses > > > more > > > memory. > > > It shouldn't use significantly more memory. > > > If you're so constrained for memory that you're considering not > > using > > > 'import class' just for this reason, > > > then you'll be fretting about the 10 mb of overhead (or whatever) > > the > > > Python interpreter takes up, I think :) > > > > > > In general, in Python, consider "If it makes it easier on me and > > the > > > speed impact is not noticeable, why would I make it hard on > > myself?" > > > premature optimization is the root of all evil. > > > In this case, I wouldn't even consider the memory usage in > > deciding > > > which syntax you like better. > > > > > > > > Final question on the topic that hopefully has a clear answer =P > > > > > Oh, let's hope. *crosses fingers* > > > > When writing a module, is there some special way to do it? Like, > > do > > > > they use only classes with no methods inside? Or do they only > > use > > > > methods? > > > > I ask because my pyForge is Class > Methods and to use it I have > > > to say: > > > > import module > > > > module().class().method(stuff) > > > Are you sure? :D > > > You should never have to do this. > > > if you import module, > > > then everything inside of module is accessed the same way it would > > > be if > > > it were in your program, > > > just with a 'module.' prepended to it. > > > Imagine it like this. > > > > > > #----- > > > #test.py > > > def aFunction(): > > > print "hello" > > > aFunction() > > > #----- > > > obviously outputs hello. > > > > > > Now consider these two files. > > > > > > #----- > > > # module.py > > > def aFunction(): > > > print "hello" > > > > > #------ > > > how would you use this in your test.py script? > > > > > > #----- > > > #test-version2.py > > > import module > > > module.aFunction() > > > print module.aVariable > > > #------- > > > You'll see > > > "hello > > > hi" > > > as the output for this script. > > > > > > The 'import module' syntax you can imagine as it creating a new > > > variable > > > that points to the _entire_ script 'module.py' and everything > > > inside of it. > > > > > > So I don't think you'd ever have to do > > > 'module().class().function()' > > > in fact, I know you would never need to do that. > > > A simple test: > > > > > > import random > > > random() > > > > > > raises a TypeError: 'module' object is not callable. > > > > > > Do not think of a module as a class, cause it's not. > > > it's just a separate namespace. > > > So the 'from module import *' just says to get rid of that extra > > > level > > > of namespaces > > > that isolates those module functions from overwriting or > > interfering > > > with my own functions, > > > and just put them all as global, and trust me not to accidentally > > > overwrite them later. > > > > > > > > > > > but when I go to use most of the "standard libraries" I can just > > > > > write > > > > something like > > > > import module > > > > module.method/class?(stuff) > > > Yeah. you should always have to have a module., never a > > > module()., as I > > > hope the above explanation clarifies. > > > > > > > > Thanks again for your patience and clear answers Luke! > > > Sure! It helps me to think about things like this too :) > > > > > > Also, one final thing: > > > You can have a class that you don't instantiate but still create > > > instances of inner classes. > > > > > > for example, > > > >>> > > > class foo(object): > > > class bar(object): > > > def __init__(self): > > > print "Initializing bar!" > > > > > > >>> foo.bar () > > > Initializing bar! > > > <__main__.bar object at 0x00B536D0> > > > >>> foo > > > <class '__main__.foo'> > > > >>> foo() > > > <__main__.foo object at 0x00B53830> > > > >>> foo().bar() > > > Initializing bar! > > > <__main__.bar object at 0x00B53890> > > > > > > You see, there's really no reason to initialize this class > > ('foo'), > > > because 'foo' is just holding the 'bar' class for us. > > > yeah, you can initialize 'foo' if you want, but it does exactly > > > the same > > > thing uninitialized, because it has no instance methods or > > variables, > > > or, in other words, nothing with 'self' in it. > > > I just thought of this because of your > > > " > > > I ask because my pyForge is Class > Methods and to use it I have > > > to say: > > > import module > > > module().class().method(stuff) > > > " > > > comment. > > > Let's assume you meant > > > module.class().method(stuff) > > > since module() raises an exception :) > > > so if you were doing this, it would mean on each call, > > > you're creating an instance of the class called 'class' and > > calling a > > > method on that instance, > > > but you're not storing the instance anywhere, so it's just > > > disappearing. > > > remember when we were talking about that before? > > > It's possible that you need to instantiate it but not keep a copy > > > around, but it's probable that this isn't what you wanted to do, > > > and you just put the () cause you thought they needed to go there. > > > > > > > > > HTH, > > > -Luke > > > > > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: | https://mail.python.org/pipermail/tutor/2006-November/050843.html | CC-MAIN-2014-15 | refinedweb | 1,626 | 75.1 |
()
These are the rules I've developed over the years that I follow when refactoring code. They're rules in the sense that I always regret it if I fail to follow them for any reason.
For my current X10 home automation project, I want the ability to schedule events to occur at sun-relative times like 'sunrise' and 'sunset'. Now, you can do that by using an X10 light sensor and watching for the 'on' and 'off' commands it will send. But will the sensor be triggered by stray light, like from a passing car's headlights? I don't know. Perhaps with careful placement of the sensor, you could avoid accidental triggering. But there's another way to handle the problem.
Given your position on the world by latitude and longitude and today's date, sunrise and sunset can be calculated accurately using spherical geometry. It's what astromomers do. You can google around for existing software and source code that does these calculations. I wanted a Python solution, and so I settled for Sun.py by Henrik Härkönen. This is code for a Python class that calculates sunrise and sunset, as well as three flavors of 'twilight'. The code is a direct translation of someone else's C code, even to the point of preserving the original C comments, but hey, it works well. It calculates all times in UTC, so you'll need to apply the correct offset for your timezone.
With this code, I can now translate an X10 event scheduled for sunrise today into the actual sunrise time for today. That's one more item on my wish-list for X10 home automation I can check off.
I.
Last.
I've written several times about the Python csv module and its limited API. I presented an adaptor class for use when you want to parse a CSV string, without being locked into reading sequentially from a file. Here's another way of doing it, using Python's standard 'I have a string, but I need a file-like object' adapter, the StringIO module.
import StringIO # Or use cStringIO, it's fasterimport csv
# First, create the StringIO object, then the csv reader object# using the StringIO object.sf = StringIO.StringIO()csvReader = csv.reader(sf)
# Now, write a CSV string out to the StringIO object.csvData = '1,2,three,"four,five",6'sf.write(csvData)
# We have to seek the StringIO pseudo-file back to its start.sf.seek(0,0)
# Now read in the same data via the csv reader object.parsedData = csvReader.next()
When we look at what parsedData contains, we see a list like so:
[ '1', '2', 'three', 'four,five', '6' ]
Using StringIO rather than the adaptor class I presented earlier is a somewhat more heavy-weight way of solving the problem, but might fit your use better.
I recently saw an ad from x10.com for a free (you pay shipping) X10 starter kit, including a 'Firecracker' computer interface. That was a deal I couldn't pass up, so I ordered it through their web site, and 3 days later, the kit arrived.
The kit consists of the CM-17a 'Firecracker' serial computer interface, which transmits via radio, a transceiver module which receives the radio commands from the Firecracker and retransmits them via the X10 protocol over your house wiring, a lamp modules for controlling... lamps, and a PalmPilot-sized hand-held remote control that lets you manually do what the computer interface does. Oh, and the transceiver module also double as an appliance module, allowing you to control appliances of up to 500 watts.
With the hand-held controller, you can control any X10 modules you have, either the ones that come with the kit, or any add-on modules you may want to buy. You could go wild, like many do, and completely automate your home -- lights, appliances, garage door, pool heater, ferret feeder, whatever.
But with the computer interface, things get much more interesting. You can, for example, download from x10.com a free application that duplicates the appearance and functionality of the hand-held controller on your computer screen. Or, you can download, for $20, an application that fully utilizes your computer and the x10 interface to do full automation. Want your hot-tub to turn on at a certain time every day? No problem. Want your lights to simulate an occupied house while you are on vacation? Easy.
Naturally, hand an X10 computer interface to a Python programmer, and he'll immediately start writing code for it. Or that was my intent, anyway. The first thing I did was google around for any existing Python projects for X10. I found two, Pyxal and Pyx10. Both projects seem to be unmaintaned. Pyxal is pure Python, and does not support the recent X10 controllers, like the Firecracker. Pyx10 uses a wrapper to turn the XAL library into a Python extention module. It supports recent X10 controllers, including the Firecracker.
I downloaded and examined both. Pyxal was right out, as it has no Firecracker support (why not add it yourself, you ask? I'll get to that in a moment...). Pyx10 and XAL looked good. After compiling and installing XAL (a snap), I tried compiling Pyx10. Nope. The wrapper code for XAL would not compile. From a quick exam, it looked like it was out-of-sync with XAL.
I could have continued hacking at it to get it to work, but further googling (the trademark police are gonna get me), I found Project WiSH, a project for turning X10 device drivers into... well, Linux device drivers. Super! Instead of having to do low-level device handling from my code, I can simply open a linux device driver and write commands to it, just like I was writing text to a file. And WiSH was a snap to compile and install. Just make sure you have your kernel source loaded on your machine. (For the CM-17a 'Firecracker', be sure to download the 1.6.10 version of WiSH. The later 2.0.1 version does not yet support it. But both versions support the CM-11a, which is the other modern popular X10 computer interface controller.)
Now, I do my work under Linux, so this is just what the code doctor ordered. Actually, it's even better than it sounds. You see, there's this little bit of info about that Firecracker X10 controller...
If you look at one of the other X10 computer interfaces, say the CM-11a that comes with another of the home automation intro packages that x10.com sells, you will see that it is controlled via the computer in a manner rather like an external serial modem. Connect it to your serial port, and send it strings of ASCII characters. Not so with the CM-17a 'Firecracker'. This little guy is a serial pass-thru 'dongle', very small. From what I can tell from my Google research, you must directly control the radio transmitter in it via bit-tiddling the RTS and DTR lines of the serial port. You must assemble a 5-byte command via bit masking, then bit-shift it out to the CM-17a by directly controlling the states of the RTS and DTR lines, doing the timing yourself. There are no smarts. Ouch. No wonder this is the bargain-basement controller.
The CM-11a controller has another advantage, too. It's smart, it has its own processor. So you don't even need to leave your computer on to do real-time home automation. Use the scheduling software to send it commands, like 'turn on my security light at local-time dusk, and turn it off at dawn', and the CM-11a will do it, all by itself.
But I don't have the CM-11a. I have a CM-17a and a Linux box. Add in the device drivers from Project WiSH, and from a Linux command line, I can execute 'echo "on" >>/dev/x10/a1', and send the 'on' command to the X10 device at house code 'A', unit code '1'. How cool is that?
OK, how can we combine equal portions of X10, Project WiSH, Linux, Python, and fun? (OK, fun gets a bigger portion.)
Here's the deal. I work for a major software house. We do automated nightly compiles of our code on all of the platforms we support (Linux, various flavors of UNIX, Windoze). The last thing you want is for some code change you made that day to 'break the build'. The automated process sends out email giving that night's build status. If you broke the build, it's supposed to be your first priority to fix it.
I keep forgetting to check my email. I have many projects, they grab my attention, and it may be hours before I check my mail. Yes, I have a little task bar thingie that tells me if I get new mail. I don't look at it if I'm concentrating on a problem.
Python and X10 to the rescue! (This is a fun solution looking for a problem.) I now have a Python script that is run via cron every 10 minutes. It uses the poplib and email modules to grab and parse my email, looking for the specific patterns that a 'you broke the build' message will contain. If it finds such a message, it opens and writes an 'on' command to the proper X10 device driver, which then turns on the BIG RED ROTATING LIGHT. I kid you not.
This is so much fun!
When.
Yesterday I wrote about working with fixed record length files, and presented a class for making it easy. Today I'll extend that idea to handle records containing csv data.
The new CSVRecordFile class inherits from the RecordFile class, overriding the read and write methods to add csv parsing and formatting. This allows you to read and write fixed length csv data records in random order. The StringCSVAdaptor class (presented earlier) is used to enable us to use Python2.3's csv module with strings. This is necessary since the csv modules reader and writer functions expect to work with interables, such as a file-like object or a sequence.
Matt Goodall took me up on the need for the StringCSVAdaptor class, rightly pointing out a simpler way of handling the problem (thanks, Matt! I think you are reader #4 of this weblog, and the first person to leave me a comment!) Sadly, Matt's suggestion does not fit with the problem domain I'm using CSVRecordFile for. For one thing, I need both a csv reader and writer. I only want to create these objects once per CSVRecordFile instance, and then use them to parse/format many records in random (not sequential) order. Matt's solution, while useful for simple one-shot csv needs, looks to me to require the creation of the reader and writer for each record that is to be parsed (because he wraps the string to be parsed in a list to make it an iterable). You can read Matt's comments from yesterday's post.
Put this code in a file called csvrecfile.py:
"""This file contains the CSVRecordFile class, for working with fixed lengthrecord files, where the records contain csv data."""
__author__ = "Mike Kent"__version__ = "$Id$".split()[-2:][0]
import recfileimport csvimport csvadaptor
class CSVRecordFileFmtError(Exception): pass
class CSVRecordFile(recfile.RecordFile): """This class provides a standard way to handle files which are layed out as fixed-length records containing csv data, where each record is padded to its proper length with a padding character, and may be optionally terminated with a record terminator string.""" def __init__(self, filename, mode, reclen, recpad='', recterm=None, **csvKwParams): recfile.RecordFile.__init__(self, filename, mode, reclen, recpad, recterm) self.csvAdaptor = csvadaptor.StringCSVAdaptor() self.csvReader = csv.reader(self.csvAdaptor, **csvKwParams) self.csvWriter = csv.writer(self.csvAdaptor, **csvKwParams) return
def read(self, recNum): """Read a record containing csv data by record number, and return a list of strings. Record numbers start a 1. An empty list will returned on end of file.""" self.csvAdaptor.data = recfile.RecordFile.read(self, recNum) try: rec = self.csvReader.next() except csv.Error: raise CSVRecordFileFmtError
return rec
def write(self, recNum, valueList): """Write a list of mixed-type values to a record, in csv format, by record number. Record numbers start with 1. The record will be padded to the correct length using the padding character, and optionally terminated by the record terminator string. You can seek to, and write, records beyond EOF. However, to append a new record to the current actual EOF, give a record number of 0. This function returns the actual record number written to.""" try: self.csvWriter.writerow(valueList) except csv.Error: raise CSVRecordFileFmtError
return recfile.RecordFile.write(self, recNum, self.csvAdaptor.data)
Here are the unit tests. Put this code in a file called test_csvrecfile.py:
import sysimport unittestimport csvimport csvrecfile
class TestCases_01_RecordFile(unittest.TestCase): def test_01_instantiate(self): recFileObj = csvrecfile.CSVRecordFile("test.txt", "w+b", 20, ' ', 'r\n', lineterminator='', quoting=csv.QUOTE_NONNUMERIC) self.assert_(recFileObj is not None) return
class TestCases_02_RecordFileWriteAdd(unittest.TestCase): def test_01_writeAddOne(self): recFileObj = csvrecfile.CSVRecordFile("test.txt", "w+b", 20, ' ', 'r\n', lineterminator='', quoting=csv.QUOTE_NONNUMERIC) self.assert_(recFileObj is not None) rec = [ 1, 2, "three" ] recFileObj.write(0, rec) recFileObj.flush() testFileObj = file("test.txt", "rb") expected = '1,2,"three" r\n' newRec = testFileObj.read(20) self.assertEqual(newRec, expected) return def test_02_writeAddSeveral(0, rec) recFileObj.flush() testFileObj = file("test.txt", "rb")
for count in range(5): expected = '1,2,"Record %d" r\n' % (count + 1) newRec = testFileObj.read(20) self.assertEqual(newRec, expected) return
class TestCases_03_RecordFileWriteRandom(unittest.TestCase): def setUp(count + 1, rec)
recFileObj.close() return
def test_01_writeRandomOne(self): recFileObj = csvrecfile.CSVRecordFile("test.txt", "r+b", 20, ' ', 'r\n', lineterminator='', quoting=csv.QUOTE_NONNUMERIC) self.assert_(recFileObj is not None)
recNum = 2 rec = [ 3, 4, "New record %d" % recNum ] recFileObj.write(recNum, rec) recFileObj.flush() testFileObj = file("test.txt", "rb")
expected = '3,4,"New record %d"r\n' % recNum testFileObj.seek(20) newRec = testFileObj.read(20) self.assertEqual(newRec, expected) return
def test_02_writeRandomSeveral(self): recFileObj = csvrecfile.CSVRecordFile("test.txt", "r+b", 20, ' ', 'r\n', lineterminator='', quoting=csv.QUOTE_NONNUMERIC) self.assert_(recFileObj is not None)
recNumList = [ 1, 5, 3, 2, 4 ] for recNum in recNumList: rec = [ 1, 2, "New record %d" % recNum ] recFileObj.write(recNum, rec) recFileObj.flush() testFileObj = file("test.txt", "rb")
for count in range(5): expected = '1,2,"New record %d"r\n' % recNumList[count] testFileObj.seek((recNumList[count] - 1) * 20) newRec = testFileObj.read(20) self.assertEqual(newRec, expected) return
class TestCases_04_RecordFileReadRandom(unittest.TestCase): def setUp(self): recFileObj = csvrecfile.CSVRecordFile("test.txt", "w+b", 20, ' ', 'r\n', lineterminator='', quoting=csv.QUOTE_NONNUMERIC) self.assert_(recFileObj is not None)
def test_01_readRandomOne(self): recFileObj = csvrecfile.CSVRecordFile("test.txt", "r+b", 20, ' ', 'r\n', lineterminator='', quoting=csv.QUOTE_NONNUMERIC)
rec = recFileObj.read(3) expected = [ "1", "2", "Record 3" ] self.assertEqual(rec, expected) return
def test_02_readRandomSeveral(self): recFileObj = csvrecfile.CSVRecordFile("test.txt", "r+b", 20, ' ', 'r\n', lineterminator='', quoting=csv.QUOTE_NONNUMERIC)
recNumList = [ 1, 5, 3, 1, 2, 2, 4 ] for recNum in recNumList: rec = recFileObj.read(recNum) expected = [ "1", "2", "Record %d" % recNum ] self.assertEqual(rec, expected) return
if __name__ == "__main__": unittest.main() sys.exit(0)
Previous/Next | http://radio.weblogs.com/0124960/ | crawl-002 | refinedweb | 2,554 | 67.35 |
Patterns in Java & JavaFX Script
By octav on Dec 18, 2007
One of the thoughts that I had the other day was related to design patterns in JavaFX Script. Patterns are quite popular with developers. The are books on this topic and lots of web resources. The question is how could write, for instance a Singleton, in JavaFX Script.
In Java it would look like this:
public class OnlyOne {
private static OnlyOne singleton = null;
private OnlyOne() {
}
public static synchronized OnlyOne getInstance() {
if (singleton == null) {
singleton = new OnlyOne();
}
return singleton;
}
}
The result of running the Driver program is:The result of running the Driver program is:
/\*\*
\* Test program to prove we've coded the singleton correctly
\*/
public class Driver {
public static void main(String[] args) {
// one would try this OnlyOne one = new OnlyOne();
// and it won't work due to the private constructor
// get an instance
OnlyOne one = OnlyOne.getInstance();
System.out.println("Myfirst attempt: " + one.toString());
// get another instance to see if they are the same
OnlyOne two = OnlyOne.getInstance();
System.out.println("My second attempt: " + two.toString());
}
}
Myfirst attempt: onlyone.OnlyOne@9b49e6
My second attempt: onlyone.OnlyOne@9b49e6
As expected, any time one is trying to get a handle to the OnlyOne object, the same instance is returned.
Wow!
This one is an eye opener!
Thank you Octavian - now I will be using this amazing pattern (thanks for your insight) everywhere and also will tell about this great technique to my friends and co-workers!
Posted by Anon on December 19, 2007 at 02:27 AM PST # | https://blogs.oracle.com/octav/entry/patterns_in_java_javafx_script | CC-MAIN-2015-18 | refinedweb | 258 | 54.22 |
This action might not be possible to undo. Are you sure you want to continue?
org Publication
Game Maker 7 is OUT!
What you need to know ((ppgg.. 66))
MarkUp
April, 2007
Plus…
IIntegrate wiith Viista’’s game expllorer ntegrate w th V sta s game exp orer
((pg.. 17)) pg 17
Pllay games off years gone by P ay games o years gone by
((pg.. 2)) pg 2
Markup is an open publication made possible by the contributions of people like you; please visit markup.gmking.org for information on how to contribute. Thank you for your support!
©2007 Markup, a GMking.org project, and its contributors.. Additionally, permission to use figures, tables and brief excerpts from this work in scientific and educational works is hereby granted, provided the source is acknowledged. As well, any use of the material in this work that is determined to be "fair use" under Section 107 or that satisfies the conditions specified in Section 108 of the U.S. Copyright Law (17 USC, as revised by P.L. 94-553) does not require the author’s permission. The names, trademarks, service marks, and logos appearing in this magazine are property of their respective owners, and are not to be used in any advertising or publicity, or otherwise to indicate sponsorship of or affiliation with any product or service. While the information contained in thi s magazine has been compiled from sources believed to be reliable, GMking.org makes no guarantee as to, and assumes no responsibility for, the correctness, sufficiency, or completeness of such information or recommendations.
Editor’s Desk
Editorial
Games of Years Gone By
Remember the days of DOS? You’d get a new game (on a floppy) from a friend and Ooo and Ahh over the simple physics that could keep you occupied for hours? Fast forward around 15 years and we have games that require two CDs or a DVD to install (over a thousand floppies) and we still Ooo and Ahh, and enjoy them just as much as we did when we first put in a copy of SimCity for DOS, or Sharky’s 3D Pool. If you’re like me you have boxes full of old games and apps on floppies for DOS, along with some of those “800+ Games” CDs that came out for Windows, slowly fading away. Why? A lot of those games can still be run, using emulation software like DOSBox (dosbox.sf.net; pictured below) for your DOS and Win 3.1 (you remember 3.1 right?) games. If you still have a legal copy of Windows 3.1 (or in my case, 3.11 for workgroups) you can get a copy of the free VMWare Server (vmware.com) and install the actual Win 3.1 in an emulator. Cool, eh? And for those of you with some old game system cartridges around, you can download copies of the games you own (it’s only legal if you already owned the original cartridge) that will run in emulators like mame (mame.net) at theoldcomputer.com. perfectly on WinXP, xrl.us/ddave) and In Search of Dr. Riptide (also available as Shareware xrl.us/driptide). Which brings up another good point, there are lots of great shareware games for DOS still floating around. Back then, the demos went just a movie of screenshots; they were hours-to-days of fun games. You’ll find a lot of them available on DOS archive sites such as dosgamesonline.com. Switching from the past of gaming, to the future; open source games are becoming more popular, more advances and much better. Here are just some of the great games I’ve run into recently (all of these run in Windows, most will also run on Linux & Macs): Scorched3D . sf.net/projects/scorched3d Bacteria ...... bacteria.simondonkers.com Planet Penguin Racer ....... xrl.us/PPRacer Enigma........... Frozen Bubble ............ frozen-bubble.org See you next month! Robin Monks, mozillaman.uni.cc
Balloon Challenge
Digging up some of those games can bring back some of the fun gaming possibilities of some of the great games of yesteryear. Some of my personal favorites I’ve resurrected are Sharky’s 3D pool shark (which I picked up a copy of a few years back in a dollar bin at the local geek shop), Balloon Challenge (got that in a 500 game pack, it’s a shareware game, so you can still pick it up at xrl.us/bchallenge), Dangerous Dave (this freeware DOS game still runs
In This Issue…
Editorials .............................................. Robs Games of Year’s Gone By ................ 2 Tuntis’ Rant .................................... 5 Reviews ............................................... Bridging the Gap! ............................ 3 Game Maker 7.0 ............................. 6 Tutorials............................................... Game Maker................................. 12 Drawing: Surfaces ......................... 13 Intergration with Vista’s Game Explorer ........................................ 17 C++ “Hello World” ........................ 20
P age |2
Reviews
Game Reviews
Bridging the Gap!
I haven’t been active on the Game Maker Community for a while, I don’t check topics and creations as much, and I’m probably not as up-to-date as I used to be. But I do check my PM daily, and that’s when I knew a creation of mine was in the cage match against this wonderful game: Bridging the Gap! The game was created by Erik Leppen and so far: I’m loving it! There are some very good points about this game that I will surely discuss, and other bad points which I’m also going to talk about.
Concept and Originality
If I just look at the game and isolate it, I have to say it has an excellent concept – and it is fun! But people like me who used to spend a lot of time in Download.com trying to find a nice game to play would find this game very familiar. When you look at the screenshot of the actual game, and compare with the screenshot of "bridge builder game" on the next page, you will notice the resemblance -- its striking! Now I would’ve liked to see a “completely” original game that I could review, but that doesn’t make the game – overall – any worse, except for the fact that coming up with the idea itself wasn’t the author’s task. For information about “Bridge Building Game”, see bridgebuilder-game.com, or for the version of the game I originally used to play, see download.com/30032111_4-5862232.html. For all of the reasons above, I have no April, 2007
choice but to give this game a 6/10 in the concept area. Yes, I know – this isn’t particularly good, but keep in mind, it is a great implementation of the game as you will see soon.
Music and Sounds
So I kept saying how good the game was, but I started out with a bad point about the game, and I decided to keep it that way: so here’s the next bad thing in the game: Music! We need music, we need sound effects, and we need something to listen to while we’re playing the game! I don’t care how fun anyone thinks the game is, because it won’t be as fun as it would’ve been with good music. So, all I can do is give the game a 3 out of 10 in the music section.
do we see in this game: well, there’s the bridge, there’s the ground, there’s the actual train, and some graphic effects (which we will cover later). If you ask a graphic designer what s/he’d think of them, you probably won’t hear much praising – but from a game play and design perspective: excellent. The graphics are what I like to call “effort effective”, which means that whoever made the graphics put in the amount of effort that would make the game good (in terms of game play), yet “worth the effort”. Now sure, more effort – and therefore better graphics – would’ve made the game even better, but it simply gets to the point where it’s simply better to keep them the way they are.
Graphics
The question is: what kind of graphics 3|P a ge
Reviews
Game Reviews
Bridging the Gap! Cont.
I give the graphics 8/10, they well suit the game, but of course – there’s always space for improvement.
Graphics Effects
So there are two types of graphics effects that I have noticed: destruction, and smoke – but I’m sure I might find more if I play it a bit longer. Graphics Effects are always a plus to have, but not an essential element in game play. When looking at the smoke alone, I like it – the way it is realistic and smooth, and when looking at the destruction effects, I also like it: it fits the rest of the game’s graphics and provide this certain “feel” to the game that enriches the experience of the player.
But again, the thing is, these effects are almost exact opposites of each other – either make them all realistic and smooth, or all cartoonish and ‘weird’. Both are good, just not together, and for that, the game gets another 8.5/10.
Game Play (Controls)
The controls are good, easy to use and understand, and most importantly: simple in every way! I’ve only played it a couple of times and learnt a few control tricks, such as clicking on a single point and connect all possible bars to it, etc. The controls themselves are excellent, different controls are accessible from the top bar as well as a quick right-click for those who can’t wait, or are simply pros in the game and like to do everything quickly. I have no other choice but to give the game a full 10/10 in Game controls.
Game Play/Player Experience
This game is fun, fun, fun! Most people would love, whether or not they are interested in physics, building, bridges, cars, trains, computers, whatever – it’s a must-try!
P age |4
The original game (originally called "Bridge Builder", now "Bridge Building Game")
Reviews
ACTION GAMES
Bridging the Gap! Cont.
There is one disadvantage in the game: when testing the bridge by allowing a train to cross it, the train moved too slowly, and I couldn’t find a way to speed the train up, or even skip the whole part – I really think such feature should be available. The game gets 9.5/10 for player experience. atmosphere of the game, etc. Here however, versatility counts in the variety of levels the game has – and here’s what I’ve heard: it has 50 levels! Now that should keep you free for a while, eh? I must give Erik’s game a 10 in versatility, because the effort itself was amazing – and in each new level: a new, different challenge! Well, according to what I’ve seen: it should. The game is based on a realistic and awesome (in my point of view) physics engine. It’s all done quite well, stress is analyzed, and according to that the bridge breaks or holds. Of course, don’t take my word as an answer; in real life, there are many variables and such things are much more difficult and complex to calculate, so I’ll just say that the game physics is “sufficient”. And by saying sufficient, I mean 9/10.
Versatility
“Versatility”, in each game, is measured in different ways. Sometimes it’s in the level design, in other cases it is in the
Realism
So how realistic is this game? Will such bridges hold that weight in real life? TUNTIS’ RANT Much isn't needed to describe my problem with them: they are just a "bit" too hard to use. Allocating colors to use, etc can be difficult. Otherwise, PHP has been quite a nice "adventure", with the exception of the lack of... Proper Online Documentation The PHP manual is a great resource, but its examples are usually too incomplete and/or undocumented. There are not enough tutorial sites and looking at some other application's source code doesn't really help. tuntis -
Programming and Bugs
PHP
Hi, my name is "tuntis", and I've been a regular user of the GMKing.org services. About 4 months ago from the moment of writing, I decided to pick up learning PHP as a programming language. I, currently, have created a lot with it, and know all the basics, and even run an online game, which I decided to pick up after it's original creator went on to another project of his own. I've extended it a bit, and continue to run it to the current day. However, there have been some things I haven't liked about PHP, namely the following: Error Reporting Error reporting could use much more beginner-friendly reports (although one does get used to the most common ones), but can really confuse new programmers sometimes. Image Functions April, 2007
Well, the programming is definitely amazing, I must say. I have personally found no bugs and I’ve enjoyed playing it, but I’ve checked the topic and found a single bug. I tried to track it and see whether or not was it resolved, but I didn’t find out much. So for programming, the game gets 9/10 – because it is one good “replication” (or even enhancement) for the original Bridge Building Game.
Overall
When adding up all the scores, I found that the game's total score is 7/10. I personally hoped the game would get a higher score, but there's nothing much that could be done. Again I must say the game is incredibly fun, and a must-try. Such a game tells us one thing about game development: a game is never limited by its tool or language; it is only limited by the skill, effort, and creativity of its author, and what a creative author he is. Bravo. Eyas Sharaiha 5|P a ge
Reviews
GAME DEVELOPER IDES
Game Maker 7.0
Introduction
Those interested about Game Maker have gone crazy in late July, when Mark announced that the next version of Game Maker will not be 6.2, as previously announced, but instead 7.0. Well, with such a change in the version numbering, you would have expected much more features and something “completely new”, some people say that is exactly what Game Maker 7.0 is, while others remain unsatisfied by the lack of sufficient new features to give the 7.0 number to this version of Game Maker. However, whether people are satisfied by the version numbering of Game Maker or not doesn’t change the software within. I think it is silly that some people wouldn’t like Game Maker 7.0 just because of its version number – it could be version 11 or 2.3 and still be as good! So, whether this version of Game Maker lived up to its number or came as a disappointment, the review won’t change – the only question that truly matter is: is Game Maker 7.0 a good addition over Game Maker 6.1, and is it worth to upgrade? This review will go through all of the new features of Game Maker 7.0 in incredible detail, and cover every change that has occurred in it, so that I could come up with a result to answer the question asked above. at the general Game Maker interface is a new item the left pane called “Extension Packages”, and two new toolbar items on the top: “Create a stand-alone executable for your game” and “Publish your finished game on the website”. This section will not go through any of these features in detail, but will instead be concerned about their integration with the Interface. So, the Game Maker interface is the same. Not much is changed; we’re still used to it, just some extra icons and a nice little YoYo Games image on the bottom of the left resource pane. However, a point worth noting is that that small link could be removed from the interface from the options menu. The changes to the interface are incredibly minor, and are done in such a way that wouldn’t affect those who are used to previous versions of Game Maker. Buttons are added to the same interface, the same way other buttons were added before. In terms of consistency, it is incredibly consistent – and that is the number one most important thing in the UI of any software. but at the end of the day, you’ll probably end up having to rework some of the transitions you have in your game, if it had lots of them.
Major Features
Those who are disappointed by the version number are probably upset about this section! Yes, it is true; Game Maker 7.0 has only a few “major” features and additions. But, this hopefully shouldn’t stop it from being a good, solid addition to the Game Maker line.
The Extension Mechanism
The Extension Mechanism has an excellent concept and implementation! The general of concept of the extension mechanism is that any user could be capable of creating “Extension packages”, and integrate them at a deeper level that before. Extension packages could be one of three: script (GML), DLL, and a Library. Now, what differentiates extension packages between regular scripts, DLLs, or Libraries is that Extension packages are integrated differently; they become actual scripts which the user might use, and it would seem like they are part of Game Maker itself. They have their own help, accessible via Game Maker, they are mentioned in the function list, like all other Game Maker functions are, they could have their own constants, etc. They are basically an actual addition to Game Maker itself, except it isn’t written by Mark, and it’s either a GML script, a DLL, or an Action Library. What confuses me is the action library
Incompatibilities
Game Maker 7.0 has one incredibly positive point: it has too few incompatibilities. So what? The file extension has changes, big deal. However, the real problem is that room transitions are incompatible with previous versions. Mark Overmars describes this problem as a “minor incompatibility with room transitions”,
The General Interface
The first thing we notice when looking P age |6
Reviews
GAME DEVELOPER IDES
Game Maker 7.0 Cont.
part; libraries are already being integrated into Game Maker – at a different level, true, but I think that was enough. Integrating them in this way as well would cause confusion: where is this library? Is it in an extension package? Or maybe it is in the lib folder? The thing is, they now have their own help – and that’s the positive thing. What occurred to me was that Mark could move all libraries to Extension Packages, but then another problem arises: compatibility. I guess it is difficult to figure something out, but for the extension packages (or at least the library part) to be better and probably less confusing, Mark should’ve thought of something. Let’s examine the process of adding/removing an installed extension to the Game. We click on Extension Packages, we click on the available packages and choose the package we want, an arrow appears, we click it, boom! Here it is! To remove an extension, we click on Used Packages, click the package we want to remove, we click on the arrow that appears, and it’s gone! To summarize, it’s easy, smooth, and a very enjoyable process overall! I like it, there’s nothing wrong with it, and I personally don’t think it could’ve been done in a better way – this is what it needs to be. inclusion mechanism. The reason was that Mark wanted to keep Game Maker simpler and easier, and now, he’s returning some of the features we saw in the Data File resource to the inclusion mechanism. This has resulted in a simple and understandable file inclusion mechanism – Just like Mark wants, and at the same time a fully capable way of storing and handling files – Just like experienced members wanted. It’s a win-win! there are many other smaller features in store, some of which are very nice, and others which are useless!
Publishing Games
On the Game Maker part, it is only a simple button that links to a web page, no big deal. But it is a big feature, guess why? Mark is finally making it simpler for newbies to publish their games onto the web via the Game Maker website! Bravo!
Splash Screens
Splash screen functionality has been expanded? I doubt many people will be happy about it, but I for one am. I haven’t seen many people use splash screens in Game Maker, even though splash screens are considered an important part of the presentation of the game, before it is actually played. Hopefully now with better splash screen functions, we would see more splash screens used in Game Maker in the future.
Windows Vista Compatibility
Previous versions of Game Maker have had a problem running on the final version of Windows Vista. So, in Game Maker 7.0, Mark fixes that problem! Yes, Game Maker now works on Windows Vista! What’s the trick? There’s an additional 1 MB of runner data attached to every Game Maker 7.0 executable, nice. So, no big deal; most of us have broadband and don’t care about an addition 1 MB of file size, true. But the other problem that Game Maker has is that when it runs on Windows Vista, a User Account Control (UAC) Dialog appears that asks if you want to run this executable, not nice. But of course, you get that kind of dialog for every unsigned, unknown-authored executable, not just Game Maker executables.
The Separate Close Event
So that’s a nice thing, you bet. Having a separate event for the close button is definitely a smart thing, and has already helped me working on a couple of projects that I quickly converter to Game Maker 7 to test it in order to make this review. It’s useful, and it doesn’t waste space or anything – it’s just added to the other events list!
File Inclusion
A rather controversial move Mark did in Game Maker 6.0 was the removal of the Data File resource type, in favor of a much simpler and more limited file
It’s the Pro Version!
Smaller Features
Be afraid not, my faithful readers; for
Instead of having a “Registered” version of Game Maker, now members with a registered copy would notice that their
April, 2007
7|P a ge
Reviews
GAME DEVELOPER IDES
Game Maker 7.0 Cont.
copy of Game Maker is labeled “Pro”. Additionally, the unregistered version is now called the “Lite” version. There is absolutely no underlying change: just the name.
Functions Renamed
The functions in all official Game Maker action libraries have been changed to be compatible with the book. This isn’t really a new feature to Game Maker 7.0, as it has been introduced in Game Maker 6.1a, but the thing is: Mark hasn’t released that over the internet, so it is a new feature for most users, since they don’t have the book.
script and code editors, you will be capable of seeing a print button that prints the code. I understand how some people might find this function useful, but I am not too excited about it. But I don’t mind having an extra button that I don’t use.
Save and Load Debug Info
So the debug info forms now have new save and load buttons added to them. I personally have never found the whole debugging to be that useful, but I admit to have used it on multiple occasions – but save and load? I’m not sure how it would be useful, but apparently Mark does.
Game Maker now accepts more File Formats
That is truly good news! Functionality for functions concerning splashes screens, sprites, and backgrounds used in GML to load a certain image or video from a file during run time have been enhanced to accept more file formats. Yes! That should have been done since GM 3!
Even Smaller Features
I’ve said before and I’ll say it again: I’m going to cover every single change made in Game Maker 7.0, and I mean it! If I forget about one, then tell me and I’ll add it! Here’s the list of even smaller and more insignificant features:
View Events: Outside View and Intersect Boundary
I’m serious: I’ve needed those events for my game! These are very useful events, especially for those games with huge rooms and enormous amounts of instances.
Select All in Image Editor
You are now capable of using the Ctrl+A keyboard shortcut, or the “Select All” command to select all of the contents of the image. Game Maker has always needed that since Game Maker 6, where selection was first introduced.
Move Actions
The move actions in the “Move Action Library” have had their buttons updated, so when you click on the blue arrows for moving actions, they turn red. Very small change, but nice, and would probably help the user recognize which buttons are being pressed in an easier way.
Showing Errors
So that’s a nice little feature: errors are now shown in a text area, nice! I can copy, that’s one thing, but also: huge errors (as in errors where the line of code they are in has too much doe) scroll over and do not result in a huge window that blocks the entire screen!
Centering a Message
The function message_position() has always existed, what’s new however is that setting the X and/or Y arguments to -1 centers the message! I’ve always thought that ability had excited before! Well, apparently it did not, and at least Mark added it now.
Showing Loading Bar
Now this is a nice move, the loading bar of the game now appears “considerably earlier” than before. This means that you don’t actually wait for a few seconds wondering if the game started running when you click run! Good job.
Getting, Setting, and Randomizing the Seed for Random Functions
What? I read the help section about that twice before I got it. Basically, it allows you to set a seed used to generate random numbers. Of course,
What’s button?
that
little
extra
Oh yes! It’s a print button! Now, on the P age |8
Reviews
GAME DEVELOPER IDES
Game Maker 7.0 Cont.
random number generation doesn’t solely depend on this value.
Navigating through a Sprite’s Sub-Images
So that’s nice: you can now navigate to the next and previous sub-image of a sprite. This will speed up editing a lot, won’t it? Nice feature, and bugs reported in betas have been solved, so don’t expect seeing errors or having problems when using this feature. I think it would be particularly useful when someone is working on manually animating a sprite. That way the spriter could move directly between the two frames and manipulate each frame accordingly.
missed in Game Maker 6. The pen_size variable (or whatever it was called) provided a very similar effect in Game Maker 5, but had been removed from Game Maker 6, since it used Direct3D. Well, now Game Maker has a function that would mimic part of that old function, yay!
they are being run.
Bugs Corrected
Mark has corrected a handful of bugs and annoyances in Game Maker 7.0, and no: I’m not talking about bugs in the beta itself, I’m talking about bugs in the previous versions of Game Maker. We will now examine these corrected bugs and the impact those fixes will have on the overall game making experience.
IS IT DAMN SUCCESSFUL?
Now we can finally know! Functions for starting and stopping d3d_ now finally return whether or not they are successful. Thank you!
Corrupt Files
Here’s a cool new feature in Game Maker 7.0: Game Maker is now more capable of reading Game Maker Source files, it doesn’t tell you it’s corrupt if it still is readable for the most part. Mark claims that most Game Maker files that GM labeled as corrupt will now be readable by Game Maker 7.0! Now that’s nice!
Setting the Cursor Sprite
Apparently we have a variable for that: cursor_sprite. From what I’ve heard it had been around for a while, but Mark only documented it now.
The ‘globalvar’ Declaration
Many people use the “var” to declare variables, well guess what? You can now use “globalvar” to declare global variables! What’s the use, you ask? Well, after declaring a global variable in such a way, you are not required to write “global.” before the variable name.
We Need More Arguments!
And we have more arguments! DLL Functions now support up to 16 arguments, cool indeed!
Major Fixes
A major fix is the encryption of scripts via runtime, and other protections to the executable file of Game Maker games. These fixes make it much harder for people to decompile a game and to view or use the code by accessing it via the RAM on runtime. This is an excellent security fix and should save great games’ sources for being viewed by unauthorized people. Please note that I am not in any way here talking about the .gmk encryption, I am talking about encryption to the executable and scripts themselves when
Corrected Limited Real Precision Bug – I know the time now!
Game Maker 7.0 has finally solved a bug that existed at least from Game Maker 6.0, where basically real numbers with a certain precision weren’t handled correctly. Since date and time in Game Maker are also expressed by real values, getting the date and time wasn’t always correct; sometimes it’d tell you it is January 24 when in fact it is January 25! I’m glad this is over, because I had huge date and time problems in one of my projects
F9 Function Screenshots
Key
Takes
Pressing the F9 function key now takes a screenshot of the game. This minifeature could be disabled via the Global Game Settings, so don’t worry if you don’t want people to use your sprites or take screenshots of your game for any other reason.
Draw a line with a width!
That is a function that we have indeed
Corrected Timeline Bug
A bug in timelines has finally been 9|P a ge
April, 2007
Reviews
GAME DEVELOPER IDES
Game Maker 7.0 Cont.
corrected! The bug occurred when content is duplicated to an earlier moment in the timeline.
No more Syntax Errors for Bitwise Assignments
Assignments such as =, +=, etc. have always worked properly; because they are the most used. But finally: now, also bitwise assignments work properly! What are bitwise assignments? They are those assignments using bitwise operators, such as &, |, ^, <<, and >>. So now, using &= |=, >>=, etc. should give out no errors, supposedly.
people discovered is that they were capable of extracting information from Games at run time. There were some other flaws too, have lead to a successful decompiling attempt. But: Mark fixed that now, thankfully. So we shouldn’t be worrying about having our creations subject to decompiling, for the short term at least. It is in general recommended, however, that we keep things like passwords away from our Games’ executables.
and a border rectangle. Smart.
Empty Window Shown Before Create Event
Were you ever annoyed that when showing messages on Create Event, you’ll actually need to move them to a later event (or use redraw functions)? Well now, the window is shown earlier, so from moment the create event is executed, the window is there. I have my concerns on this “fix”, as probably many people were satisfied that the window weren’t shown before. There is no way to predict whether or not will this fix backfire, except for waiting.
Less Annoying Debug Forms
Debug forms are now less annoying, Mark says. Debug forms no longer keep jumping to the top position.
Show Message actions keep box centered
All show message actions keep the show_message function itself centered in the screen (unless the position itself is changed). This is important for providing users with a better experience when playing your Game, even though it’s probably not that big of a deal.
No More Multiple Fonts, Median Now works properly ALWAYS Color Coding!
So, I bet most of you have had this problem. Copying a piece of code from somewhere like a webpage where it has been formatted results in having it pasted in that same formatting, and no color coding is applied. That has been a very annoying bug in Game Maker, and Mark has finally fixed it in the 7.0 release!
Explosions work, Even at cold weather!
I’ve never knew that, but apparently using explosions with the snow effects at the same time caused problems! Good news: it is now fixed and they both work properly!
I don’t know about the rest of the people, but I personally use the median() function a lot. For those who do not know, the median function calculates the average of a number of values entered, and is really useful in numerous games. Apparently, it had a problem, but it has been fixed in this version.
Backgrounds settings
keep
their Resizing crashes
Grid:
No
more
Don’t Worry Decompiling!
About
So in Game Maker 6, we’ve all heard about Mark’s huge efforts to stop decompiling from occurring, and it worked for a while. Though decompiling itself didn’t occur for a long time, what
A rather annoying bug was that backgrounds would lose all of their settings when you change the background image. Luckily, it has been fixed in GM7.
I haven’t noticed that bug to be honest, but apparently, Game Maker crashes sometimes when grids are being resized. Mark has finally solved that issue now, but I’m still confused – because I’ve never saw it.
Rectangles are now accurately drawn
Grid Data Structures Now Work Well With Strings So, now there is now no difference
between the size of a solid rectangle
The “grid” data structure previously had
P a g e | 10
Reviews
GAME DEVELOPER IDES
Game Maker 7.0 Cont.
problems with storing string values; this has been fixed in Game Maker 7.0. parents. That is incredibly good news, from my point of view.
Sprite Preview Issues – Fixed
The sprite preview pane sometimes showed sprites as being transparent even though they have been set to nontransparent. This issue has now been fixed: all sprites preview correctly.
Bounce Bounces Correctly!
So that’s good news: if you have diagonal surfaces, and use the bounce action on collision, the object will now realistically bounce off it, and it wouldn’t treat it like horizontal and vertical surfaces.
community, and many have strongly opposed it, trying to let Mark change his mind about it. About the .gmk encryption, it refers to the fact that Game Maker 7.0 source files are now encrypted, and their content cannot be read. The encryption isn’t a security issue, since the file being encrypted isn’t the executable, but instead the source itself! Here’s the thing, Mark never lied: the .gmk encryption is aimed to stop projects that access Game Maker source files like G-Java. It is Mark’s belief that by stopping projects like G-Java, it is actually in Game Maker’s best interest, and he means it. Users were upset because they thought what Mark was sort of a betrayal to the Game Maker members who have worked hard to provide such tools for Game Maker. They also believe that Mark hasn’t gave much thought about incorporating that “feature”, and have said that it would do more harm than good to Game Maker, since those making these tools could decide to make their own Game Development toolkits that rival against Game Maker. In my point of view, however, Mark’s probably more right. Converters would create lots of benefit for Game Maker, true. But the important point is, they would create much confusion to the beginner users, it might as well hurt Game Maker’s reputation when features in the converters themselves do not work – and that was what concerned Mark. 11 | P a g e
Collision Checking works with Scaled Instances
If an instance of an object has a scaled sprite, it won’t stop you from having proper collision checking in Game Maker 7.0! That’s indeed good news.
Is there something wrong with Game Maker 7.0?
You might ask: is there something wrong with Game Maker 7.0? And the answer would be: definitely. Game Maker 7.0 is by far not perfect when we judge it a separate piece of software. However, when looking at it at a simple upgrade, it has no bad points compared to Game Maker 6.1 (except for the .gmk encryption, we’re getting to that later). So, this means that if you want to use Game Maker as a regular game development tool, you definitely should get Game Maker7.0 –it is that simple: Game Maker 7.0 isn’t worse than Game Maker 6.1, as a matter of fact: it’s better. The other question is: is it what we had expected? And the answer to that could be different from person to person; I’ll tell you my point of view after a couple of sections.
Collision_ Functions with noninteger Coordinates work properly
All of the collision_ functions that check for collisions between lines, rectangles, circles, etc. and objects now work as expected, even if their coordinates are non-integers.
Opening a Non-Existent Binary File Creates it
As with the rest of file handling functions, the open function for binary files file_bin_open() now creates the file to be opened if it doesn’t exist. It’s surprising such function didn’t exist before.
Setting Object Parent Via GML now has Checks
So, the object setting function of GML now has addition checks to see if any cycles were made in the object’s April, 2007
The .GMK Encryption
The “.gmk encryption” is a new change in Game Maker introduced by Mark Overmars. It has been highly controversial in the Game Maker
Reviews
GAME DEVELOPER IDES
Game Maker 7.0 Cont.
Still though, it is a shame to see such projects fade away, and I would truly hope to still see those years later (on Game Maker 6), to provide “ports” to Game Maker in other languages and systems. Game Maker simultaneously on your machine, so you could both take advantage of Game Maker 7’s new features and the lack of source code encryption Game Maker 6.1 has, if you’re considering converting to Java or other languages. It has few “big features”, yes, but it isn’t a disappointment –at least for me; because every one of those “small features” would truly make a difference to a Game developer. It would be a disappointment however, if we expected the changes to be as significant as the 5.3A->6.0 differences. THEN, it would have been truly disappointing. Good job, Mark Overmars; this is truly a great tool, and this is truly a great release. Some of us would have expected more, but I’m pretty sure we’re getting more in the future. Eyas Sharaiha
Should I get Game Maker 7.0?
Almost definitely yes! Game Maker 7.0 provides more compatibility, more fixes, and more functionality, the only reason you might stick to using Game Maker 6.1 is to take advantage of the tools like G-Java, which are no longer allowed to work on Game Maker 7.0. Even so, you might consider running both versions of
Final Remarks
Game Maker 7 is definitely better than Game Maker 6.x, and is definitely worth to upgrade for a few reasons: it’s free and easy to upgrade, so why not get a better version. However, I must really look at Game Maker 7.0 from another perspective and ask myself: is it a disappointing release?
Game Maker Tutorial
Getting the number of blue pixels on the screen in Game Maker is an excellent example of the return function of Game Maker. This script makes a loop that checks the color of each pixel on the room. To do this, we check one row at a time, then move on to the next row. It then returns the number of blue pixels in the current room. Handy if you were making a game that required user interaction with colors, or for a drawing program. The Example
TUTORIAL
width=room_width; height=room_height; current_x=0; current_y=0; blue_pixels=0; repeat(height) { repeat(width) { current_pixel_color=draw_getpixel(current_x,current_y); if current_pixel_color==c_blue { blue_pixels+=1; } } current_y+=1; current_x=0; } return blue_pixels;
P a g e | 12
Tutorial
DRAWING TUTORIAL
Surfaces
reset) the surface.
Introduction
Surfaces is a new feature that was added in Game Maker 6.1, it allows the user to use the normal draw functions to draw on a canvas, or a “surface” once, and then, it can be saved to a file, drawn on the screen, go through some manipulations and rotations, or get copied to another surface.
But this is not all what surfaces are about! When you draw a surface, the surface uses the system temporary memory to save its contents, which means it acts as if it is a bitmap file (or something similar) in a file in the Main Memory! So that is why speed is saved when using a surface. Since we now know what a surface is, I think we can start learning about the code these surfaces use in order to function.
enter in the “w” field in the “surface_create(w, h)” function. surface_get_height(id) Returns the height of the surface with the given id. The height is what you inter in the “h” field in the “surface_create(w, h)” function.
First Attempt
Ok! So let’s try out these functions that we have just learnt in a piece of code, and see what happens! We will create an object called “o_surfaces” and put this code in its Create Event.
surface=surface_create(50,100); //Creates the surface draw_text(5,5,“This text is drawn in the create event.”); /*The code above attempts to draw text in the create event!*/
Benefits
Surfaces usually are handy when making a paint system, like MS Paint. You draw a line to the screen, then the line is saved on the surface, and the surface is drawn at the end of each step, which means that even if you draw thousands of lines on the surface, then draw the surface on the screen, the game will still run fast, as the surface is drawn all at once, not each line separately.
Primary Code
The Basics
surface_create(w, h) Creates a new surface with the width “w” and height “h.” It then returns the surface “id” which is used in all the other functions. This means that when calling this function, you must set a variable’s value to this function, like “_var=surface_create(5,5)” surface_exists(id) Checks whether the surface with the given id exists. Returns true or false (1 or 0, respectively). surface_free(id) Frees the memory that the surface with the given id is using. This must be called when there is a surface you are no longer using in order to save memory. surface_get_width(id) Returns the width of the surface with the given id. The width is what you
Concept
To understand Surfaces more, we have to understand the regular drawing first. To do that, imagine that the main room in any game made with Game Maker is just a simple piece of cardboard, that everything you draw on it is erased after one millisecond. Therefore, if you draw a line once, it would be removed after one millisecond, which means that you need to draw it once after each millisecond is over. However, Surfaces are just a piece of paper that “flies” above the main room (or the piece of cardboard) and lines drawn on it do not get removed after each millisecond, but they stay drawn on the surface unless you empty (or April, 2007
Explanation of First Attempt The code above creates a surface called “surface” and attempts to use it to draw text in the create event, and therefore take advantage of the surfaces by using a drawing action once to draw on a surface on the screen. Problem But after you place the object in the room and run the game, you will notice that no text is drawn! “Why is that?” you wonder! Reason The answer is simple! Game Maker doesn't understand automatically when to draw on a certain surface and when you need to draw on the main room, so you need to use certain functions that will switch between drawing on surfaces and the main room, and switch 13 | P a g e
Tutorial
DRAWING TUTORIAL
Surfaces Cont.
between making the drawings on certain surfaces between each other. Code Explanation will help: surface_set_target(id) This function is the function that tells Game Maker what is the target of the drawing. You need to enter the id of which surface do you want the drawings to be on. surface_reset_target() Resets the drawing target to be on the normal screen again. It is important to use this code immediately when you finish drawing what you need on the surface, as it may mess up the whole game; objects, backgrounds, and other things are drawn on the main screen, making the game draw these things on a surface may corrupt the game. Reason It’s simple: the test is saved in the surface, and it is in the memory, but it is not drawn to the game’s main screen! It is true that I said you don’t have to use the draw functions constantly to draw all the drawings and lines, but however, you do need to draw the surface. So when you draw a 100 lines in the surface, you only need to execute one each step (the surface drawing function), not zero. Below is the code explanation for the surface drawing functions. They have been copied from the help field, and then edited to make the functions clearer. draw_surface(id, x, y) Draws the surface with the given id in the position (x, y) without any colors or alpha blending. draw_surface_stretched(id, x, y, w, h) Draws the surface with the given id stretched to the width of w and h, in the position (x, y). draw_surface_tiled(id, x, y) Draws the surface with the given id tiled so that it fills the entire room. It starts the tile in the position (x, y). draw_surface_part(id, left, top, width, height, x, y) Draws the indicated part of the surface with the given id that is drawn at the position (x, y). The part of the surface starts and the position (left, top) with the width “width” and the height “height.” draw_surface_ext(id, x, y, xscale, yscale, rot, color, alpha) Draws the surface with the given id in the position (x, y) scaled by xscale and yscale (1= no scaling) and rotated using the value rot (0=no rotation), and with blending color (use c_white for no blending) and the transparency alpha value from 0 to 1, whereas 0 is transparent completely.
draw_surface_stretched_ext(id, x, y, w, h, color, alpha)
Draws the surface with the given id stretched to the size of (w, h) in the position (x, y). Color is the blending color (c_white=no color blending) and alpha indicates the transparency setting from 0 to 1 whereas 0=transparent. draw_surface_tiled_ext(id, x, y, xscale, yscale, color, alpha) Draws the surface with the given id tiled so that it fills the entire room and starts in the position (x, y), but now with scale factors (xscale, yscale) and a color blending (color) and transparency setting (alpha) from 0 to 1 whereas 0 is transparent. draw_surface_part_ext(id, left, top, width, height, x, y, xscale, yscale, color, alpha) Draws the indicated part of the surface with the given id that starts on the position (left, top) of the surface, with
Second Attempt
surface=surface_create(50,100); //Creates the surface surface_set_target(surface); //Sets drawing surface target draw_text(5,5,“This text is drawn in the create event.”); /*The code above attempts to draw text in the create event!*/ surface_reset_target();/*Resets the drawing target. The drawing target is not set as the main screen in order for the game to continue functioning properly without corruption.*/
Problem Go ahead and test this code, you may think it will work. But it still wouldn't! Do you have any idea why?
P a g e | 14
Tutorial
DRAWING TUTORIAL
Surfaces Cont.
the width and height (width, height), with its origin at position (x, y) but now with scale factors (xscale, yscale) and a color blending (color) and transparency setting (alpha) from 0 to 1 whereas 0 is transparent. draw_surface_general(id, left, top, width, height, x, y, xscale, yscale, rot, c1, c2, c3, c4, alpha) The most general drawing function. It draws the indicated part of the surface with the given id, that starts on the position (left, top) in the surface, with the width and height of (width, height), with its origin at position (x, y) but now with scale factors (xscale, yscale), a rotation angle (rot), a color for each of the four vertices (top-left, top-right, bottom-right, and bottom-left) (c1,c2,c2,c4 respectively), and an alpha transparency value (alpha) from 0 to 1 whereas 0 is transparent. you may see that a part of the text is not drawn, that is because your surface width is “50,” and there might not be room for all the text! This, ladies and gentlemen is the magic of surfaces! Now let’s move to the more-complex part of the surfaces, which is the once dealing with files and saving. (source) to the new surface (destination). The (source) copied will be pasted in the position (x, y) of the new surface (destination). The copying occurs without doing any blending. surface_copy_part(destination, x, y, source, xs, ys, ws, hs) This function copies a part of the surface (source) to the new surface (destination). The (source) copied will be pasted in the position (x, y) of the new surface (destination). The part of the (source) to be copied will start on position (xs, ys) of the source and have the width (ws) and height (hs). The copying occurs without doing any blending.
Secondary Code
Files and Saving
surface_save(id, fname) This function saves the whole surface with the given id to a bitmap file. The filename must be a string (fname). The “fname” could be just the name of the file or its complete target. surface_save_part(id, fname, x, y, w, h) This function saves a part of the surface with the given id to a bitmap file. The filename must be a string (fname). The “fname” could be just the name of the file or its complete target. The part of the surface begins at the position (x, y) on the surface, and has the width (w) and height (h).
Cleaner Surface Drawing
To draw to a cleaner surface, all add this piece of code after surface_set_target(id): draw_clear_alpha(c_white,0); This will make the surface completely transparent.
Third Attempt
So in order to make the drawing on surfaces function work properly, you need to draw the surface in the draw event, all the other code that you have made in the create event is correct and must stay the same. Add the following code to the Draw Event.
draw_surface(surface,0,0); //Draws the surface
More Functions
surface_getpixel(id, x, y) This function gets the color of the pixel in the position (x, y) in the surface with the given id. surface_copy(destination, x, y, source) This function copies the whole surface
Special thanks & Closing Remarks
Thank you for reading this tutorial. The tutorial has been originally written by Eyas Sharaiha and published in the Game Maker community. It is now part of our wiki (GMking.org’s Wiki), you can visit the wiki here: Eyas Sharaiha 15 | P a g e
Result Now you can clearly see that the text is drawn, even though only the surface drawing function is called! Depending on your system and font-size settings,
April, 2007
Tutorial
PROGRAMMING TUTORIAL
Integration with Vista’s Game Explorer
A fabulous new feature in Microsoft’s latest version of Microsoft Windows – Windows Vista – is the Game Explorer, and it is of particular interests to us game developers, and the gamers out there as well. This article will describe – in detail – how to integrate your own game with the Game Explorer. Throughout the article, I will try to be as IDEindependent and language-independent as possible. This article will go through the whole process in great detail, so it’ll be easy to understand both for novice developers and the “gurus”. The second section of this article, specifically integrating with the installer, is based off portions from the MSDN site at Microsoft. A more complete article will be released in the next issue of markup, showing how to integrate these objects with InstallShield itself. system requirements 4- Game content rating and description Other advantages the Game Explorer provides are: Ability of parental controls to control which game ratings could be played Unique settings for multiple installations on the same systems Customizable context menus displaying actions to be performed when right clicking a game about your game. In order for your information to be shown, you must create at least one of these GDF documents. If you want your game information to differ for each different world region, then you must create multiple GDFs, one for each region. A Game Definition File has a certain format which you might abide by: The Game Definition File Schema There are certain data types allowed in Game Definition File (a table of which is at the bottom of the next page). First of all, as with any XML document, you must define it:
<?xml version="1.0" encoding="utf-16"?>
Adding your game!
In order to successfully create a game which could be added to the Game Explorer in Windows Vista, you must do two things: 1- Create certain settings and files that the system will read 2- Add these files and settings to the Installer of the game
Introduction of the Game Explorer
The Game Explorer is a new feature in Windows Vista that provides gamers with an excellent way to view information about the games they have, this includes: 1- The game title, description, version, release date, publisher, and developer information 2- Box-art image 3- Minimum and recommended P a g e | 16
This defines the XML file as an XML 1.0 file, with a UTF-16 encoding. IF you do not know much about XML documents, then you can use the line above as it is, as UTF-16 is the most common encoding, and version 1.0 is the proper version to use. Second, there’s the GameDefinitionFile element. Now I’ve searched a lot about this element, but found very little explaining its syntax. I’ve seen the syntax of how a couple of games were written, and it seems to be the same, so it’d probably be okay to include this element as it is:
<GameDefinitionFile xmlns="urn:schemas-microsoftcom:GameDescription.v1" xmlns:baseTypes="urn:schemasmicrosoft-
Creating Data Files
There are specific types of data which will be read by the Game Explorer, you must create them in order to take advantage of the Game Explorer’s capabilities. Step 1: Create GDFs A GDF is short for “Game Definition File” and it is an XML-based file carrying data
Tutorial
PROGRAMMING TUTORIAL
Vista’s Game Explorer Cont.
com:GamesExplorerBaseTypes.v1">
GameDefination Element Attributes
Name gameID
Note that the GameDefinitionFile element will be wrapped around the rest of the XML document (the structure of the whole document will later be presented). Inside the GameDefinitionFile, there’s an element called the GameDefinition element. This contains two important attributes which need to be defined (see table at right). An example is as follows:
<GameDefinition gameID="GAMEID" WMID="WMID">
Data Type guid
Description The game's ID. This uniquely identifies your game title to the Game Explorer. This is generated by you, or, in the case of certain titles, has already been provided. The game's ID for Windows Metadata Services. This should only be used for legacy games.
Game</Description>
WMID
guid
is their data type. For each element, check its data type and make sure to write it in the proper criteria. Please note that the GameDefinition element will also wrap around the rest of the document, so all later elements will be included in this element itself. An important element is the Name element. Its data type is a boundedString, and it represents the name of the game.
<Name>Super Game 2005</Name>
Another optional element is the ReleaseDate element; its data type is “date” and is written as “yyyy-mm-dd”:
<ReleaseDate>2004-0630</ReleaseDate>
An example includes:
<GameDefinition gameID="{5C08D2FF-A48E-43ca-846C08924563E5A7}" WMID="{5C08D2FF-A48E-43ca-846C08924563E5A7}">
There is an element called description with its data type as boundedString, which is an optional element to include.
<Description>The Penultimate
The version element is a choice type which contains one of the two ways of specifying the version number of your game one method is an explicit version number embedded in the XML. The other method is a path to an executable or DLL where the version number can be extracted. If it was to be written element inside the element will be VersionNumber with as a number, an main Version added, called fourPartVersion
Notice that both gameID and WMID are written in the format of a “guid” which
Game Defination File Date Types
Name fourPartVersion guid
Schema Component simpleType simpleType
Type String (with facets) String (with facets)
boundedString filePathAttributeGroup filePathAttributeGroup: baseKnownFolderID
simpleType attributeGroup attribute
String (with facets) N/A guid
filePathAttributeGroup: path April, 2007
attribute
boundedString
Description A simple type that contains a regular expression for 4-part versions A simple type that contains a regular expression for guids. Guids must be of standard type, enclosed in braces. A string which preserves whitespace and is limited to 32768 characters. Two frequently used attributes for file paths combined into an AttributeGroup. A guid that represents a KnownFolder as the base path for folders. The path passed along is relative to this known folder. If this folder isn't specified then the path attribute below is relative to the game's installation directory. A bounded string for the file path represented by this group. This file path is relative to the 17 | P baseKnownFolderID above.a g e
WindowsSystemPerformanceRating attributes
as its data type.
<Version> <VersionNumber versionNumber="1.2.3.4"/> </Version>
Name minimum
Data Type int
Description The minimum WSPR rating that a computer should have in order to play this game. The recommended WSPR rating that a computer should have in order to play this game.
recommended int
If it was to be written as a path to a file which contains the version number inside it, an element inside the main Version element should be added, called VersionFile with filePathAttributeGroup as its data type.
<Version> <VersionFile path="bin\MyGame.exe"/> </Version>
The developers element specifies the developers of this particular game, a link to their website can also be included:
<Developers> <Developer URI="">Mi crosoft</Developer> </Developers>
element is an important but optional attribute that allows you to choose the recommended and required “Windows Experience Index” values for running your game.
<WindowsSystemPerformanceRating minimum="4" recommended="5"/>
Another element I really like is the ratings element which gives you multiple rating attributes for the game, so that parents or anyone else could know if the games suit themselves, their children, or any other person. I’m not going to talk much about that element, but you can read more info at their MSDN article. Use the links at the end of the article. The Game Executables element is the last one I’ll talk about. It is very simple to use and understand:
<GameExecutables> <GameExecutable path="bin\game.exe"/> </GameExecutables>
The table below lists the attributes for WindowsSystemPerformanceRating. There’s also an element called the genres element, which could contain multiple genre elements, it looks as follows:
<Genres> <Genre>Action</Genre> <Genre>Adventure</Genre>
Note: A total of five different developer links could be added inside the developers element
The publishers element specifies the </Genres> publishers of this particular game, a link Complete document code to their website can alos be included:
<Publishers> <Publisher URI="">Mi crosoft</Publisher> </Publishers>
An example of the complete code of the document is below:
Note: A total of five different developer links could be added inside the developers element The WindowsSystemPerformanceRating P a g e | 18
<?xml version="1.0" encoding="utf-16"?> <GameDefinitionFile xmlns="urn:schemas-microsoftcom>
Tutorial
PROGRAMMING TUTORIAL
Vista’s Game Explorer Cont.. Step 3: Embed Bitmaps and GDFs After creating the GDF and Bitmap files, you can now embed them all together. an IGameExplorer COM Object in the Installation Your next step would be creating an IGameExplorer COM object. As seen in reference (4). Step 3: Call function “VerifyAccess” in the IGameExplorer The function VerifyAccess must be called from the IGameExplorer COM object. It will check if the game has permission to run on the current user account. As seen in reference (5). Step 4: Call function “AddGame” in the IGameExplorer The function AddGame must be called from the IGameExplorer COM object. You must call AddGame with the path to your GDF resource, base install path, and install scope, and optionally an InstanceID GUID. The add game following syntax: function has the For more information, see ref. (6). Step 5: Persist Game InstanceID You must persist the InstanceID that is returned from the AddGame function. This is needed in order to be able to properly uninstall the game. Step 6: Create Game Task Folders As seen in reference (9), you must use the InstanceID to create a subdirectory of that ID either in the common task directory used for all files or in the user-specific task directory. In that folder, you should create the tasks that could be done with the game. Eyas Sharaiha
References
1. Main Page, 2. Defined constants of GameUx.h, 3. GDF file schema, 4. IGameExplorer COM, 5. Verify Access, 6. AddGame, 7. Game Explorer Tasks, 8. Registry information (XP), 9. Create Game Task Folders,
Adding the Game from the Installer
Step 1: Install the game files
HRESULT AddGame( const BSTR bstrGDFBinaryPath, const BSTR bstrGameInstallDirectory, GAME_INSTALL_SCOPE installScope, GUID* pguidInstanceID );
April, 2007
19 | P a g e
Tutorial
PROGRAMMING TUTORIAL
C++ “Hello World” tutorial
C++ is one of the most popular programming languages out there, but learning can be a tedious process. One of the first things anyone learning C++ should know is outputting text. Unlike more recent software, no function exists in C++ “as is” that could display text; instead, you need include “libraries” that would introduce such functions and capabilities. To start the tutorial, open a new C++ project, and start working on the main .cpp file. (Need a development tool? Try Microsoft Visual C++ 2005 Express Edition SP1, you can get it from
normal. The important thing is knowing that the line of code "int main()" initializes the code. It is in this function that all the actions occur. Many also like to use:
void main()
now, but most functions return values of some sort, so the return itself is used to mark the end of a function. Since we really do not need to return any value, let’s just choose to return “0”:
return 0;
But I personally – for some weird reason – prefer using int, so that’s how we’re going to continue. The curled brackets you saw earlier define the beginning and ending of a block of code. All the code that we will perform in this tutorial must be in the int main() block of code. The actual code to output the “Hello world!” text is:
std::cout << "Hello World!!\n";
Final Code Form
#include <iostream> int main() { std::cout << "Hello World!!\n"; return 0; }
Running the code
You can build the C++ project or you can use the Debug function to run it. Note: in Visual C++ 2005 Express Edition, you will not get a "Press Any Key to Continue . . ." message, and the program ends instantly if it is run in debug mode, therefore you will see no result. To fix that, click on the Debug menu on top, and then click on the menu item "Start Without Debugging".
and, it’s totally free!)
The Code
The very first thing you should include is Input/output stream that would allow you to output text. In older versions of C++, you could include a header file (.h file) that would give you these functions, but now it is done differently:
#include <iostream>
The “std::cout<<” is the command that tells the computer to output text. The text written later must be a “string” – so text and numbers should be surrounded by quotation marks. The final “\n” you see at the end defines a new line, similar to the Enter Key we use when typing text in notepad or word. If this wasn’t use, the “Insert any key to continue” text that is normally automatically outputted by C++ would be right next to the “!!” in the text you outputted. Another important thing is that all instructions must end with a semicolon (;), otherwise an error is outputted. Finally, to conclude the function “main”, we need to write a return instruction, this might seem pretty meaningless
End Result
When running the program, you should see the following:
Hello World!! Press any key to continue . . .
To start giving out instructions to output the text, you should first initialize the main function that would execute the actual code. You could do so by typing:
int main() { … }
The "int" stands for integer. That means "int" initializes the function main()’s returned value as an integer. This might be hard to understand when you first start programming C++, but that's P a g e | 20
However, if you have omitted the “\n” (newline) at the end of the code, as stated earlier, you would see:
Hello World!!Press any key to continue . . .
Eyas Sharaiha
gmpedia.org forums.gmking.org openload.info ircbloopers.com gmking.org irc://irc.gamemaking.org/#gmking
April, 2007
21 | P a g e
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue reading from where you left off, or restart the preview. | https://www.scribd.com/document/24605/Markup-Issue-2 | CC-MAIN-2017-04 | refinedweb | 11,283 | 70.02 |
Firmware Over the Air
Firmware Over the Air (FOTA) is our latest development for Bluetooth Low Energy (BLE) devices. We’re working towards enabling FOTA for the platforms based on Nordic’s nRF51822 Bluetooth system, so that any BLE application may enable FOTA by the simple addition of a Device Firmware Upgrade (DFU) service to its GATT server.
You can view a short video about FOTA, starting at 01:55. We’ll show you the same example, in greater detail, below.
Note that this functionality requires the use of a (Nordic-specific) DFU boot loader on the device, to provide the basic functionality of firmware download and reprogramming. Instructions for the boot loader’s installation are available below.
Warning: at the moment, the firmware-update protocol has very little security; we’re working on this.
We’ll start with a general review of the software components needed to support FOTA, and then move to an execution example to show just how easily a FOTA update can be performed.
Software components
The following figure shows the layout of the main software components of a FOTA-capable system. These include:
SoftDevice: Nordic’s encapsulation of the Bluetooth stack.
Application: the user’s BLE application.
Boot loader: responsible for firmware updates.
Main software components in a FOTA-dapable system
How FOTA updates work
FOTA updates rely on the SoftDevice and boot loader:
On power up, the SoftDevice checks the User Information Configuration Register (UICR). The UICR can point either to the app or to the boot loader.
If the UICR points to the app, the SoftDevice passes control to the app, which starts up normally.
If the UICR points to the boot loader, the SoftDevice passes control to the boot loader. The UICR will point to the boot loader if the boot loader had overwritten it; see our Default Boot Loader to understand how that’s done. For a FOTA platform, a bootloader is always resident, with the UICR pointing to it.
The boot loader determines if either control needs to be forwarded to the application or if it should remain waiting for a new application firmware image to be sent over the DFU service. The former case being the default.
FOTA is reliable, but the application might block it by hanging in interrupt context (preventing the BLE stack from receiving an update, which prevents FOTA’s forwarding control to the boot loader). In this case, you’ll have to restart the device to enable further updates.
The FOTA process can currently be driven from an external BLE agent, such as an Android phone. For the moment, we recommend using Nordic’s nRF Master Control Panel as a generic tool. You can see more information about it below.
We’ll soon be releasing our own reference apps for iOS and Android, together with SDKs to build custom apps for FOTA.
FOTA sequence diagram
The default boot loader
The boot loader must be preinstalled on the device. To install a fully-functional default boot loader, please download this image. Remember that it is designed for the Nordic nRF51822 mKIT.
The image also contains a default application, which serves as an example of FOTA implementation. See below for more information.
Update packages
mbed platforms typically come with an interface chip called CMSIS-DAP, which offers drag-n-drop programming (usually over USB). This mechanism erases everything on the chip before programming the new firmware, so binaries used with this method must include the SoftDevice and any other pre-requisites. FOTA application updates are different; they affect only the application, so the SoftDevice and boot loader aren’t deleted, and therefore don’t need to be included in the application update package. This reduces the size of the package, helping it meet BLE limitations.
Virtual platforms
As we said, FOTA applications don’t need to be combined with the SoftDevice as they do not erase the existing SoftDevice. They therefore need a separate (virtual) build target for each Nordic platform. These are generated by building for “shadow” platforms specifically intended for FOTA. You can get virtual platforms for mKIT, nRF-DK and others. You’ll need to add these to your online compiler and build for them when generating FOTA binaries.
Adding DFU support to an application
When you build for a FOTA-enabled platform, an instance of DFUService is implicitly added during the call to ble.init(). The assumption is that any application built for a FOTA-enabled platform wants to enable FOTA.
If you’re building for a non-FOTA platform, you’ll need to explicitly introduce DFUService support into an application; this requires only two lines of code:
Include the
DFUService.hheader.
Call the service, as shown below:
/* Enable over-the-air firmware updates. *Instantiating DFUSservice introduces a * control characteristic which can be used to * trigger the application to * handover control to a resident bootloader. */ DFUService dfu(ble);
Running a FOTA update
The next three sections explain how to use Nordic’s Master Control Panel to view, trigger and drive a FOTA update. As an example, we’ll update the default app bundled into the initial boot loader image. Among other services, this application offers a DFU service that supports FOTA.
You can view a short video demonstrating this, starting at 01:55.
Viewing the DFU service
The following images show how to use Nordic’s Master Control Panel to view a DFU-capable application.
- The default app (DefaultApp), listed in the Master Control Panel. Tap the app to view more information.
- General information for the default app. Note the Device Firmware Update Service section; tap the section to view more information.
- Detailed information for the Device Firmware Update Service.
Triggering FOTA
The following images show how Nordic’s Master Control Panel can be used to cause a DFU-capable application to forward control to the boot loader. The boot loader then checks for firmware updates on the server and transfers them to the device:
- We start at the detailed view of the app that we saw in the previous section. The DFU Control Point offers FOTA triggers.
- Tap the up arrow to view the write options. This is the FOTA’s control-point.
- The control-point options are:
- SoftDevice.
- Boot loader.
- Application.
- For this example, we select the third option: Application.
- The Master Control Panel now shows the default application under the name DfuTarg, indicating that the boot loader is running.
Driving FOTA
Finally, these images show the main FOTA sequence using the boot loader:
- We start at the detailed view of the app that we saw in the first section. Since we already triggered FOTA in the previous section (meaning we transferred control of the application to the DFU-service), we can now update the application.
- Tap the DFU button to select a file type.
The file type options are:
- SoftDevice.
- Boot loader.
- Application.
- Multiple files (in ZIP format).
For this example, we select the Application file type.
- We can now select a source for the file.
- The update begins as soon as we select the file. We can see its progress, and the transfer speed.
- When the update is finished, we return to the Master Control Panel. The application is no longer under the boot loader’s control. Instead, it is back under its own control, and is therefore no longer listed as DfuTarg (note that the update changed the application’s name, so that it is also no longer called DefaultApp).
Attribute and service caching
Note that a GATT client app often caches the results from a service discovery. However, after changing or updating an application – and especially after replacing it with a different application – your app may need to re-discover services. You may therefore want to restart the app or the Bluetooth service after a FOTA update.
UART access over BLE
Overview
If you want to receive console outputs from an updated app, it is possible to do so over the BLE UART Service. For instance, the default app that comes bundled with the boot loader generates regular pings on the RX characteristic of the UARTService. These pings can be received using several UART apps, such as Nordic’s nRF UART.
Please note:
At the moment, you cannot have more than one active connection to a BLE device. For example, if you’re working with a heart-rate application and you’ve connected to it using nRF UART for console output, then you cannot simultaneously connect to it from another heart-rate phone app.
Console messages are sent in notification packets of up to 20 bytes; this limit is imposed by the Bluetooth standard. the BLE_UARTConsole program to your compiler.
#if NEED_CONSOLE_OUTPUT #define DEBUG(STR) { if (uart) uart->write(STR, strlen(STR)); } #else #define DEBUG(...) /* nothing */ #endif /* #if NEED_CONSOLE_OUTPUT */ uart = new UARTService(ble); DEBUG("ping\r\n");
Note: You will need to include
UARTService.h.
Limitations of the current implementation
There is no security or safety built into the process yet; anyone with the right tools can update a FOTA-capable target. Resolving this is very high on our priorities.
Building FOTA binaries currently requires using a “shadow” build platform for every target. This process is cumbersome and should be simplified.
FOTA requires installing an initial image containing the boot loader. For non-official mbed platforms, this means that a user would need to understand the internals well enough to be able to build an initial image, and also find a programming interface to transfer it to the target. We’re working on releasing a USB->SWD adaptor that can target nRF51822 boards that don’t have an mbed CMSIS-DAP interface.
The two-stage FOTA process is cumbersome and error-prone. We’re working on creating a simple reference app to drive FOTA. Eventually we hope to release an SDK to allow users to create their own FOTA driver applications. | https://docs.mbed.com/docs/ble-intros/en/master/Advanced/FOTA/ | CC-MAIN-2018-05 | refinedweb | 1,644 | 55.03 |
With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.
import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.ToolItem; public class ToolBarListener implements Listener { private Shell shell; @Override public void handleEvent(Event event) { ToolItem toolItem = (ToolItem) event.widget; if (toolItem == Gui.item1) { System.out.println("item1 clicked..."); DirectoryDialog dlg = new DirectoryDialog(shell); String dir = dlg.open(); System.out.println("chosen dir : " + dir); } else if (toolItem == Gui.item13) { Gui.swichTabChecks(); } else if (toolItem == Gui.item23) { Gui.swichTabResults(); } else if (toolItem == Gui.item3333333) { Gui.swichTabFiles(); } } public void setShell(Shell shell) { this.shell = shell; } }
} else if (toolItem == Gui.item111) {
FileDialog fd = new FileDialog(shell, SWT.MULTI);
String firstFile = fd.open();
if (firstFile != null) {
String[] selectedFiles = fd.getFileNames();
for (int ii = 0; ii < selectedFiles.length; ii++ ) {
System.out.println("select
}
}
}
What it does is, it selects the folders because the DirectoryDialog is before the FileDialog in the if statement.
If I remove this piece of if statement then the new code that you suggested can only select multiple files but not the folders.
This is the code I have:
Open in new window
My requirement is to select multiple files and/or directories by using the same icon. Also, files and directories should be selected at the same time in one shot.
So as an example, I have the following files and folders in directory A.
Open in new window
I should be able to select the following files and folders in dirA directory in one shot by using the same icon on the UI:
Open in new window
I would appreciate if you can help me with that.
Thanks,
With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.
You need to develop your own custom widget.
I found exactly what you need here:
Thank you for your reply. Can you please tell me in more detail how I will use the cod that you sent me in the link?
Currently, this is the code that I use to select directories. How should I change this code/
Open in new window
I would appreciate if you could take a look at these questions?
Thanks,
If you have time, can you please take a look at my other questions?
Thanks,
FileTree.java
I created the file you sent me, FileTree.java.
I added the following line to ToolBarListener.java:
Open in new window
I added this listener in Gui.java:
Open in new window
Then I created this function in Gui.java:
Open in new window
But I don't know what to write in it.
Can you please help?
Can you please take a look at this question?
Thanks,
Can you please take a look at this open question:
Thanks, | https://www.experts-exchange.com/questions/28160970/How-to-select-multiple-files-and-or-folders-at-the-same-time-in-a-GUI-by-using-SWT.html | CC-MAIN-2018-09 | refinedweb | 518 | 60.61 |
Regular Expression Improvements in .NET 7
A friend once quipped to me that “computer science is entirely about sorting and searching”. While that’s a gross overgeneralization, there’s a grain of truth to it. Searching is, in one way, shape, or form, at the heart of many workloads, and it’s so important that multiple domain-specific languages have been created over the years to ease the task of expressing searches. Arguably none is more ubiquitous than regular expressions.
A regular expression, or regex, is a string that enables a developer to express a pattern being searched for, making it a very common way to search text and to extract from the results key finds. Every major development platform has one or more regex libraries, either built into the platform or available as a separate library, and .NET is no exception. .NET’s
System.Text.RegularExpressions namespace has been around since the early 2000s, introduced as part of .NET Framework 1.1, and is used by thousands upon thousands of .NET applications and services.
At the time it was introduced, it was a state-of-the-art design and implementation. Over the years, however, it didn’t evolve significantly, and it fell behind the rest of the industry. This was rectified in .NET 5, where we re-invested in making
Regex very competitive, with many improvements and optimizations to its implementation (elaborated on in Regex Performance Improvements in .NET 5). However, those efforts didn’t expand much upon its functionality. Now with .NET 7, we’ve again heavily invested in improving
Regex, for performance but also for significant functional enhancements.
In this post, we’ll explore many of these improvements to highlight why
Regex in .NET 7 is an awesome choice for your text searching needs in .NET.
Table Of Contents
- Backtracking (and
RegexOptions.NonBacktracking)
- StringSyntaxAttribute.Regex)
- Case-insensitive matching (and RegexOptions.IgnoreCase)
- Source Generation
- Spans
- Vectorization
- Auto-Atomicity and Backtracking
- Set Optimizations
- What’s Next?
Backtracking (and
RegexOptions.NonBacktracking)
There are multiple ways a regex engine (the thing that does the actual searching) can be implemented. Since the beginning of .NET’s
Regex, it’s employed a “backtracking” engine, sometimes called a “regex-directed” engine. Such engines work the way you might logically think about performing a search in your head: try one thing, and if it fails, go back and try the next… hence, “backtracking”. For example, given a pattern
"a{3}|b{4}", which says “match either three
'a' characters or four
'b' characters”, a backtracking engine will walk along the input text, and at each relevant position, first try to match three
'a's, and if it can’t, then try to match four
'b's. In doing so, it might end up needing to examine the same text multiple times. Backtracking engines are capable of supporting more than just “regular languages”, and are a very popular form of engine because they enable fully implementing features like backreferences and lookarounds. Such backtracking engines also can be incredibly efficient, in particular when the thing being searched for matches and does so with as few wrong tries along the way as possible.
The problem with backtracking engine performance isn’t the best-case or even the expected-case, however, but rather the worst-case. You can find explanations of “catastrophic backtracking” or “excessive backtracking” all over the internet. Most of them use nested loops as an example, however I find that it’s easier to reason about with alternations. Consider an expression like
^(\d\w|\w\d)$; this expression ensures you’re matching at the beginning of the input, then matches either a digit followed by a word character, or a word character followed by a digit, and then requires being at the end of the input. If you try to match this against the input
"12a" (ASCII numbers are both digits and word characters), it will:
- Match
\d\wagainst
"12".
- Try to match
$but fail because it’s not at the end of the input, so backtrack to the last choice made.
- Match
\w\dagainst
"12".
- Try to match
$but fail because it’s not at the end of the input, so backtrack to the last choice made.
- There are no more choices left, so fail.
Seems simple enough, but now let’s copy-and-paste the alternation so there are two of them, and double the number of digits in the input, matching
^(\d\w|\w\d)(\d\w|\w\d)$ against
"1234a". Now we find it performs roughly as follows:
- Match alternation 1’s
\d in the second alternation, so backtrack further.
- Match alternation 1’s
\w left, so fail.
Notice that by adding one more alternation, we actually doubled the number of steps in our matching operation. If we were to add one more alternation, we’d double it again. One more, double it again. And so on. And there in lies the rub. For every additional alternation we add here, each with two possible choices, we’re allowing the implementation to backtrack through two choices for each alternation, for each of which it needs to evaluate everything else, yielding an
O(2^N) algorithm. That’s… bad.
We can actually see this in practice. Try running the following code (and after starting it, go get a cup of coffee), which is the expression we just talked about, except using a repeater to express multiple alternations rather than copy-and-pasting that subexpression multiple times:
using System.Diagnostics; using System.Text.RegularExpressions; var sw = new Stopwatch(); for (int i = 10; i <= 30; i++) { var r = new Regex($@"^(\w\d|\d\w){{{i}}}$"); string input = new string('1', (i * 2) + 1); sw.Restart(); r.IsMatch(input); sw.Stop(); Console.WriteLine($"{i}: {sw.Elapsed.TotalMilliseconds:N}ms"); }
On my machine, I see numbers like this:
10: 0.14ms 11: 0.32ms 12: 0.62ms 13: 1.26ms 14: 2.43ms 15: 5.03ms 16: 9.82ms 17: 19.71ms 18: 40.12ms 19: 79.85ms 20: 152.44ms 21: 318.82ms 22: 615.87ms 23: 1,230.21ms 24: 2,436.38ms 25: 4,895.82ms 26: 9,748.99ms 27: 19,487.77ms 28: 39,477.51ms 29: 82,267.19ms 30: 160,748.51ms
Notice how at first it’s fast, but as we increase the number of alternations, it slows down exponentially, approximately doubling in execution time on every addition. By the time we get to 30 alternations, what once was fast is now taking more than two and a half minutes.
This is the whole reason .NET’s
Regex introduced support for timeouts. In practice, most regular expressions and the inputs they’re provided do not result in this catastrophic behavior. But if you can’t trust that the pattern isn’t susceptible given the right (or, rather, wrong) input, a timeout serves as a stopgap to help mitigate the possibility of a “ReDoS” attack, a “Regex Denial-of-Service” where such catastrophic backtracking is taken advantage of to get the system to spin its wheels. Thus,
Regex supports timeouts, and guarantees that it will only do at most
O(n) work (where
n is the length of the input) between timeout checks, thus enabling a developer to prevent such runaway execution. .NET also supports setting a global timeout, such that if a timeout isn’t set on an individual problematic expression, the app itself can mitigate any such concerns.
There’s another approach, however. I mentioned that some engines are backtracking, or “regex-directed”. Others, however, in particular ones that are ok eschewing more advanced features like backreferences, and that are interested in being able to make worst-case guarantees about execution time regardless of the pattern, can opt for a more traditional “input-directed” model based on the origins of regular expressions: finite automata.
Imagine the regular expression being turned into a graph, where every construct in the pattern is represented as one or more nodes in a graph, and you can transition from one node to another based on the next character in the input. For example, consider the simple expression
abc|cd. As a directed graph, this expression could look like this:
Here, the 0 node in the graph is the “start state”, the location in the graph at which we start the matching process. If the next character is a
'c', we transition to node 3. If the next character after that is a
'd', we transition to the final state of node 4 and declare a match. However, this graph really only represents the ability to match at a single fixed location in the input; if the initial character we read isn’t an
'a‘ or a
'c', nothing is matched. To address that, we can prefix the expression with a
.*? lazy loop (here I’m using
'.' to mean “match anything” rather than “match anything other than
'n'“, as if
RegexOptions.Singleline was specified), to encapsulate the idea that we’re going to walk along the input until the first place we find
"abc" or
"cd" that matches. If we do that, we get almost the exact same graph, but this time with an extra transition from the start state back to the start state.
This graph represent’s what’s known as a “non-deterministic finite automata” (NFA). The “non-deterministic” part of it stems from that new transition we added from state 0 to state 0. Note that the transition is tagged as
., meaning it matches anything, and “anything” can include both
'a' and
'c', for which we already have transitions. That means if we’re in the start state and we read an
'a', we actually have two transitions we can take, one leading to node 1, and one leading back to node 0, which means after reading the
'a', we’re effectively in two nodes at the same time. A backtracking engine is often referred to as an NFA-based engine, as it’s logically walking the NFA graph, and when it comes to a point in the graph where it has to make a choice, it tries one choice, and if that ends up not matching, “backtracks” to the last choice it made, and goes a different way. As noted, this can result in exponential worst case processing time for some expressions.
But there are other ways to process an NFA. For example, rather than just considering ourselves in one node at a time, we can maintain a “current state” that’s the set of all nodes we’re currently “in”. For each character in the input we read, we enumerate all the states in our set, and for each, find all the new nodes we could transition to, creating our new set. This leads to
O(n * m^2) worst-case processing time, where
m is the number of nodes in the graph, and if you consider the pattern to be fixed and the only thing that’s dynamic is the input, then the size of the graph is constant, and this becomes
O(n) worst-case processing time. For example, given the input
"aaabc", we’d:
- Begin at the start state, such that our state set contains only that starting node: [0].
- Read
'a', find two transitions to nodes 0 and 1, yielding the new state set: [0, 1].
- Read
'a'again. From node 0, we again have two transitions to nodes 0 and 1, and from node 1, there’s no transition for
'a'. This again yields: [0, 1].
- Read
'a'again. And again, we end up with [0, 1].
- Read
'b'. There’s only one transition from node 0 back to itself, and there’s only one transition from node 1 for
'b'to node 2, yielding the new state set: [0, 2].
- Read
'c'. There’s now two transitions from node 0, one back to itself and one to node 3, and there’s one transition from node 2 to node 4: [0, 3, 4].
- Our state set includes the final state 4, so we’re done with a match.
There’s another form of finite automata, however, and that’s a “deterministic finite automata” (DFA). The key difference between a DFA and an NFA is the DFA is guaranteed to only have a single transition out of a node for a given input (so whereas every DFA is an NFA, not every NFA is a DFA). That makes a DFA really valuable for a regex engine, because it means the engine simply needs to make a single walk through the input (at least to determine whether there is a match): read the next character, transition to the next node, read the next character, transition to the next node, and on and on until either a final state is found (match) or it dead-ends, unable to transition out of the current node for the next input character (no match). This leads to
O(n) worst-case processing time. The graph, however, is considerably more complex:
Notice how there are many more distinct transitions in this graph, to account for the fact that there’s only one possible transition out of a node for a given input, e.g. there are three transitions out of node 0, one for an
'a', one for a
'c', and one for everything other than
'a' or
'c'. Additionally, for any given state in the graph, we don’t have a lot of information about where we came from and what path we took to get there. That means a regex engine using this approach can employ such a graph to determine whether there is a match, but it then needs to do additional work to determine, for example, where the match starts, or the values of any subcaptures that might be in the pattern. Further, while every NFA can be transformed into a DFA, for an NFA with
n nodes you can actually end up with a DFA with
O(2^n) nodes. This leads most regex engines that use finite automata, like Google’s RE2 and Rust’s regex crate, to employ multiple strategies, for example starting out with a DFA that’s lazily computed (only adding nodes to the graph as they’re needed) and then falling back to an NFA-based model if the DFA-based model gets too large.
In .NET 7, developers using
Regex now also have a choice to pick such an automata-based engine, using the new
RegexOptions.NonBacktracking options flag, with an implementation grounded in the Symbolic Regex Matcher work from Microsoft Research (MSR). Going back to my previous catastrophic backtracking example, we can change the constructor call from:
var r = new Regex($@"^(\w\d|\d\w){{{i}}}$");
to
var r = new Regex($@"^(\w\d|\d\w){{{i}}}$", RegexOptions.NonBacktracking);
and now run the program again. Don’t bother going to get a cup of coffee this time. On my machine, I see numbers like this:
10: 0.10ms 11: 0.11ms 12: 0.10ms 13: 0.09ms 14: 0.09ms 15: 0.10ms 16: 0.10ms 17: 0.10ms 18: 0.12ms 19: 0.12ms 20: 0.13ms 21: 0.12ms 22: 0.13ms 23: 0.14ms 24: 0.14ms 25: 0.14ms 26: 0.15ms 27: 0.15ms 28: 0.17ms 29: 0.17ms 30: 0.17ms
The processing is now effectively linear in the length of the (short) input. And, actually, most of the cost here is in building the graph, which is done lazily as the implementation walks the graph and discovers it needs to transition to a node in the graph that hasn’t been computed yet (the implementation starts with a DFA, building out the nodes lazily, and at some point if the graph gets too big, it switches over dynamically to NFA-based processing, such that the graph then only grows linearly with the size of the pattern). If I subtly change the original program from doing:
sw.Restart(); r.IsMatch(input); sw.Stop();
to instead doing:
r.IsMatch(input); // warm-up sw.Restart(); r.IsMatch(input); sw.Stop();
I then get numbers like these:
10: 0.00ms 11: 0.01ms 12: 0.00ms 13: 0.00ms 14: 0.00ms 15: 0.00ms 16: 0.01ms 17: 0.00ms 18: 0.00ms 19: 0.00ms 20: 0.00ms 21: 0.00ms 22: 0.01ms 23: 0.00ms 24: 0.00ms 25: 0.00ms 26: 0.00ms 27: 0.00ms 28: 0.00ms 29: 0.00ms 30: 0.00ms
With the graph fully computed already, we’re now seeing just the costs associated with execution, and it’s fast.
The new
RegexOptions.NonBacktracking option doesn’t support everything the other built-in engines support. In particular, the option can’t be used in conjunction with
RegexOptions.RightToLeft or
RegexOptions.ECMAScript, and it doesn’t allow for the following constructs in the pattern:
Some of these restrictions are fairly fundamental to the implementation, while some of them could be relaxed in time should there be sufficient demand.
RegexOptions.NonBacktracking also has a subtle difference with regards to execution. .NET’s
Regex has historically been unique amongst popular regex engines with regards to its behavior around captures. If a capture group is in a loop, most engines only provide the last matched value for that capture, but .NET’s
Regex supports the notion of tracking all values a capture group inside a loop captured, and providing access to all of them. As of now, the new
RegexOptions.NonBacktracking only supports providing the last, as do most other regex implementations. For example, this code:
using System.Text.RegularExpressions; foreach (RegexOptions option in new[] { RegexOptions.None, RegexOptions.NonBacktracking }) { Console.WriteLine($"RegexOptions.{option}"); Console.WriteLine("----------------------------"); Match m = Regex.Match("a123b456c", @"a(\w)*b(\w)*c", option); foreach (Group g in m.Groups) { Console.WriteLine($"Group: {g}"); foreach (Capture c in g.Captures) { Console.WriteLine($"\tCapture: {c}"); } } Console.WriteLine(); }
outputs:
RegexOptions.None ---------------------------- Group: a123b456c Capture: a123b456c Group: 3 Capture: 1 Capture: 2 Capture: 3 Group: 6 Capture: 4 Capture: 5 Capture: 6 RegexOptions.NonBacktracking ---------------------------- Group: a123b456c Capture: a123b456c Group: 3 Capture: 3 Group: 6 Capture: 6
Beyond that, most anything you do today with
Regex you can do with
RegexOptions.NonBacktracking. Note that the goal of
NonBacktracking is not to be always faster than the backtracking engines. In fact, one of the reasons backtracking engines are so popular is they can be extremely fast in the best and even expected cases, and the .NET backtracking engines have been optimized with even more tricks and vectorization in .NET 7 to make them even faster than before in the best and typical use cases (I’ll discuss vectorization in more depth later in the post).
NonBacktracking‘s bread-and-butter is to be fast (but not necessarily the fastest) for all cases, especially worst-case. Here’s an example to try to drive that home.
private Regex _backtracking = new Regex("a.*b", RegexOptions.Singleline | RegexOptions.Compiled); private Regex _nonBacktracking = new Regex("a.*b", RegexOptions.Singleline | RegexOptions.NonBacktracking); private string _input; [Params(1, 2)] public int Input { get; set; } [GlobalSetup] public void Setup() { _input = new string('a', 1000); if (Input == 1) { _input += "b"; } } [Benchmark] public bool Backtracking() => _backtracking.IsMatch(_input); [Benchmark(Baseline = true)] public bool NonBacktracking() => _nonBacktracking.IsMatch(_input);
Here we’re matching the expression
a.*b against an input of one thousand
'a's followed by a
'b'. The backtracking engine implements that essentially by doing an
IndexOf('a') to find the first place to try to match. Then as part of the match, it’ll compare the
'a', then jump to the end of the input (since
.* with
RegexOptions.Singleline matches everything), then
LastIndexOf('b'), and will declare success. In contrast, the non-backtracking engine will read a character in the input, look in a transition table to determine the next node to transition to, move to that node, and will rinse and repeat until it finds a match. So in one case, we’re effectively doing fractional amounts of instructions per character (thanks to the vectorization), and in the other, we’re executing multiple instructions per character. The impact of that is evident in the resulting benchmark numbers:
For this input, the backtracking engine did effectively zero backtracking and was ~128x faster than the non-backtracking engine. But, now consider the second input, which is a thousand
'a's without a following
'b', such that it doesn’t match. The strategy employed by the non-backtracking engine will be exactly the same: read a character, transition to the next node, read a character, transition to the next node, and so on. But the backtracking engine will end up having to do much more work. It’ll start off the same way, doing an
IndexOf('a') to find the next place to match, jumping to the end of the input, and doing a
LastIndexOf('b')… but this time it won’t find one, so it’ll declare failure to match at position 0. It’ll then bump to position 1 and try again, finding the next
'a' at position 1, jumping to the end of the input, doing a
LastIndexOf('b'), and not finding one. And it’ll bump again. And again. The result is it’ll end up doing
O(n^2) work, and even though it’s vectorizing some of those operations, it’s still much more work, which again shows up in the numbers:
With the same pattern and just a different input, now the backtracking engine is ~8x slower than the non-backtracking engine rather than being ~128x faster. And importantly, the time the non-backtracking engine took is almost exactly the same with both inputs. Which is the whole point.
StringSyntaxAttribute.Regex
For developers using
Regex, Visual Studio has a really nice feature that provides syntax colorization, syntax validation, and regex IntelliSense when working with regular expressions.
Historically, Visual Studio contained a hardcoded list of methods where it knew the arguments to those methods would be regular expressions. This isn’t scalable, however, with this treatment only afforded to
Regex‘s constructors and static methods. This isn’t an issue unique to regular expressions, of course. There are many APIs that accept strings that need to adhere to specific syntaxes, for example passing JSON content into a method, or passing a
DateTime format string into a
ToString call, or any number of other domain-specific languages, and it’s not feasible for every tool that could meaningfully improve the developer experience around those APIs to hardcode the list of every possible API known to accept that syntax (nor to come up with heuristics for them).
Instead, .NET 7 introduces the new
[StringSyntax(...)] attribute, which is used in .NET 7 on more than 350
string,
string[], and
ReadOnlySpan<char> parameters, properties, and fields to highlight to an interested tool what kind of syntax is expected to be passed or set. Now, any method that wants to indicate a string parameter accepts a regular expression can attribute it, e.g.
void MyCoolMethod([StringSyntax(StringSyntaxAttribute.Regex)] string expression), and Visual Studio 2022 will provide the same syntax validation, syntax coloring, and IntelliSense that it provides for all the other
Regex-related methods. For example, the
WebProxy class provides a constructor that accepts an array of regex strings to be used as proxy bypasses; this
string[] parameter is attributed in .NET 7 as
[StringSyntax(StringSyntaxAttribute.Regex)], a fact that’s visible when using it in Visual Studio 2022:
String parameters, properties, and fields throughout the core .NET libraries now have been attributed to say whether they’re regular expressions, JSON, XML, composite format strings, URLs, numeric format strings, and on and on.
Case-insensitive matching (and
RegexOptions.IgnoreCase)
It’s common with regular expressions to want to tell the engine to perform the match in a case-insensitive way. For example, you might write the pattern
[a-z0-9] in order to match an ASCII letter or digit, but you also want the uppercase values to be included. To achieve that, most modern regex engines have support for the
(?i) inline syntax which, when included in the pattern, tells the engine that everything after that token in its current subexpression should be treated in a case-insensitive manner. Thus:
(?i)[a-z0-9]is equivalent to
[A-Za-z0-9]
(?i)[abc]d*efgis equivalent to
[AaBbCc][Dd]*[Ee][Ff][Gg]
(?i)abc|defis equivalent to
[Aa][Bb][Cc]|def
abc|(?i)defis equivalent to
abc|[Dd][Ee][Ff]
(?i)(abc|def)is equivalent to
([Aa][Bb][Cc]|[Dd][Ee][Ff])
.NET has long supported this inline syntax, but it’s also supported the
RegexOptions.IgnoreCase option, which is equivalent to applying
(?i), and thus case-insensitivity, to the whole pattern. .NET has also supported the
RegexOptions.InvariantCulture option, which is only relevant when
RegexOptions.IgnoreCase or
(?i) is used and which changes exactly what values are considered case-equivalent.
In every version of .NET prior to .NET 7, this case-insensivity support is implemented via
ToLower. When the
Regex is constructed, the pattern is transformed such that every character in the pattern is lowercased, and then at match time, each time an input character is compared to something in the pattern, the input character is also
ToLower‘d, and the lowercased values are compared. This support is functional, but there are some significant downsides to this implementation approach.
- Culture changes. By default, the “current” culture is used to perform the lowercasing, e.g.
CultureInfo.CurrentCulture.TextInfo.ToLower(c), and that’s relevant because culture impacts how characters change case. One of the most famous examples of this is the “Turkish i”. If you run
(int)new CultureInfo("en-US").TextInfo.ToLower('I'), that will produce the value
105, the numerical value for the ASCII lowercase ‘i’, known in Unicode as “LATIN SMALL LETTER I”. If, however, you run the exact same code but changing the name of the culture to “tr-TR”, as in
(int)new CultureInfo("tr-TR").TextInfo.ToLower('I'), that code will now produce the value
305, otherwise known in Unicode as the “LATIN SMALL LETTER DOTLESS I”. So culture matters (specifying
RegexOptions.InvariantCulturesimply serves to make the implementation use
CultureInfo.InvariantCultureinstead of
CultureInfo.CurrentCulture). But there’s a functional issue here. I mentioned that the pattern is lowercased at construction time and the input is lowercased at match time, and that the current culture is used to perform that lowercasing… what happens if the culture changes between when the pattern is constructed and the input is matched? Nothing good. You then end up with inconsistencies, trying to compare one character lowercased according to one culture’s rules against another character lowercased according to another culture’s rules.
using System.Globalization; using System.Text.RegularExpressions; CultureInfo.CurrentCulture = new CultureInfo("tr-TR"); var r = new Regex("İ", RegexOptions.IgnoreCase); // "construction time" ... // some other code CultureInfo.CurrentCulture = new CultureInfo("en-US"); Console.WriteLine(r.IsMatch("I")); // "match time"
- ToLower overhead.
ToLowerisn't super expensive, but it's also not free. Having to call
ToLoweron every character in order to process it means a comparatively high cost to processing each value. This overhead was decreased in previous versions of .NET, for example changing the code generated by
RegexOptions.Compiledto cache the culture information so that rather than emitting the equivalent of
CultureInfo.CurrentCulture.TextInfo.ToLower(c)on each comparison, it instead output
_textInfo.ToLower(c). But even with such optimizations, this still contributes meaningfully to the gap in performance between case-sensitive and case-insensitive matching. Consider this example:);
In theory, these two expressions should be identical, and functionally they are. But in the first case, with the set, in .NET 6 the compiled implementation will use code along the lines of
(c == 'A') | (c == 'a')to match
[Aa], whereas with the
IgnoreCaseversion, in .NET 6 the compiled implementation will use code along the lines of
_textInfo.ToLower(c) == 'a', such that on my machine I get results like this from the microbenchmark:
For two expressions that should be identical, ~3x is a sizeable difference, and it's all because of
ToLower.
- Vectorization. There are two primary ways regular expressions end up being used: to validate whether some text fully matches a pattern, or to find occurrences of the pattern within some larger text. For the latter, it's critically important for performance to move as quickly as possible through the portions of text that can't possibly match in order to only spend more resources on the portions that might possibly match. The more comparisons that can be elided or done concurrently, the better off we are. And that's where vectorization comes into play. Vectorization is the approach of taking advantage of hardware instructions that support doing multiple things at the same time. Consider if I have 4 bytes and I want to compare all 4 of them to see if they're each 0xFF. I could write a for loop that walks each byte and compares each of the 4 against 0xFF, or I could treat the 4 contiguous bytes as if they were a 32-bit integer and just compare all 4 at the same time against 0xFFFFFFFF. Doing so will end up being ~4x faster. In a 64-bit process, I could do the same with 8 bytes, comparing against 0xFFFFFFFFFFFFFFFF, and it'd be ~8x faster. And modern hardware offers specialized instruction sets that support performing operations like this on 16, 32, or even 64 bytes at a time, and not just comparisons, but other more complicated operations as well. .NET exposes APIs for these "intrinsics", and exposes higher-level "vector" types like
Vector<T>,
Vector128<T>, and
Vector256<T>that make targeting these instructions easier, but the core libraries also use all of this support internally to vectorize operations like
IndexOf. That way, a developer can just use
IndexOfto perform their search and gain the full benefits of vectorization without having to manually write that vectorization code by hand. In .NET 5,
Regexgot in on this vectorization game by trying to use
IndexOfand
IndexOfAnyto find the next location a pattern may match, if possible. But now consider this slightly tweaked version of the previously shown benchmark:);
Here we're searching a string of mostly
'z's that ends with
"AaAa"against the pattern
[Aa]+or the
IgnoreCasepattern
a+. With the former, the implementation in .NET 6 could use
IndexOfAny('A', 'a')to find the next possible start of a match, but because the case-insensitive implementation for
IgnoreCaseneeds to call
ToLoweron every character, that implementation is forced to walk character by character through the input rather than vectorizing to process it in batches. The difference is stark:
All of these issues have led us to entirely reconsider how
RegexOptions.IgnoreCase is handled. In .NET 7, we no longer implement
RegexOptions.IgnoreCase by calling
ToLower on each character in the pattern and each character in the input. Instead, all casing-related work is done when the
Regex is constructed.
Regex now uses a casing table to essentially answer the question "given the character
'c', what are all of the other characters it should be considered equivalent to under the selected culture?" So for example, in my current culture:
- Given the character
'a', it'll be determined to also be equivalent to
'A'.
- Given the "GREEK CAPITAL LETTER OMEGA" (
'u03A9'), it'll be determined to also be equivalent to the "GREEK SMALL LETTER OMEGA" (
'u03C9'), and the "OHM SIGN" (
'u2126').
From that, the implementation throws away the original
IgnoreCase character and replaces it instead with a non-
IgnoreCase set composed of all the equivalent characters. So, for example, given the pattern
(?i)abcd, it'll replace that with
[Aa][Bb][Cc][Dd]. This solves all three of the problems previously outlined:
- Culture changes. The only culture that matters is the one at the time of construction, since that's when the pattern is being transformed.
- ToLower overhead.
ToLoweris no longer being used, so its overhead doesn't matter.
- Vectorization. We now have sets of known characters we can search for with methods like
IndexOfAny.
Now with .NET 7, I can run these benchmarks again:);
and we can see that the difference between the expressions has disappeared, since the
IgnoreCase variants are being transformed to be identical to their counterparts.
It's also interesting to note that the first benchmark not only trippled in throughput to match the set-based expression, they both then further doubled in throughput, dropping from ~86us on .NET 6 to ~47us on .NET 7. More on that in a bit.
Now, several times I've stated that this eliminates the need for casing at match time. That's ~99.5% true. In almost every regex construct, the input text is compared against the pattern text, which we can compute
IgnoreCase sets for at construction. Great. There is, however, a single construct which compares input text against input text: backreferences. Imagine I had the pattern
"(?i)(\w\w\w)1". What happens when we try to match this against input text like
"ABCabc". The engine will successfully match the
"ABC" against the
\w\w\w, storing that as the first capture, but the
\1 backreference is itself
IgnoreCase, which means it's now case-insensitively comparing the next three characters of the input against the already matched input
"ABC", and it needs to somehow determine whether
"ABC" is case-equivalent to
"abc". Prior to .NET 7, it would just use
ToLower on both, but we've moved away from that. So for
IgnoreCase backreferences, not only will the casing tables be consulted at construction time, they'll also be used at match time. Thankfully, use of case-insensitive backreferences is fairly rare. In an open-source corpus of ~19,000 regular expressions gathered from appropriately-licensed nuget packages, only ~0.5% include a case-insensitive backreference.
Source Generation
When you write
new Regex("somepattern"), a few things happen. The specified pattern is parsed, both to ensure validity of the pattern and to transform it it into an internal
RegexNode tree that represents the parsed regex. The tree is then optimized in various ways, transforming the pattern into a variation that's functionally equivalent but that can be more efficiently executed, and then that tree is written into a form that can be interpreted, a series of opcodes and operands that provide instructions to the internal
RegexInterpreter engine on how to match. When a match is performed, the interpreter simply walks through those instructions, processing them against the input text. When instantiating a new
Regex instance or calling one of the static methods on
Regex, the interpreter is the default engine employed; we already saw how the new
RegexOptions.NonBacktracking can be used to opt-in to the new non-backtracking engine, and
RegexOptions.Compiled can be used to opt-in to a compilation-based engine.
When you specify
RegexOptions.Compiled, prior to .NET 7, all of the same construction-time work would be performed. Then, the resulting instructions would be transformed further by the reflection-emit-based compiler into IL instructions that would be written to a few
DynamicMethods. When a match was performed, those
DynamicMethods would be invoked. This IL would essentially do exactly what the interpreter would do, except specialized for the exact pattern being processed. So for example, if the pattern contained
[ac], the interpreter would see an opcode that essentially said "match the input character at the current position against the set specified in this set description" whereas the compiled IL would contain code that effectively said "match the input character at the current position against
'a' or
'c'". This special-casing and the ability to perform optimizations based on knowledge of the pattern are some of the main reasons specifying
RegexOptions.Compiled yields much faster matching throughput than does the interpreter.
There are, however, several downsides to
RegexOptions.Compiled. Most impactfully, it involves much more construction cost than does using the interpreter. Not only are all of the same costs paid as for the interpreter, but it then needs to compile that resulting
RegexNode tree and generated opcodes/operands into IL, which adds non-trivial expense. And that generated IL further needs to be JIT-compiled on first use leading to even more expense at startup.
RegexOptions.Compiled represents a fundamental tradeoff between overheads on first use and overheads on every subsequent use. The use of reflection emit also inhibits the use of
RegexOptions.Compiled in certain environments; some operating systems don't permit dynamically generated code to be executed, and on such systems,
Compiled will become a nop.
To help with these issues, the .NET Framework provides a method
Regex.CompileToAssembly. This method enables the same IL that would have been generated for
RegexOptions.Compiled to instead be written to a generated assembly on disk, and that assembly can then be referenced as a library from your app. This has the benefits of avoiding the startup overheads involved in parsing, optimizing, and outputting the IL for the expression, as that can all be done ahead of time rather than each time the app is invoked. Further, that assembly could be ahead-of-time compiled with a technology like ngen / crossgen, avoiding most of the associated JIT costs as well.
Regex.CompileToAssembly itself has problems, however. First, it was never particularly user friendly. The ergonomics of having to have a utility that would call
CompileToAssembly in order to produce an assembly your app would reference resulted in relatively little use of this otherwise valuable feature. And on .NET Core,
CompileToAssembly has never been supported, as it requires the ability to save reflection-emit code to assemblies on disk, which also isn't supported.
.NET 7 addresses all of this with the new
RegexGenerator source generator. The original compiler for C# was implemented in C/C++. A decade ago, in the grand tradition of compilers being implemented in the language they compile, the "Roslyn" C# compiler was implemented in C#. As part of this, it exposed object models for the entire compilation pipeline, with APIs the compiler itself uses to parse and understand C# but that are also exposed for arbitrary code to use to do the same. It then also enabled components that could plug into the compiler itself, with the compiler handing these "analyzers" all of the information the compiler had built up about the code being compiled and allowing the analyzers to inspect the data and issue additional "diagnostics" (e.g. warnings). More recently, Roslyn also enabled source generators. Just like an analyzer, a source generator is a component that plugs into the compiler and is handed all of the same information as an analyzer, but in addition to being able to emit diagnostics, it can also augment the compilation unit with additional source code. The .NET 7 SDK includes a new source generator which recognizes use of the new
RegexGeneratorAttribute on a partial method that returns
Regex, and provides an implementation of that method which implements on your behalf all the logic for the
Regex. For example, if previously you would have written:
private static readonly Regex s_myCoolRegex = new Regex("abc|def", RegexOptions.Compiled | RegexOptions.IgnoreCase); ... if (s_myCoolRegex.IsMatch(text) { ... }
you can now write that as:
[RegexGenerator("abc|def", RegexOptions.IgnoreCase)] private static partial Regex MyCoolRegex(); ... if (MyCoolRegex().IsMatch(text) { ... }
The generated implementation of
MyCoolRegex() similarly caches a singleton
Regex instance, so no additional caching is needed in consuming code.
But as can be seen, it's not just doing
new Regex(...). Rather, the source generator is emitting as C# code a custom
Regex-derived implementation with logic akin to what
RegexOptions.Compiled emits in IL. You get all the throughput performance benefits of
RegexOptions.Compiled (more, in fact) and the start-up benefits of
Regex.CompileToAssembly, but without the complexity of
CompileToAssembly. The source that's emitted is part of your project, which means it's also easily viewable and debuggable.
You can set breakpoints in it, you can step through it, and you can use it as a learning tool to understand exactly how the regex engine is processing your pattern and your input. The generator even spits out XML comments in order to help make the expression understandable at a glance at the usage site.
The initial creation of the source generator was a straight port of the
RegexCompiler used internally to implement
RegexOptions.Compiled; line-for-line, it would essentially just emit a C# version of the IL that was being emitted. Let's take a simple example:
[RegexGenerator(@"(a|bc)d")] public static partial Regex Example();
Here's what the initial incarnation of the source generator emitted for the core matching routine:
protected override void Go() { string runtext = base.runtext!; int runtextbeg = base.runtextbeg; int runtextend = base.runtextend; int runtextpos = base.runtextpos; int[] runtrack = base.runtrack!; int runtrackpos = base.runtrackpos; int[] runstack = base.runstack!; int runstackpos = base.runstackpos; int tmp1, tmp2, ch; // 000000 *Lazybranch addr = 20 L0: runtrack[--runtrackpos] = runtextpos; runtrack[--runtrackpos] = 0; // 000002 *Setmark L1: runstack[--runstackpos] = runtextpos; runtrack[--runtrackpos] = 1; // 000003 *Setmark L2: runstack[--runstackpos] = runtextpos; runtrack[--runtrackpos] = 1; // 000004 *Lazybranch addr = 10 L3: runtrack[--runtrackpos] = runtextpos; runtrack[--runtrackpos] = 2; // 000006 One 'a' L4: if (runtextpos >= runtextend || runtext[runtextpos++] != 97) { goto Backtrack; } // 000008 *Goto addr = 12 L5: goto L7; // 000010 Multi "bc" L6: if (runtextend - runtextpos < 2 || runtext[runtextpos] != 'b' || runtext[runtextpos + 1] != 'c') { goto Backtrack; } runtextpos += 2; // 000012 *Capturemark index = 1 L7: tmp1 = runstack[runstackpos++]; base.Capture(1, tmp1, runtextpos); runtrack[--runtrackpos] = tmp1; runtrack[--runtrackpos] = 3; // 000015 One 'd' L8: if (runtextpos >= runtextend || runtext[runtextpos++] != 100) { goto Backtrack; } // 000017 *Capturemark index = 0 L9: tmp1 = runstack[runstackpos++]; base.Capture(0, tmp1, runtextpos); runtrack[--runtrackpos] = tmp1; runtrack[--runtrackpos] = 3; // 000020 Stop L10: base.runtextpos = runtextpos; return; Backtrack: int limit = base.runtrackcount * 4; if (runstackpos < limit) { base.runstackpos = runstackpos; base.DoubleStack(); // might change runstackpos and runstack runstackpos = base.runstackpos; runstack = base.runstack!; } if (runtrackpos < limit) { base.runtrackpos = runtrackpos; base.DoubleTrack(); // might change runtrackpos and runtrack runtrackpos = base.runtrackpos; runtrack = base.runtrack!; } switch (runtrack[runtrackpos++]) { case 0: { // 000000 *Lazybranch addr = 20 runtextpos = runtrack[runtrackpos++]; goto L10; } case 1: { // 000002 *Setmark runstackpos++; goto Backtrack; } case 2: { // 000004 *Lazybranch addr = 10 runtextpos = runtrack[runtrackpos++]; goto L6; } case 3: { // 000012 *Capturemark index = 1 runstack[--runstackpos] = runtrack[runtrackpos++]; base.Uncapture(); goto Backtrack; } default: { global::System.Diagnostics.Debug.Fail($"Unexpected backtracking state {runtrack[runtrackpos - 1]}"); break; } } }
That's... intense. But it's the equivalent of what
RegexCompiler was producing, essentially walking through the operators/operands created for the interpreter and emitting code for each. There are multiple issues with this. First, it's mostly unintelligible. If one of the goals of the source generator is to emit debuggable code, this largely fails at that goal, as even for someone deeply knowledgable about regular expressions, this isn't going to be very meaningful. Second, there are performance issues; for example, every operation involves pushing and popping state from a "runstack". And third, this loses out on additional possible optimizations, such as being able to use vectorized operations as part of handling specific constructs in the pattern; with this lowered opcode/operand representation, we lose much of the information that could enable the compiler or source generator to add useful improvements based on knowledge of the initial tree.
As such, for .NET 7, after this initial incarnation of the source generator, both the source generator and
RegexCompiler were almost entirely rewritten, fundamentally changing the structure of the generated code. In .NET 5, we experimented with an alternative approach, and for simple patterns that didn't involve any backtracking, the
RegexCompiler could emit code that was much cleaner, the primary goal being performance. That approach has now been extended to handle all constructs (with one caveat), and both
RegexCompiler and the source generator still mapping mostly 1:1 with each other, following the new approach.
Now, here's what the source generator outputs for that same method (which has been renamed) today:
private bool TryMatchAtCurrentPosition(ReadOnlySpan<char> inputSpan) { int pos = base.runtextpos; int matchStart = pos; int capture_starting_pos = 0; ReadOnlySpan<char> slice = inputSpan.Slice(pos); // 1st capture group. { capture_starting_pos = pos; // Match with 2 alternative expressions. { if (slice.IsEmpty) { UncaptureUntil(0); return false; // The input didn't match. } switch (slice[0]) { case 'a': pos++; slice = inputSpan.Slice(pos); break; case 'b': // Match 'c'. if ((uint)slice.Length < 2 || slice[1] != 'c') { UncaptureUntil(0); return false; // The input didn't match. } pos += 2; slice = inputSpan.Slice(pos); break; default: UncaptureUntil(0); return false; // The input didn't match. } } base.Capture(1, capture_starting_pos, pos); } // Match 'd'. if (slice.IsEmpty || slice[0] != 'd') { UncaptureUntil(0); return false; // The input didn't match. } // The input matched. pos++; base.runtextpos = pos; base.Capture(0, matchStart, pos); return true; }
That's a whole lot more understandable, with a much more followable structure, with comments explaining what's being done at each step, and in general with code emitted under the guiding principle that we want the generator to emit code as if a human had written it. Even when backtracking is involved, the structure of the backtracking gets baked into the structure of the code, rather than relying on a stack to indicate where to jump next. For example, here's the code for the same generated matching function when the expression is
[ab]*[bc]:
private bool TryMatchAtCurrentPosition(ReadOnlySpan<char> inputSpan) { int pos = base.runtextpos; int matchStart = pos; int charloop_starting_pos = 0, charloop_ending_pos = 0; ReadOnlySpan<char> slice = inputSpan.Slice(pos); // Match a character in the set [ab] greedily any number of times. //{ charloop_starting_pos = pos; int iteration = 0; while ((uint)iteration < (uint)slice.Length && (((uint)slice[iteration]) - 'a' <= (uint)('b' - 'a'))) { iteration++; } slice = slice.Slice(iteration); pos += iteration; charloop_ending_pos = pos; goto CharLoopEnd; CharLoopBacktrack: if (Utilities.s_hasTimeout) { base.CheckTimeout(); } if (charloop_starting_pos >= charloop_ending_pos || (charloop_ending_pos = inputSpan.Slice(charloop_starting_pos, charloop_ending_pos - charloop_starting_pos).LastIndexOfAny('b', 'c')) < 0) { return false; // The input didn't match. } charloop_ending_pos += charloop_starting_pos; pos = charloop_ending_pos; slice = inputSpan.Slice(pos); CharLoopEnd: //} // Advance the next matching position. if (base.runtextpos < pos) { base.runtextpos = pos; } // Match a character in the set [bc]. if (slice.IsEmpty || (((uint)slice[0]) - 'b' > (uint)('c' - 'b'))) { goto CharLoopBacktrack; } // The input matched. pos++; base.runtextpos = pos; base.Capture(0, matchStart, pos); return true; }
You can see the structure of the backtracking in the code, with a
CharLoopBacktrack label emitted for where to backtrack to and a
goto used to jump to that location when a subsequent portion of the regex fails.
If you look at the code implementing
RegexCompiler and the source generator, they will look extremely similar: similarly named methods, similar call structure, even similar comments throughout the implementation. For the most part, they spit identical code, albeit one in IL and one in C#. Of course, the C# compiler is then responsible for translating the C# into IL, so the resulting IL in both cases likely won't be identical. In fact, the source generator relies on that in various cases, taking advantage of the fact that the C# compiler will further optimize various C# constructs. There are a few specific things the source generator will thus produce more optimized matching code for than does
RegexCompiler. For example, in one of the previous examples, you can see the source generator emitting a switch statement, with one branch for
'a' and another branch for
'b'. Because the C# compiler is very good at optimizing switch statements, with multiple strategies at its disposal for how to do so efficiently, the source generator has a special optimization that
RegexCompiler does not. For alternations, the source generator looks at all of the branches, and if it can prove that every branch begins with a different starting character, it will emit a switch statement over that first character and avoid outputting any backtracking code for that alternation (since if every branch has a different starting first character, once we enter the case for that branch, we know no other branch could possibly match).
Here's a slightly more complicated example of that. In .NET 7, alternations are more heavily analyzed to determine whether it's possible to refactor them in a way that will make them more easily optimized by the backtracking engines and that will lead to simpler source-generated code. One such optimization supports extracting common prefixes from branches, and if the alternation is atomic such that ordering doesn't matter, reordering branches to allow for more such extraction. We can see the impact of that for a weekday pattern
Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday, which produces a matching function like this:
private bool TryMatchAtCurrentPosition(ReadOnlySpan<char> inputSpan) { int pos = base.runtextpos; int matchStart = pos; ReadOnlySpan<char> slice = inputSpan.Slice(pos); // Match with 5 alternative expressions, atomically. { if (slice.IsEmpty) { return false; // The input didn't match. } switch (slice[0]) { case 'M': // Match the string "onday". if (!slice.Slice(1).StartsWith("onday")) { return false; // The input didn't match. } pos += 6; slice = inputSpan.Slice(pos); break; case 'T': // Match with 2 alternative expressions, atomically. { if ((uint)slice.Length < 2) { return false; // The input didn't match. } switch (slice[1]) { case 'u': // Match the string "esday". if (!slice.Slice(2).StartsWith("esday")) { return false; // The input didn't match. } pos += 7; slice = inputSpan.Slice(pos); break; case 'h': // Match the string "ursday". if (!slice.Slice(2).StartsWith("ursday")) { return false; // The input didn't match. } pos += 8; slice = inputSpan.Slice(pos); break; default: return false; // The input didn't match. } } break; case 'W': // Match the string "ednesday". if (!slice.Slice(1).StartsWith("ednesday")) { return false; // The input didn't match. } pos += 9; slice = inputSpan.Slice(pos); break; case 'F': // Match the string "riday". if (!slice.Slice(1).StartsWith("riday")) { return false; // The input didn't match. } pos += 6; slice = inputSpan.Slice(pos); break; case 'S': // Match with 2 alternative expressions, atomically. { if ((uint)slice.Length < 2) { return false; // The input didn't match. } switch (slice[1]) { case 'a': // Match the string "turday". if (!slice.Slice(2).StartsWith("turday")) { return false; // The input didn't match. } pos += 8; slice = inputSpan.Slice(pos); break; case 'u': // Match the string "nday". if (!slice.Slice(2).StartsWith("nday")) { return false; // The input didn't match. } pos += 6; slice = inputSpan.Slice(pos); break; default: return false; // The input didn't match. } } break; default: return false; // The input didn't match. } } // The input matched. base.runtextpos = pos; base.Capture(0, matchStart, pos); return true; }
Note how
Thursday was reordered to be just after
Tuesday, and how for both the
Tuesday/
Thursday pair and the
Saturday/
Sunday pair, we end up with multiple levels of switches. In the extreme, if you were to create a long alternation of many different words, the source generator would end up emitting the logical equivalent of a trie, reading each character and
switch'ing to the branch for handling the remainder of the word.
At the same time, the source generator has other issues to contend with that simply don't exist when outputting to IL directly. If you look a couple of code examples back, you can see some braces somewhat strangely commented out. That's not a mistake. The source generator is recognizing that, if those braces weren't commented out, the structure of the backtracking would be relying on jumping from outside of a scope to a label defined inside of that scope; such a label would not be visible to such a
goto and the code would fail to compile. Thus, the source generator needs to avoid there actually being a scope in the way. In some cases, it'll simply comment out the scope as was done here. In other cases where that's not possible, it may sometimes avoid constructs that require scopes (e.g. a multi-statement
if block) if doing so would be problematic.
The source generator handles everything
RegexCompiler handles, with one exception. Earlier in this post we discussed the new approach to handling
RegexOptions.IgnoreCase, how the implementations now use a casing table to generate sets at construction time, and how
IgnoreCase backreference matching needs to consult that casing table. That table is internal to
System.Text.RegularExpressions.dll, and for now at least, code external to that assembly (including code emitted by the source generator) does not have access to it. That makes handling
IgnoreCase backreferences a challenge in the source generator. We could choose to also output the casing table if it's required, but it's quite a hefty chunk of data to blit into consuming assemblies. So at least for now,
IgnoreCase backreferences are the one construct not supported by the source generator that is supported by
RegexCompiler. If you try to use a pattern that has one of these (which, at least according to our research, are very rare), the source generator won't emit a custom implementation and will instead fall back to caching a regular
Regex instance:
Also, neither
RegexCompiler nor the source generator support the new
RegexOptions.NonBacktracking. If you specify
RegexOptions.Compiled | RegexOptions.NonBacktracking, the
Compiled flag will just be ignored, and if you specify
NonBacktracking to the source generator, it will similarly fall back to caching a regular
Regex instance. (It's possible the source generator will support
NonBacktracking as well in the future, but that's unlikely to happen for .NET 7.)
Finally, the $10 million dollar question: when should you use the source generator? The general guidance is, if you can use it, use it. If you're using
Regex today in C# with arguments known at compile-time, and especially if you're already using
RegexOptions.Compiled (because the regex has been identified as a hot spot that would benefit from faster throughput), you should prefer to use the source generator. The source generator will give your regex all the throughput benefits of
RegexOptions.Compiled, the startup benefits of not having to do all the regex parsing, analysis, and compilation at runtime, the option of using ahead-of-time compilation with the code generated for the regex, better debugability and understanding of the regex, and even the possibility to reduce the size of your trimmed app by trimming out large swaths of code associated with
RegexCompiler (and potentially even reflection emit itself). And even if used with an option like
RegexOptions.NonBacktracking for which it can't yet generate a custom implementation, it will still helpfully emit caching, XML comments describing the implementation, and so on, such that it's still valuable. The main downside of the source generator is that it is emitting additional code into your assembly, so there's the potential for increased size; the more regexes in your app and the larger they are, the more code will be emitted for them. In some situations, just as
RegexOptions.Compiled may be unnecessary, so too may be the source generator, e.g. if you have a regex that's needed only rarely and for which throughput doesn't matter, it could be more beneficial to just rely on the interpreter for that sporadic usage. However, we're so confident in the general "if you can use it, use it" guidance that .NET 7 will also include an analyzer that identifies use of
Regex that could be converted to the source generator, and a fixer that does the conversion for you:
Spans
Span<T> and
ReadOnlySpan<T> have fundamentally transformed how code gets written in .NET, especially in higher-performance scenarios. These types make it easy to implement a single algorithm that's able to process strings, arrays, slices of data, stack-allocated state, or native memory, all behind a fast, optimized veneer. Hundreds of methods in the core libraries now accept spans, and ever since spans were introduced in .NET Core 2.1, developers have been asking for span support in
Regex. This has been challenging to accomplish for two main reasons.
The first issue is
Regex's extensibility model. The aforementioned
Regex.CompileToAssembly generated a
Regex-derived type that needed to be able to plug its logic into the general scaffolding of the regex system, e.g. you call a method on the
Regex instance, like
IsMatch, and that needs to find its way into the code emitted by
CompileToAssembly. To achieve that,
System.Text.RegularExpressions exposes an abstract
RegexRunner type, which exposes a few abstract methods, most importantly
FindFirstChar and
Go. All of the engines plug into the execution via
RegexRunner: the internal
RegexInterpreter derives from
RegexRunner and overrides those methods to implement the regex by interpretering the opcodes/operands written during construction, the
NonBacktracking engine has a type that derives from
RegexRunner, and
RegexCompiler ends up creating delegates to
DynamicMethods it reflection emits and creates an instance of a type derived from
RegexRunner that will invoke those delegates. The source generator also emits code that plugs in the same way. The problem as it relates to span, though, is how to get the span into these methods.
RegexRunner is a class and can't store a span as a field, and these
FindFirstChar and
Go methods were long-since defined and don't accept a span as an argument. As such, with the shape of this model as it's been defined for nearly 20 years, there's no way to get a span into the code that would process it.
The second issue is around the API for returning results.
IsMatch is simple: it just returns a
bool. But
Match and
Matches are both based on returning objects that represent matches, and such objects can't hold a reference to a span. That's an issue, because the mechanism by which the current model supports iterating through results is lazy, with the first match being computed, and then using the resulting
Match's
NextMatch() method to pick up where the first operation left off. If that
Match can't store the input span, it can't provide it back to the engine for subsequent matching.
In .NET 7, we've tackled these issues, such that
Regex in .NET 7 now supports span inputs, at least with some of the APIs. Overloads of
IsMatch accept
ReadOnlySpan<char>, as do overloads of two new methods:
Count and
EnumerateMatches. This means you can now use the .NET
Regex type with data stored in a
char[], or data from a
char* passed via interop, or data from a
ReadOnlySpan<char> sliced from a
string, or from anywhere else you may have received a span.
The new
Count method takes a
string or a
ReadOnlySpan<char>, and returns an
int for how many matches exist in the input text; previously if you wanted to do this, you could have written code that iterated using
Match and
NextMatch(), but the built-in implementation is leaner and faster (and doesn't require you to have to write that out each time you need it, and works with spans). The performance benefits are obvious from a microbenchmark:
private Regex _r = new Regex("a", RegexOptions.Compiled); private string _input = new string('a', 1000); [Benchmark(Baseline = true)] public int Match() { int count = 0; Match m = _r.Match(_input); while (m.Success) { count++; m = m.NextMatch(); } return count; } [Benchmark] public int Count() => _r.Count(_input);
which on my machine yields results like this:
The more interesting method, though, is
EnumerateMatches.
EnumerateMatches accepts a
string or a
ReadOnlySpan<char> and returns a
ref struct enumerator that can store the input span and thus is able to lazily enumerate all the matches in the input.
using System.Text.RegularExpressions; ReadOnlySpan<char> text = "Shall I compare thee to a summer’s day"; foreach (ValueMatch m in Regex.EnumerateMatches(text, @"\b\w+\b")) { Console.WriteLine($"Word: {text.Slice(m.Index, m.Length)}"); }
One of the interesting things about both
Count and
EnumerateMatches (and the existing
Replace when not employing backreferences in the replacement pattern) is that they can be much more efficient than
Match or
Matches in terms of the work required for an engine. In particular, the
NonBacktracking engine is implemented in a fairly pay-for-play manner: the less information you need, the less work it has to do. So with
IsMatch only requiring the engine to compute whether there exists a match,
NonBacktracking can get away with doing much less work than for
Match, where it needs to compute the exact offset and length of the match and also compute all of the subcaptures. Neither
Count nor
EnumerateMatches requires computing the captures information, however, and thus can save
NonBacktracking a non-trivial amount of work. Here's a microbenchmark to highlight the differences:
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Running; using System.Text.RegularExpressions; [MemoryDiagnoser] public class Program { static void Main(string[] args) => BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args);. """; private readonly Regex _words = new Regex(@"\b(\w+)\b", RegexOptions.NonBacktracking); [Benchmark] public int Count() => _words.Count(s_text); [Benchmark] public int EnumerateMatches() { int count = 0; foreach (ValueMatch _ in _words.EnumerateMatches(s_text)) { count++; } return count; } [Benchmark] public int Match() { int count = 0; Match m = _words.Match(s_text); while (m.Success) { count++; m = m.NextMatch(); } return count; } }
which on my machine yields results like these:
Note that
Count and
EnumerateMatches are much faster than
Match, as
Match needs to compute the captures information, whereas
Count and
EnumerateMatches only need to compute the bounds of the match. Also note that both
Count and
EnumerateMatches end up being ammortized allocation-free.
So, spans are supported, yay. You can see we overcame the second highlighted issue by creating a new
EnumerateMatches method that doesn't return a
class Match and instead returns a
ref struct ValueMatch. But what about the first issue? To address that, we introduced a new virtual
Scan(ReadOnlySpan<char>) method on
RegexRunner, and changed the existing abstract methods to be virtual (they now exist only for compatibility with any
CompileToAssembly assemblies that might still be in use), such that
Scan is the only method that now need be overridden by the source generator. If we try a sample like:
using System.Text.RegularExpressions; partial class Program { public static void Main() => Console.WriteLine(Example().IsMatch("aaaabbbb")); [RegexGenerator(@"a*b", RegexOptions.IgnoreCase, -1)] private static partial Regex Example(); }
we can see the source generator spits out a
RegexRunner-derived type that overrides
Scan:
/// <summary>Scan the <paramref name="inputSpan"/> starting from base.runtextstart for the next match.</summary> /// <param name="inputSpan">The text being scanned by the regular expression.</param> protected override void Scan(ReadOnlySpan<char> inputSpan) { // Search until we can't find a valid starting position, we find a match, or we reach the end of the input. while (TryFindNextPossibleStartingPosition(inputSpan) && !TryMatchAtCurrentPosition(inputSpan) && base.runtextpos != inputSpan.Length) { base.runtextpos++; } }
With that, the public APIs on
Regex can accept a span and pass it all the way through to the engines for them to process the input. And the engines are all then fully implemented in terms of only span. This has itself served to clean up the implementations nicely. Previously, for example, the implementations needed to be concerned with tracking both a beginning and ending position within the supplied string, but now the span that's passed in represents the entirety of the input to be considered, so the only bounds that are relevant are those of the span itself.
Vectorization
As noted earlier when talking about
IgnoreCase, vectorization is the idea that we can process multiple pieces of data at the same time with the same instructions (also known as "SIMD", or "single instruction multiple data"), thereby making the whole operation go much faster. .NET 5 introduced a bunch of places where vectorization was employed. .NET 7 takes that significantly further.
Leading Vectorization
One of the most important places for vectorization in a regex engine is when finding the next location a pattern could possibly match. For longer input text being searched, the time to find matches is frequently dominated by this aspect. As such, as of .NET 6,
Regex had various tricks in place to get to those locations as quickly as possible:
- Anchors. For patterns that began with an anchor, it could either avoid doing any searching if there was only one place the pattern could possibly begin (e.g. a "beginning" anchor, like
^or
A), and it could skip past text it knew couldn't match (e.g.
IndexOf('\n')for a "beginning-of-line" anchor if not currently at the beginning of a line).
- Boyer-Moore. For patterns beginning with a sequence of at least two characters (case-sensitive or case-insensitive), it could use a Boyer-Moore search to find the next occurrence of that sequence in the input text.
- IndexOf(char). For patterns beginning with a single case-sensitive character, it could use
IndexOf(char)to find the next possible match location.
- IndexOfAny(char, char, ...). For patterns beginning with one of only a few case-sensitive characters, it could use
IndexOfAny(...)with those characters to find the next possible match location.
These optimizations are all really useful, but there are many additional possible solutions that .NET 7 now takes advantage of:
- Goodbye, Boyer-Moore.
Regexhas used the Boyer-Moore algorithm since
Regex's earliest days; the
RegexCompilereven emitted a customized implementation in order to maximize throughput. However, Boyer-Moore was created at a time when vector instruction sets weren't yet a reality. Most modern hardware can examine 8 or 16 16-bit
chars in just a few instructions, whereas with Boyer-Moore, it's rare to be able to skip that many at a time (the most it can possibly skip at a time is the length of the substring for which it's searching). In the aforementioned corpus of ~19,000 regular expressions, ~50% of those expressions that begin with a case-sensitive prefix of at least two characters have a prefix less than or equal to four characters, and ~75% are less than or equal to eight characters. Moreover, the Boyer-Moore algorithm works by choosing a single character to examine in order to perform each jump, but a well-vectorized algorithm can simultaneously compare multiple characters, such as the first and last in the prefix (as described in SIMD-friendly algorithms for substring searching), enabling it to stay in the inner vectorized loop longer. In .NET 7,
IndexOfperforming an ordinal search for a string has been significantly improved with such tricks, and now in .NET 7,
Regexuses
IndexOfrather than Boyer-Moore, the implementation of which has been deleted (this was inspired by Rust's regex crate making a similar change last year). You can see the impact of this on a microbenchmark like the following, which is finding every word in a document, creating a
Regexfor that word, and then using each
Regexto find all occurrences of each word in the document (this would be an ideal use for the new
Countmethod, but I'm not using it here as it doesn't exist in the previous releases being compared):
private string _text; private Regex[] _words; [Params(false, true)] public bool IgnoreCase { get; set; } [GlobalSetup] public async Task Setup() { using var hc = new HttpClient(); _text = await hc.GetStringAsync(@""); _words = Regex .Matches(_text, @"\b\w+\b") .Cast<Match>() .Select(m => m.Value) .Distinct(IgnoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal) .Select(s => new Regex(Regex.Escape(s), RegexOptions.Compiled | (IgnoreCase ? RegexOptions.IgnoreCase | RegexOptions.CultureInvariant : RegexOptions.None))) .ToArray(); } [Benchmark] public int FindAllOccurrencesOfAllWords() { int count = 0; foreach (Regex word in _words) { Match m = word.Match(_text); while (m.Success) { count++; m = m.NextMatch(); } } return count; }
On my machine, I get numbers like this:
Even when compared against an optimized string searching algorithm like Boyer-Moore, this really highlights the power of vectorization.
- IndexOfAny in More Cases. As noted, .NET 6 supports using
IndexOfAnyto find the next matching location when a match can begin with a small set, specifically a set with two or three characters in it. This limit was chosen because
IndexOfAnyonly has public overloads that take two or three values. However,
IndexOfAnyalso has an overload that takes a
ReadOnlySpan<T>of the values to find, and as an implementation detail, it actually vectorizes the search for up to five. So in .NET 7, we'll use that span-based overload for sets with four or five characters, expanding the reach of this valuable optimization.
private static Regex s_regex = new Regex(@"Surname|(Last[_]?Name)", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static string s_text = @"We're looking through text that might contain a first or last name."; [Benchmark] public bool IsMatch() => s_regex.IsMatch(s_text);
- Fixed-Distance Sets. Just looking at what starts a pattern can be limiting. Consider a pattern like this one, which could be used to match United States social security numbers:
d{3}-d{2}-d{4}. Even if
\dmatched only 10 possible characters (it actually matches any Unicode digit, which is closer to 370 characters), that's more difficult to vectorize a search for. However, it's trivial to vectorize a search for
'-'.
Regexin .NET 7 is now able to compute sets of characters that can exist at fixed-distance offsets from the beginning of the pattern (e.g. in this social security example, the set
[-]exists at index 3 into the pattern), and it can then pick the one it expects will yield the fastest search. Here's a microbenchmark to show the impact this can have: 012-34-5678. """; private static readonly Regex s_social = new Regex(@"\d{3}-\d{2}-\d{4}", RegexOptions.Compiled); [Benchmark] public bool ContainsSocial() => s_social.IsMatch(s_text);
On my machine, I get numbers like this:
In other words, .NET 6 is more than 15x faster for this search than .NET Framework 4.8, and .NET 7 is still more than 8x faster than .NET 6 (almost 128x faster than .NET Framework 4.8).
- Non-Prefix String Search. Just as we can search for a string at the beginning of the pattern, we can also search for a string in the middle of the pattern. This is effectively an extension of the fixed-distance sets optimization: rather than searching for a single character, if there are multiple next to each other, we can search for all of them and enable
IndexOfto work its magic and minimize the number of false positives and the number of times we need to jump back and forth between the vectorized search and the matching logic. For example, the regex benchmarks at rust-leipzig/regex-performance contain a pattern
[a-z]shing. The opening set is fairly large, with 26 possible characters, so the fixed-distance sets optimization would prefer to use one of the subsequently computed sets, each of which has just a single character. But it's even better to search for all of them ("shing") as a string.
private static Regex s_regex = new Regex(@"[a-z]shing", RegexOptions.Compiled); private static string s_text = new HttpClient().GetStringAsync(@"").Result; [Benchmark] public int SubstringSearch() { int count = 0; Match m = s_regex.Match(s_text); while (m.Success) { count++; m = m.NextMatch(); } return count; }
This produces numbers like this on my machine:
showing that, for this test, .NET 7 is an enormous ~103x faster than .NET 6, and ~383x faster than .NET Framework 4.8. This support is also valuable even in more complicated patterns. Consider this pattern from Rust's regex performance tests:
(?m)^Sherlock Holmes|Sherlock Holmes$. The
(?m)inline modifier is the same as specifying
RegexOptions.Multiline, which changes the meaning of the
^and
$anchors to be beginning-of-line and end-of-line, respectively. Thus, this is looking for "Sherlock Holmes" at either the beginning of a line or the end of a line. Either way, though, we can search for "Sherlock Holmes" in each line (noting, too, that the lines in this input are fairly short). I've been showing mostly benchmarks with
RegexOptions.Compiled, but to highlight that these optimizations benefit the interpreter as well, I'll leave that option off here:
private static Regex s_sherlock = new Regex(@"(?m)^Sherlock Holmes|Sherlock Holmes$"); private static string s_text = new HttpClient().GetStringAsync(@"").Result; [Benchmark] public int Match() { int count = 0; Match m = s_sherlock.Match(s_text); while (m.Success) { count++; m = m.NextMatch(); } return count; }
which on my machine produces:
- Literals After Loops. Consider a pattern like the simple email regex in the cross-language regex benchmarks at:
[\w.+-]+@[\w.-]+.[\w.-]+. There's no leading prefix here, and there's no small set we can vectorize a search for at a fixed distance from the beginning of the pattern, because of that pesky
[\w.+-]+set loop at the beginning. But there are also some interesting things to notice here. Most importantly, there's an
@following that loop, the loop has no upper bound, and the set being looped around can't match
@. That means, even though the loop wasn't written as an atomic loop, it can be processed as one. We can search for the
@, match backwards through the opening loop, and then if it's successful, continue the matching forward after the
@. So rather than walking each character looking to see if it's in the set
[\w.+-], we can vectorize a search for the
@. Here's that mariomka/regex-benchmark benchmark extracted into a standalone benchmarkdotnet test:
private static Regex s_email = new Regex(@"[\w.+-]+@[\w.-]+.[\w.-]+", RegexOptions.Compiled); private static string s_text = new HttpClient().GetStringAsync(@"").Result; [Benchmark] public int Email() { int count = 0; Match m = s_email.Match(s_text); while (m.Success) { count++; m = m.NextMatch(); } return count; }
which on my machine produces lovely numbers like this:
That's not a copy-and-paste error. .NET 6 is ~21x faster than .NET Framework 4.8 here, primarily because of optimizations added in .NET 5 to precompute set lookups for ASCII characters, and .NET 7 is ~78x faster than .NET 6 (and a whopping ~1,636x faster than .NET Framework 4.8) because of this vectorization. This optimization was inspired by a nicely-written description of what nim-regex does for similar patterns, highlighting how many regex engines are turning to this kind of vectorization for improved performance (HyperScan has long been a leader in this area, in particular for domains focused on streaming, such as intrusion prevention systems).
- Trailing Anchors. Since the beginning of
Regexin .NET, it's applied anchor-based optimizations, like the ones cited earlier. However, these optimizations have all been based on leading anchors, i.e. anchors at the beginning of the pattern. It's largely ignored trailing anchors, such as
$at the end of the pattern. But such anchors are potentially huge sources of performance improvements, in particular for patterns that aren't also anchored at the beginning. .NET 7 now looks for patterns that end with anchors and also computes whether there's a maximum length a pattern could match (.NET 5 added an optimization to compute the minimum length a pattern could match, which is used primarily to determine whether there's even enough input left to try to match); if it has both a trailing end anchor and a maximum match length, the engine can immediately jump to that offset from the end, as there's no point trying to match anything before then. It's almost unfair to show a benchmark and resulting improvements here... but these numbers are just plain fun, so I will:
private static Regex s_endsInDigits = new Regex(@"\d{5}$|\d{5}-\d{4}$", RegexOptions.Compiled); private static string s_text = new HttpClient().GetStringAsync(@"").Result; [Benchmark] public bool IsMatch() => s_endsInDigits.IsMatch(s_text);
On my machine, I get:
Making operations faster is valuable. Entirely eliminating unnecessary work is priceless.
- Better Leading Anchors. Consider a pattern like
^abc. Every previous version of
Regexwill notice that this pattern leads with a beginning anchor, and will use that to root the match at the beginning of the input, avoiding the unnecessary expense of trying to match the pattern elsewhere in the input when it's guaranteed to not. However, now consider a pattern like
^abc|^def. Previous versions of
Regexwould fail to notice that the pattern was still rooted, since every possible branch of the alternation begins with the same anchor. In .NET 7, the optimizer does a better job of properly searching for leading anchors, and will see that this pattern is the equivalent of
^(?:abc|def), which it knows how to optimize. This can make matching way faster. Consider this Dutch century pattern:
(^eeuw|^centennium)b. The implementation previously wouldn't have optimized for that leading
^, but now in .NET 7 it will:
private static Regex s_centuryDutch = new Regex(@"(^eeuw|^centennium)b", RegexOptions.Compiled);. """; [Benchmark] public bool IsMatch() => s_centuryDutch.IsMatch(s_text);
Note that most of these optimizations apply regardless of the engine being used, whether it's the interpreter,
RegexOptions.Compiled, the source generator, or
RegexOptions.NonBacktracking. For the backtracking engines, all of these find optimizations apply as part of the scan loop. The loop essentially repeatedly calls a
TryFindNextStartingPosition method, and for each viable location found, invokes the
TryMatchAtCurrentPosition method; these optimizations form the basis of the
TryFindNextStartingPosition method. For the non-backtracking engine, as mentioned previously, it's essentially just reading the next character from the input and using that to determine what node in a graph to transition to. But one or more nodes in that graph are considered a "starting state", which is essentially a state that's guaranteed not to be part of any match. In such states, the non-backtracking engine will use the same
TryFindNextStartingPosition that the interpreter does in order to jump past as much text as possible that's guaranteed not to be part of any match.
It's also important to note that, as with almost any optimization, when one things gets faster, something else gets slower. Hopefully the thing that regresses is rare and doesn't regress by much, and the thing that gets faster is so much faster and so much more common that the upsides completely outweigh the downsides. This is the case with some of these optimizations. It's possible, for example, that we use
IndexOf in cases where we didn't previously, and it turns out that the
IndexOf for a given input wasn't actually necessary, because the very first character in the input matches; in such a case, we will have paid the overhead for invoking
IndexOf (overhead that is very small but not zero) unnecessarily. Thankfully, these wins are so huge and the costs so small, that they're almost always the right tradeoff, and in cases where they're not, the losses are tiny and have workarounds (e.g. if you know the input will match at the beginning, using a beginning anchor).
Internal Vectorization
Finding the next possible location for a match isn't the only place vectorization is useful; it's also valuable inside the core matching logic, in various ways. .NET 5 added a few such optimizations here:
- "not" loops. Consider an expression like
abc.*def. With a backtracking engine, this is going to match
"abc", then consume anything other than a
'\n'greedily, and then backtrack (giving back some of what was greedily matched) until it finds
"def". Thus, the forward portion of that match can use
IndexOf('\n')to find the initial end of the loop. Similarly,
abc[^-:]*defwill try to match
"abc", then greedily consume anything other than
'-'and
':'characters, and then backtrack until it finds
"def". Here as well, the forward portion of that match can use
IndexOfAny('-', ':').
- Singleline
.*. When you specify the
RegexOptions.Singlelineoption, that has the sole effect of changing
.in a pattern from meaning "match anything other than
'\n'to "match anything". With a
.*loop with
RegexOptions.Singlelinethen, that really says "greedily consume everything", and the implementation needn't even use
IndexOfor
IndexOfAny... it can simply jump to the end of the input.
.NET 7 adds more:
- Loop Backtracking. The previous "not" loop example of
abc.*defis interesting. I highlighted that this will match the
"abc", then use
IndexOf('\n')to find the end of the greedy consumption, and then backtrack looking for
"def". In .NET 6, such backtracking would happen one character at a time. But in .NET 7, we now use
LastIndexOf("def")to find the next possible place to run the remainder of the pattern, allowing that search to be vectorized. This extends not just to multiple-character sequences and single characters following such loops, but also to sets. If the pattern were instead
abc.*[def], the compiler and source generator will instead emit a call to
LastIndexOfAny('d', 'e', 'f'). Here's an example microbenchmark:
private static Regex s_regex = new Regex(@"abc.*def", RegexOptions.Compiled); private static string s_text = @"abcdef this is a test to see what happens when it needs to backtrack all the way back"; [Benchmark] public bool IsMatch() => s_regex.IsMatch(s_text);
and we can see the effect this vectorization has on the numbers I get back:
Throughput here almost doubles going from .NET Framework 4.8 to .NET 6, primarily because the
.*matching is performed in .NET 6 using an
IndexOf('\n')rather than matching each next character consumed by the loop individually. And then throughput gets ~5x faster again going to .NET 7, as now not only is the forward direction vectorized with
IndexOf('\n'), the backtracking direction gets vectorized with
LastIndexOf("def").
- Lazy Loop Backtracking. Consider a pattern like
<.*?>. This is looking for an opening
'<', then lazily consuming as many characters other than
'\n'as it can until the next
'>'. In .NET 6, this would dutifully backtrack one character at a time, consuming the next non-
'\n'and then checking whether the current character is a
'>', consuming the next non-
'\n'and then checking whether the current character is a
'>', and on. Now in .NET 7, this recognizes the operation for what it is, a search for either
'\n'or
'>', and will use an
IndexOfAny('\n', '>')to speed up that search:
private static Regex s_regex = new Regex(@"<.*?>", RegexOptions.Compiled); private static string s_text = @"This is a test <to see how well this does at finding the bracketed region using a lazy loop>."; [Benchmark] public bool IsMatch() => s_regex.IsMatch(s_text);
Here I get these numbers:
- StartsWith. Going back to the earliest days of the
RegexCompiler, one of the main optimizations employed was to unroll various loops. For example, if a pattern contained the string
"abcd", rather than emitting that as a loop over the string comparing each character with the input, it would emit it as a hardcoded check against
'a', a hardcoded check against
'b', and so on. This helps to avoid some of the loop overhead as well as the overhead associated with indexing into and reading from the pattern string. In .NET 5, this was improved upon by reading not just one character at a time, but either two or four at a time, reading and comparing
Int32or
Int64values rather than 16-bit character values, a process that can double or quadruple the matching time for such strings. This manual vectorization, however, has some downsides, especially in the face of the source generator. Such code is difficult to read and comprehend. On top of which, such operations need to be very careful about endianness. With
RegexCompiler, where the numerical comparison values were being computed in the same process that was then doing the same operation on the input, endianness isn't an issue as the endianness of the values computed at compilation time are guaranteed to be the same as the endianness of the machine at execution time. But with the source generator, the source generator could end up being run on a machine with one endianness and then executed on a machine with a different endianness, which means the generated code needs to be able to handle both. Since comparing against literal strings is a common task, in .NET 7 the Just-in-Time compiler (JIT) adds optimizations for methods like
StartsWithwhen passed a string literal. The JIT is now able to generate assembly code employing similar styles of vectorization, which means developers can just use methods like
StartsWithand get these optimizations for free. So can the source generator. So now in .NET 7, both the
RegexCompilerand the source generator do the simple thing of just emitting calls to
StartsWith, and in doing so get all the perf benefits of the vectorized comparisons, while also getting code that's very readable. Further, this applies to
RegexOptions.IgnoreCaseas well. If the
RegexCompilerand source generator find a sequence of sets that have pairs of ordinal-case-insensitive-equivalent ASCII letters, rather than emitting set comparisons for each, it will emit for the whole sequence a single call to
StartsWithwith
StringComparison.OrdinalIgnoreCase, and the JIT again will vectorize the processing of this literal. Meaning, we get nicely readable source and as good or better performance.
private static Regex s_regex = new Regex(@"babcd", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static string s_text = @"ABCD"; [Benchmark] public bool IsMatch() => s_regex.IsMatch(s_text);
To see this in action, this is what the source generator emits for the TryMatchAtCurrentPosition method for the above regex:
/// <summary>Determine whether <paramref name="inputSpan"/> at base.runtextpos is a match for the regular expression.</summary> /// <param name="inputSpan">The text being scanned by the regular expression.</param> /// <returns>true if the regular expression matches at the current position; otherwise, false.</returns> private bool TryMatchAtCurrentPosition(ReadOnlySpan<char> inputSpan) { int pos = base.runtextpos; int matchStart = pos; ReadOnlySpan<char> slice = inputSpan.Slice(pos); // Match if at a word boundary. if (!Utilities.IsBoundary(inputSpan, pos)) { return false; // The input didn't match. } if ((uint)slice.Length < 4 || !slice.StartsWith("abcd", StringComparison.OrdinalIgnoreCase)) // Match the string "abcd" (ordinal case-insensitive) { return false; // The input didn't match. } // The input matched. pos += 4; base.runtextpos = pos; base.Capture(0, matchStart, pos); return true; }
Auto-Atomicity and Backtracking
In a backtracking engine, especially when matching inputs that force a lot of backtracking, that backtracking tends to be the dominating cost of the match operation itself. It's thus very beneficial to try to construct patterns in a way that avoids incurring backtracking as much as possible. One way a developer can do this is by manually using an atomic group,
(?> ). Such an atomic group tells the engine that, regardless of what happens inside the group, once the group matches, it matches, and nothing after the group can backtrack into the group. For example, if you had the pattern
a*b, and you try to match it against
"aaaa", a backtracking engine might successfully match four
'a's, then try to match the
'b', see it doesn't match, so backtrack one, try to match there, it doesn't, backtrack again, etc. But if you instead wrote it as
(?>a*)b, an engine will match the four
'a's as before, but then when it goes to match the
'b' and fails, there's nothing to backtrack to other than failing the whole match, since the loop is now atomic and doesn't give anything back.
Of course, using such atomic groups isn't something most developers are accustomed to doing. In recognition of that, and because it's easy to miss opportunities where atomicity could be used without negative impact, .NET 5 added some "auto-atomicity" optimizations, inspired by discussion in Jeffrey Friedl's seminal "Mastering Regular Expressions" book. Effectively, as part of optimizing the
RegexNode tree from parsing the expression, the analyzer would look for loop and alternation constructs (which are where backtracking comes from) where backtracking wouldn't actually have a behavioral impact such that it could be eliminated. Let's look at the previous example of
a*b again. After finding there's no
'b' to match, the engine can backtrack to see if it could match
'b' against something earlier in the input that had matched as part of the
'a*'. But there's nothing
'a' matches that
'b' could possibly match, hence all attempts at getting a match via backtracking here are for naught. In such cases, the optimizer can automatically upgrade the loop to being an atomic one. You can see this taking affect with the source generator... here's that same email regex used in a microbenchmark earlier:
Note that there's no atomic loop in the pattern as I wrote it in the
RegexGenerator attribute, but the IntelliSense comment is highlighting that both the first and third loop in this pattern are atomic. The analyzer has determined that there's no behavioral difference whether these are greedy as written or atomic, other than the negative perf implications of them being greedy; hence it's made them atomic.
However, the .NET 5 optimizations had some limitations. In particular, the optimizer would only look at a single node guaranteed to come immediately after the construct in question. So for example, with the expression
a+b+c+, when analyzing the
a+, it would only look at the
b+. In that particular case, it's fine, because
b+ is the same as
bb*, guaranteeing there will be a
b after the
a+, and since
a and
b don't overlap, enabling the
a+ to be made atomic. But now consider if our expression was instead
a*b*c*. Now the
b* is "nullable", meaning it can match the empty string, and that means the
a* could actually be followed by whatever comes after the
b*. At that point the optimizations from .NET 5 would just give up, and the
a* would remain greedy. Now in .NET 7, the optimizer is able to continue processing the rest of the expression, and will see that the
a* could be followed by either a
b or
c (or nothing), neither of which overlaps with
a, so it can still be made atomic; in fact in this example, all of the loops will be made atomic.
private static Regex s_regex = new Regex(@"a*b*c*d*$", RegexOptions.Compiled); private static string s_text = @"aaaaaaaaaaaaaaaaaz"; [Benchmark] public bool IsMatch() => s_regex.IsMatch(s_text);
This applies to lazy loops as well (though due to their nature of preferring fewer rather than more iterations, there are also fewer circumstances in which they can be made atomic). So, for example, whereas in .NET 6 the expression
a*?b*?c wouldn't be modified, in .NET 7 that will now be equivalent to
(?>a*)(?>b*)c. The analyzer recognizes here that, for example, there's nothing
b*? can match that will also match
c. If the lazy loop were to match fewer
bs than existed in the input, then the subsequent
c wouldn't match (because it would try to match
c against
b), and the lazy loop would backtrack to add an additional iteration (that sounds funny, but whereas a greedy loop means match as much as possible and then backtrack to give some of it back, a lazy loop means match as little as possible and then backtrack to take more). The net result of that is when a lazy loop doesn't overlap with what's guaranteed to come next, it's indistinguishable from a greedy loop in terms of what it will end up matching, and so it can similarly be made into an atomic greedy loop.
private static Regex s_regex = new Regex(@"a*?b*?c$", RegexOptions.Compiled); private static string s_text = @"aaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbz"; [Benchmark] public bool IsMatch() => s_regex.IsMatch(s_text);
The optimizer is now also better at handling loops and lazy loops at the end of expressions. This can even result in some fairly surprising output from the source generator that might leave you scratching your head for a moment, e.g.
Why is the expression
a*? described as "Match an empty string"? Because the optimizer sees that there's nothing after the
a*?, which means nothing can backtrack into it, which means it can be made atomic. And lazy loops only add additional iterations either because they're required by the minimum bound or in response to backtracking, so a lazy loop that's atomic can be transformed into a loop with its upper bound lowered to its lower bound. A
* loop has an upper bound of infinity and a lower bound of 0, which means
a*? actually becomes
a{0}, which is the same as empty. As a result, here's the entirety of the generated
Scan method for this pattern:
/// <summary>Scan the <paramref name="inputSpan"/> starting from base.runtextstart for the next match.</summary> /// <param name="inputSpan">The text being scanned by the regular expression.</param> protected override void Scan(ReadOnlySpan<char> inputSpan) { // The pattern matches the empty string. int pos = base.runtextpos; base.Capture(0, pos, pos); }
Neat.
There's another valuable related optimization, and while not about auto-atomicity, it is about avoiding redoing the same computations when we know they won't produce any new payoff. In .NET 5, one of the optimizations added was an "update bumpalong" operation. The main
Scan loop repeatedly invokes the logic to find the next possible match location, and then match there. If the match at that location fails, we need to "bump along" the position pointer to start from at least one past where we previously tried. But there are other situations where we might want to update that position pointer. Consider an expression like
a*c invoked on input like
"aaaaaaaabaaaaaaaac", in other words a sequence of
as followed by a
b and then a sequence of
as followed by a
c. We'll try to match at position 0, match all 8
as, but then find that what comes next isn't a
c. Thanks to the auto-atomicity logic, this won't try to backtrack. But, when it goes back to the scan loop, the bumpalong logic will increment the position from 0 to 1, and start the match over there. Now the
a* will match from position 1 and find 7
as, followed by a
b rather than a
c, and again we'll exit out to the
Scan loop. You can see where this is going. We're trying to perform the same match at each of the first 8 positions, even though we actually can prove after the first that none of the rest will be successful. It won't be until we get past where the atomic loop examined that we might have a chance of finding a match. To help with this, .NET 5 added the optimization of updating the bumpalong, such that at the end of the opening atomic loop, the top-level bumpalong pointer would be updated to refer to the furthest position seen by the loop. That way, after the match at position 0 failed, we would next try not at position 1 but rather at position 8.
However, while valuable for leading atomic loops, this optimization ended up not helping with leading greedy loops. With an atomic loop, when we're done consuming and update the bumpalong, that's it, we never revisit the loop. But with a greedy loop, we'd start by updating the bumpalong to the furthest value seen, but then when we'd backtrack, we'd update the position to that lower index, and then we'd backtrack again and update the position to there, and so on. So even though we did in fact already examine all of the positions up to the updated location, the updated bumpalong pointer wouldn't retain its value, and we could end up redoing some or all of the matches again.
.NET 7 tweaks the logic to ensure, for appropriate greedy loops, that the update bumpalong ensures the position is as far into the input as it can be. It also is updated to support lazy loops in addition to greedy ones. The effect is evident from this (silly but representative) benchmark (note the capital
'D' amongst all the lowercase letters in the input):
private static readonly Regex s_greedy = new Regex(".*abcd", RegexOptions.Compiled); private static readonly Regex s_lazy = new Regex(".*?abcd", RegexOptions.Compiled); private static readonly string s_input = string.Concat(Enumerable.Repeat("abcDefghijklmnopqrstuvwxyz", 1000)); [Benchmark] public void Greedy() => s_greedy.IsMatch(s_input); [Benchmark] public void Lazy() => s_lazy.IsMatch(s_input);
Not having to redo the same work over and over and over is one of the best possible performance optimizations, as the numbers relay:
Set Optimizations
After backtracking, the cost of determining whether a character is in a character class (a set) is often one of the largest costs associated with matching a regular expression. In versions of .NET prior to .NET 5, there were very few optimizations around this, however. Sets containing just one character, e.g.
[a], or the negation of just one character, e.g.
[^a], were well optimized, but beyond that, determining whether a character matched a character class involved a call to the protected
RegexRunner.CharInClass method. This method accepts the character to be tested as well as a string-based description of the set, and returns a Boolean indicating whether the character is included. .NET 5 recognized that this is a significant cost, and added some very impactful optimizations here which were often the source of 3-4x speedups in regex when migrating to .NET 5, in particular for
RegexOptions.Compiled. For example:
\dwould be emitted as a call to
char.IsDigit.
\swould be emitted as a call to
char.IsWhiteSpace.
- A range like
[0-9]would be emitted as the equivalent of C# like
((uint)ch) - '0' <= (uint)('9' - '0').
- A single Unicode category like
\p{Lt}would be emitted as the equivalent of C# like
char.GetUnicodeCategory(ch) == UnicodeCategory.TitlecaseLetter.
- A small set of just a couple of characters like
[ac]would be emitted as the equivalent of C# like
(ch == 'a') | (ch == 'c').
Beyond those, however, the implementation would compute a 128-bit ASCII bitmap (stored as an 8-character string) that it could use to quickly answer the question of set inclusion for ASCII characters, and would then only fall back to calling the original
RegexRunner.CharInClass if none of the special-cases handled the set and an input character was non-ASCII. For example, the character class
[\w\s], which contains all Unicode word characters and all Unicode spaces, will yield a check equivalent to:
ch < 128 ? ("\u3e00\u0000\u0001\u03ff\ufffe\u87ff\ufffe\u07ff"[ch >> 4] & (1 << (ch & 0xF))) != 0 : !RegexRunner.CharInClass((char)ch, "\u0000\u0000\u000B\u0000\u0002\u0004\u0005\u0003\u0001\u0006\u0009\u0013\u0000\u0064"))
That first string isn't really text, but rather 128 bits representing the ASCII characters, with a 1 bit for each that's in the set and a 0 bit for each that's not... 8 characters in a string is just a convenient way to store the data.
There are a variety of ways we can improve on this, though, and .NET 7 does:
- .NET 6 already optimized
.with
RegexOptions.Singlelineto be the equivalent of
true. However, it turns out in practice a lot of developers end up using somewhat odd looking sets like
[\s\S],
[\w\W], and
[\d\D]to be the equivalent of "match anything", yet the code generator didn't recognize that these sets were all-inclusive. Now it does.
- .NET 6 optimizes sets that are simply a single Unicode category, as shown previously. Now in the source generator, .NET 7 supports any number of categories, emitting a check as a
switchexpression that enables the C# compiler's optimizations around switch expressions to kick in. For example,
\p{L}will now be emitted as:
char.GetUnicodeCategory(ch) switch { UnicodeCategory.LowercaseLetter or UnicodeCategory.ModifierLetter or UnicodeCategory.OtherLetter or UnicodeCategory.TitlecaseLetter or UnicodeCategory.UppercaseLetter => true, _ => false })
which the C# compiler in turn will optimize to the equivalent of
(uint)char.GetUnicodeCategory(ch) <= 4u
The C# compiler doesn't yet optimize pattern matching to the same degree, but when it does, this will likely change to be based on an
isinstead of a
switch.
- .NET 6 optimizes small sets of characters as previously shown, but not small negated sets of characters. Now in .NET 7 if you write a set like
[^14], you'll get a check like
(ch != '1') & (ch != '4').
- .NET 7 also now recognizes the very common pattern of two ASCII characters that differ by only a single bit, which is common in large part because of case-insensitivity, due to uppercase ASCII letters differing by only a single bit (0x20) from their lowercase ASCII counterparts. Thus if you write the set
[Aa], that will be emitted as
(ch | 0x20) == 'a'. Interestingly, the optimization is written in such a way that it doesn't care which bit it is that differs, so if for example you write
[<>], that will be emitted as
(ch | 0x2) == '>'. This also applies for three character sets where the lower two case to each other. That's relevant because there are a handful of sets generated by
RegexOptions.IgnoreCasethat follow this pattern. For example, in the "en-US" culture, the letter
i(0x69) is not only considered case-insensitive-equivalent to the letter
I(0x49) but also to LATIN CAPITAL LETTER I WITH DOT ABOVE (0x130). With this optimization in place, then,
iwith
RegexOptions.IgnoreCasebecomes the equivalent of
[Iiİ], which is now emitted as
((ch | 0x20) == 'i') | (ch == 'İ').
- .NET 6 optimized sets with a single range, e.g. the
[0-9]shown earlier. .NET 7 now similarly handles sets with two ranges, e.g. the set
[\p{IsGreek}\p{IsGreekExtended}]will now be emitted as:
((uint)(ch - 'Ͱ') <= (uint)('Ͽ' - 'Ͱ')) | ((uint)(ch - 'ἀ') <= (uint)('u1fff' - 'ἀ'))
.
One of the more valuable set improvements, though, is another level of fallback before we get to the string-based ASCII bitmap. If upon examination of the set we can determine that the smallest and largest character in the set are within 64 values of each other, then we can emit a
ulong-based bitmap, and we can do so in a way that's not only smaller in size, but is also branchless in execution. This allows for sets like
[A-Fa-f0-9], which is a set for all hexadecimal digits, to be handled very efficiently, e.g. that set will now be handled with code emitted like:
(long)((0xFFC07E0000007E00UL << (int)(charMinusLow = (uint)ch - '0')) & (charMinusLow - 64)) < 0
and the impact of that can add up:
private static Regex s_regex = new Regex(@"0x[A-Fa-f0-9]+", RegexOptions.Compiled); private static string s_text = @"This is a test to find hex numbers like 0x123ABC."; [Benchmark] public bool IsMatch() => s_regex.IsMatch(s_text);
What's Next?
We still have months before .NET 7 ships, and we've not seen the end of improvements coming for
Regex. In fact, while writing this post I'm using a nightly .NET 7 Preview 5 build, which includes improvements new since Preview 4. All of the new features discussed in this post will continue to see improvements prior to release, and additional performance gains are also expected. We'd love your feedback on the new APIs, the new
NonBacktracking engine, the new performance improvements, and in general your feedback on using
Regex in .NET in general. And for anyone interested, we'd welcome improvements in the form of issues and pull requests as well.
Happy coding.
Many thanks for this article! I really appreciate you took the time to explain the various optimizations, which are very interersting. Each post of yours is excellent. And of course, that’s a lot of great work on the engine itself! I can’t wait to try it out.
I maintain PCRE.NET, so I can’t help but compare .NET Regex to PCRE2. I was wondering if you plan on expanding the regex capabilities, either with syntactic sugar like possessive quantifiers (
a++being the equivalent of
(?>a+)), or with new features such as recursive patterns (that one in particular would be awsesome). Thanks!
Thanks!
We have an open issue for possessive quantifiers:
but we haven’t received much interest in it.
I haven’t really seen interest expressed in that either. Most uses of recursive patterns I’ve seen is around parenthesis/bracket/etc. matching, and balancing groups in .NET regexes are often used to achieve the same.
I think recursion is valuable since it allows you to match a context-free language, and it’s easier to reason about than balancing groups (which AFAIK only the .NET Regex engine supports).
It also allows constructs similar to method calls: a subpattern can be called multiple times, and combining that feature with
(?(DEFINE) ... )blocks lets you build a pattern with a clear structure.
I’m not surprised you haven’t received much interest in those, since they’re pretty advanced features that few people want to deal with. 🙂
All that longread is interesting, but is there anything what prevents you from porting new engine to .NET FW 4.8?
That is a fake excuse and a transfer of responsibility to someone else’s post. Is there a reason
It’s not an excuse, it’s an explanation. We’re not making such changes (or any of the myriad of changes they in turn rely on) to .NET Framework.
Thanks for the article but IMO this is way too long to read.
there should be a shorter version of this in order to reach more audience
Thank you for the suggestion. I prefer to write and publish all the content and then enable folks to consume it whenever and however they choose, rather than artificially breaking it up into pieces and forcing it to be consumed in a more prescribed manner.
You clearly spent many hours just putting this article together. For that and the many more hours adding these performance gains, thank you.
Thanks 🙂
Thanks, as always, for the fantastic deep dive!
It struck me when you mentioned how /w and /s match large character classes that are too big for optimizations. As these are the path of least-resistance for most developers it is a shame they can’t benefit. Are there any thoughts to improving this? Maybe a Regex option that controls what they encompass?
The other question I have from reading this is if there are any noticeable known breaks in Regex from prior versions given the deep engine changes, and if so, how well you guys maintain the bar for “standardization” of Regex (eg- most regex dialects across languages are 90% similar to each other).
Such an option exists: while it also impacts a few other corner-case things, RegexOptions.ECMAScript primarily serves to change the meaning of \d, \w, and \s to be ASCII-only, e.g. \d becomes [0-9].
For some optimizations. Optimizations are still applied for these, we just can’t apply some things, e.g. we can’t vectorize a search for all of the thousands of characters that compose \w.
The short answer is “no”. Other than any unknown bugs, the only observable behavioral impact stems from the IgnoreCase changes, where there are few corner-case differences in what would have been considered equal previously from what is now considered equal. Previously Regex would consider two characters IgnoreCase-equal if they both lowercased to the same value; now it considers them equal if they lowercase to the same value or if one of them lowercases to the other.
Thank you for significantly improving .NET regular expressions!
If you want to expand your test set of regular expressions: I have developed a machine-learning program that learns/generates interesting executable regular expressions, from an unlimited number of different input sets of strings (randomly generated, or supplied by you) against which you can test.
A toned down proof-of-concept version of this program can be accessed on
It uses a novel ML algorithm to learn opinionated, descriptive, near optimal and executable regular expressions. Furthermore, the learning of regex will be user-guidable in the near future, using hyper-parameters, to balance readability, optimality and abstraction.
Here is a learned regex for matching the words in the last three lines of the poem in your blog above:
\b((e?t(im|h)?|s|giv|li(n|v|f)|br|Wh|ey|m)e+(s|athe|rnal|n)?|(th?|l|gr|S)?o(ng?|w’st?|u|r)?|c?and?|this|as|in)\b | https://devblogs.microsoft.com/dotnet/regular-expression-improvements-in-dotnet-7/comment-page-2/?WT_mc_id=DOP-MVP-4025064 | CC-MAIN-2022-27 | refinedweb | 18,011 | 55.24 |
Code. Collaborate. Organize.
No Limits. Try it Today.
I stumbled across many color conversion libraries/tools that didn't take in account that an RGB color isn't per se defined. It's important to know what exact RGB colorspace this
value is in (e.g., sRGB, AdobeRGB, or ProPhotoRGB) because they have different reference whites, different gamma values and different Chromaticity coordinates. Likewise things are important for other colormodels, too.
sRGB
AdobeRGB
ProPhotoRGB
Because I needed those features for another software, wanted to learn a bit more about this whole color stuff and make the internet a better place, I wrote this library.
There are also some small GUIs:
There are several different colormodels and spaces included in the library:
Also it is possible to do chromatic adaption and change the reference white.
The conversion between those colormodels looks like this:
If you want to know more about how the conversion works:
#region Conversions
Using the library is quite simple but still gives you all
possibilities to define or convert a color.
Lets have a look at the static part of the
ColorConverter class. There are some settings that are used if not defined otherwise. Those settings are:
ColorConverter
ChromaticAdaptionMethod
ReferenceWhite
StandardColorspace
PreferredRenderingIntent
StandardYCbCrSpace
Also, before you start using the library you should initiate the
ColorConverter class. There won't be an error if you don't but this way everything will work controlled:
ColorConverter.Init();
Here are some examples for creating a new color. There are some more possibilities, just try it out as you need it. The code is documented so you'll see the explanation.
ColorRGB color = new ColorRGB(RGBSpaceName.sRGB); //new RGB color in sRGB space
ColorRGB color = new ColorRGB(0, 0.5, 1); //new RGB color in standard RGB space from settings
ColorRGB color = new ColorRGB(RGBSpaceName.sRGB, 0, 0.5, 1, true); //new linear RGB color in sRGB
ColorRGB color = new ColorRGB(new ICC("profile.icc")); //new RGB color from an ICC profile
ColorLab color = new ColorLab(50, 12, -12); //new Lab color with reference white from settings
ColorLab color = new ColorLab(new Whitepoint(WhitepointName.D50)); //new Lab color with D50 reference white
ColorCMYK color = new ColorCMYK(new ICC("CMYKprofile.icc")); //CMY(K) colors have to have an ICC profile
To convert from one color to another, use the ColorConverter class. Note that if you use multithreading, each thread has to have its own instance of the
ColorConverter class!
ColorConverter Converter = new ColorConverter(); //create a new instance of a ColorConverter
ColorLab lab = new ColorLab(50, 12, -12); //create a Lab color
ColorRGB rgb = Converter.ToRGB(lab, RGBSpaceName.sRGB); //convert it to an RGB color in AdobeRGB colorspace
ColorConverter Converter = new ColorConverter(); //create a new instance of a ColorConverter
ColorRGB rgb = new ColorRGB(RGBSpaceName.AdobeRGB, 0, 0.5, 1); //create an RGB color
ColorLab lab = Converter.ToLab(rgb, WhitepointName.D50); //convert it to a Lab color with D50 reference white
ColorLab lab = Converter.ToLab(rgb); //or convert it to a Lab color with the default reference white
Converting with ICC profiles is a little bit different and may not work correctly yet. I couldn't test it thoroughly yet because of lack of different profiles and comparison with correct values. Nevertheless I add it here and if you find any mistakes/bugs, please report them to me.
ColorConverter Converter = new ColorConverter(); //create a new instance of a ColorConverter
ColorLab lab = new ColorLab(50, 12, -12); //create a Lab color
ColorRGB rgb = (ColorRGB)Converter.ToICC(lab, new ICC("profile.icc")); //convert a color with an ICC profile
And to find the difference between two colors, use the ColorDifference class (not multithreading safe)
ColorDifference
ColorLab lab1 = new ColorLab(0.5, 30, -12); //create the first Lab color
ColorLab lab2 = new ColorLab(0.5, 40, -2); //create the second Lab color
double difference = ColorDifference.GetDeltaE_CIEDE2000(lab1, lab2); //calculate the difference with CIE DE 2000 method
Or with the Din99c method:
ColorLCH99c din1 = new ColorLCH99c(50, 12, 120); //create the first DIN99c color
ColorLCH99c din2 = new ColorLCH99c(50, 16, 140); //create the second DIN99c color
double difference = ColorDifference.GetDeltaE_DIN99(din1, din2); //calculate the difference with the DIN99 method
For some methods you can also use GetDeltaC to get the
Chroma difference and with GetDeltaH you can get the Hue difference.
GetDeltaC
Chroma
GetDeltaH
For chromatic adaption, simply convert from one XYZ color to another:
ColorConverter Converter = new ColorConverter(); //create a new instance of a ColorConverter
ColorXYZ xyz = new ColorXYZ(new Whitepoint(WhitepointName.D50), 0, 0.5, 1); //create a XYZ color with D50 reference white
xyz = Converter.ToXYZ(xyz, WhitepointName.D65); //convert it to a XYZ color with a different reference white
If it's necessary to do chromatic adaption inbetween a conversion, say, from RGB to Lab, it is done automatically of course and you don't have to worry about it. I just wanted to mention that you can also do it explicitly.
Since version 3.0 there is also the namespace Light available. It contains a few colormodels that stores all values as either byte (8 bit - BColor) or ushorts(16 bit - UColor) and generally is more lightweight than the standard color classes. The lightweight classes are working like the normal classes and the ColorConverter class can be used for conversions, too.
Light
BColor
UColor
If you simply want to know how some color is represented in another colorspace you can use this GUI. Type in the values of your known color and press the "Convert" button
next to the boxes.
To compare two colors use this GUI to see the difference calculated in different ways. On the right side are the general settings. To calculate the difference, select and set the two colors you want to compare and click on "Compare". To set the values, select the channel and type the value in the textbox above. The results will be below. Delta E is the difference, Delta H is the Hue difference and Delta C is the Chroma difference.
To see how fast a conversion is, use this GUI. You can also see what difference multithreading makes. On the right side you can set the number of iterations and the general settings as well as the number of threads to use. Once you have set the colors like you want them, click on "Start" and wait for the result. The total time is the time it took for all iterations (in milliseconds) and the time per iteration is the average time it took for one conversion (in microseconds).
As already noted before, ICC profiles are still in alpha and haven't been tested thoroughly. If you know some stuff about ICC profiles and how the conversion with them works, I'd appreciate any help. And since it's not really finished yet, the conversion speed with ICC profiles is rather slow (compared to the normal conversion).
Well, learning how all those colorspaces work certainly broke my brain several times but now (I think) I understand it. So, if you have any questions on how anything from this stuff works, don't
hesitate to ask.
For future version I have planned:
This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)
customWP_XYZ
ColorConverter converter = new ColorConverter();
double[] customWP_XYZ = new double[] { 0.96422, 1, 0.82521 }; //replace values with your custom whitepoint XYZ values
Whitepoint customWP = new Whitepoint(customWP_XYZ);
ColorXYZ xyzIn = new ColorXYZ(customWP, 0, 0, 0);
ColorXYZ xyzOut;
for (int i = 0; i < 100; i++) //replace the loop with your own
{
xyzIn.X = 0; //set X value of image input here
xyzIn.Y = 0; //set Y value of image input here
xyzIn.Z = 0; //set Z value of image input here
xyzOut = converter.ToXYZ(xyzIn, WhitepointName.D65); //Chromatic adaption
}
|Xout| |Xin|
|Yout| = |M| * |Yin|
|Zout| |Zin|
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Articles/613798/Colorspaces-and-Conversions?msg=4601751 | CC-MAIN-2014-23 | refinedweb | 1,329 | 54.22 |
dmG728Encode(3dm) dmG728Encode(3dm)
dmG728Encode - implements the ITU (International Telecommunication Union)
Recommendation G.728 compression (LD-CELP).
#include <dmedia/dm_audioutil.h>
DMstatus dmG728Encode(DMG728encoder handle,
short *ibuf, unsigned char *obuf, int nsamples)
handle DMG728encoder structure, created by dmG728EncoderCreate(3dm),
specifies the signal processing parameters.
ibuf pointer to input sample data buffer. The data format is short
(16-bit). The samples are assumed to be two's complement. The
sampling rate must be 8 kHz.
obuf pointer to output data buffer. The data format is unsigned
char (8-bit). This bitstrem buffer must consist of a multiple
of 10 bytes.
nsamples number of samples in the input buffer to be processed. the
value of nsamples passed to the G.728 encode/decode routines
must always be a multiple of 40.
Returns DM_FAILURE or DM_SUCCESS.
dmG728Encode(3dm) implements the ITU Recommendation G.728 compression.
The uncompressed data sampling rate is 8000 Hz. And the compressed
bitrate is 16000 bits/s.
ITU Recommendation G.728 compression also uses a linear prediction
scheme. This means that the compressed bits, which carrying compressed
information, are interrelated or interdependent. If a application calls
afSeekFrame(3dm) to an offset into the compressed bit stream file and
then starts reading bits in the middle of the bit stream and decompress
them with dmG728Decode(3dm), the interdependency of the bits at the
cutting point is lost. The application will initially get back data with
a lower amplitude than if he had read the same data back during a
complete pass over the file from the beginning.
Page 1
dmG728Encode(3dm) dmG728Encode(3dm)
There is no way to exactly recreate the decoded data in the middle of the
bit stream file without going all the way back to the beginning.
However, with a "preroll" value to read ahead a portion of the compressed
file, application can compensate for the amplitude problem. We recommend
2 second "preroll".
G.728 algorithm was developed for sampling rate of 8 kHz.
dmG728EncoderCreate(3dm), dmG728EncoderDestroy(3dm), dmG728Decode(3dm),
ITU Recommendation G.728.
PPPPaaaaggggeeee 2222 | http://nixdoc.net/man-pages/IRIX/man3d/dmG728Encode.3d.html | CC-MAIN-2020-16 | refinedweb | 339 | 51.24 |
This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project.
The PowerPC64 Makefile variable "no-special-regs" uses the -ffixed-* directives to disable float and vector register (and thus vector scalar register) usage by the compiler for certain modules. GCC version 4.6 is more aggressive in emitting instructions from new instruction sets (like Altivec and VSX) for optimization. If it emits these instructions when there are no VRs or VSRs available the compiler will ICE. The following patch adds -mno-vsx and -mno-altivec to the "no-special-regs" variable to ensure that these instructions are not emitted when their corresponding register sets are explicitly disabled. I've checked this into my ibm-2.13 branch and I've verified that it can be cherry-picked into master with the following: git cherry-pick -x 4749a0058b27274a95c5a798e339c7299cdf890e Ryan S. Arnold IBM Linux Technology Center 2011-05-18 Ryan S. Arnold <rsa@us.ibm.com> * sysdeps/powerpc/powerpc64/Makefile (no-special-regs): Add -mno-vsx and -mno-altivec to prevent the compiler from using Altivec and/or VSX instructions when the corresponding registers are not available. diff --git a/sysdeps/powerpc/powerpc64/Makefile b/sysdeps/powerpc/powerpc64/Makefile index fe96aae..4d9be6c 100644 --- a/sysdeps/powerpc/powerpc64/Makefile +++ b/sysdeps/powerpc/powerpc64/Makefile @@ -12,7 +12,10 @@ endif # These flags prevent FPU or Altivec registers from being used, # for code called in contexts that is not allowed to touch those registers. -# Stupid GCC requires us to pass all these ridiculous switches. +# Stupid GCC requires us to pass all these ridiculous switches. We need to +# pass the -mno-* switches as well to prevent the compiler from attempting +# to emit altivec or vsx instructions, especially when the registers aren't +# available. no-special-regs := $(sort $(foreach n,40 41 50 51 60 61 62 63 \ $(foreach m,2 3 4 5 6 7 8 9, \ 3$m 4$m 5$m),\ @@ -20,7 +23,7 @@ no-special-regs := $(sort $(foreach n,40 41 50 51 60 61 62 63 \ $(sort $(foreach n,$(foreach m,0 1 2 3 4 5 6 7 8 9,\ $m 1$m 2$m) 30 31,\ -ffixed-v$n)) \ - -ffixed-vrsave -ffixed-vscr + -ffixed-vrsave -ffixed-vscr -mno-altivec -mno-vsx ifeq ($(subdir),csu) sysdep_routines += hp-timing | http://sourceware.org/ml/libc-alpha/2011-05/msg00055.html | CC-MAIN-2014-42 | refinedweb | 385 | 53 |
VSCode with activated ssh-agent on Windows 10
I want to use git from within VSCode, using my ssh-key. My current working fix is this:
- start Powershell
- run start-ssh-agent.cmd (of git installation)
- run code
This links the ssh agent or socket to VSCode, effectively allowing me to use the key for git commands.
How do turn this into a proper script? Or even better: How do I start and configure the ssh-agent automatically so it's globally available (similar to ssh-add on linux)?
See also questions close to this topic
- How to collaborate with poeple using Dropbox if I prefer to use Git (Github)?
Short question:
Is there tricks from
git, (or command-line/
Git-bash/
WSL_on_Windows), such that I will be hosting the git-repo locally, in wherever I prefer, and have only the real files synced two-ways between the local git-repo and a Dropbox folder?
Even shorter: is there a way to push from a local repo to a Git remote, and have the files stay "two-way-synced" to a Dropbox folder before and after the push?
At the end of the day, I would like to keep pushing to the remote git-repo as usual. I will push shortly after committing, and would prefer all file-contents from the two sources (the Dropbox folder and the local copy of the Git-repo) to stay synced before and after the commit-push activities. (I am less confident here as this may go against the philosophy of "staging" my works per each commit.)
Clarification: I do not intend to do anything fancy with Git. I prefer to keep working with the same branch, and to pull/push from/to the same Github repo as the remote. In particular, I will need to get things to work on multiple PCs and a Linux machine.
Unsuccessful attempts:
- First, I think it is a bad idea to initialize a git-repo inside the
~/Dropboxfolder, as it creates clutters and thereby, likely, conflicts.
- I have thought about creating a "Selective-sync" through the Dropbox GUI to simply exclude the
.gitfolder. Yet, without such
.gitfolder, it is unclear how to establish the local repo on all computers of mine (I do use multiple Windows PC and one more Linux box).
- I am not good at
symlink, and have been playing with it a good number of times but failed. If someone were to suggest it, please be precise. Also, I would need it to work across multiple Windows machines and Linux box. I am happy to add more details as long as I get a working demo from you.
Backgrounds
Thankfully, my collaborators has improved from the emailing habit of handing off drafts and work-in-progress through piles of zip-files. Nowadays, they are happy with a shared Dropbox folder. Yet, they haven't started to care too much about version control. Quotes from them: "Git on the command-line? It is a joke?" lol.
On the other hand, I have been happy with pushing to Github as my remote repo, and have been doing so for a good number of years. I am used to my git commands, and have devised the following
aliassettings to do so quickly.
alias ga='git add -A' alias gs='git status' alias gc='git commit -m' alias gp='git push' alias gpp='git pull'
I am looking for a way to use Git(Github) and Dropbox in harmony. And I am aware of the following knowledge:
- How to use
gitoccasionally when hosting everything on Dropbox ==> I am not a paid user of Dropbox, and my projects may easily overgrow my limit.
- Details on Git and Github
- Brilliant notes on using Dropbox as a Git (remote) repository
- Super convening marking material to pull people from Dropbox to Git (Github)
Among the three unsuccessful attempts on my end, I am inclined to believe some
symlinkcommand (or complicated scripts) will do the trick. Looking forward to further instruction from the community. I am tagging as many vision control
- gitignore pattern doesn't work without double stars
This pattern works properly:
**/Assets/Plugins/Editor/JetBrains*
But this pattern doesn't:
Assets/Plugins/Editor/JetBrains*
As far as I know, these two patterns are equivalent. What might be the problem here?
- git: Split existing repository into submodules
I only found answers on how to use git subtrees to split up a repository. However, I explicitly want submodules.
It's a Java maven project. Currently, everything is in one maven project and one repository. My goal is to achieve something like this:
The root repository should contain the main pom.xml, system documentation, etc Then there should be a few submodules, one for a utility library, one for the main application, and so on. The submodules are their own maven project, referenced from the main maven project in the root repository. The root repository will not contain any source code.
I could create everything new from current HEAD, but it is important to me that the commit history is kept as complete as possible.
-?
- Change the styling of function arguments in VS Code
I'm trying to edit the styling in my Visual Studio Code workspace and I don't know how to edit the styling of function arguments. I have found that you can style parameters (using textMateRules and
"scope" = "variable.parameter") but can't find anything on styling arguments (when calling the function as opposed to defining it.)
Hopefully someone could find me the textMateRules scope name or some other way of getting at it in VS Code settings. Thanks in advance!
- Python + Multiprocessing + VMware: Process Hangs
Trying to run a simple test script in a Linux VM in VMware Workstation 15, in VSCode. The script just hangs at the worker pool, 'results = p.map(f, chunk)'. Not sure if I missed something to have it run in a VM or Linux. Runs fine in windows.
import multiprocessing as mp import os import time def f(x): print('Doing: ' + str(x) + ' with process id:'+ str(os.getpid()) + '\n') return(x*x) def main(): start_time = time.time() id_list = range(100) chunksize = 2 lock = mp.Lock() p = mp.Pool(chunksize) for i in range(0, len(id_list), chunksize): print(i) if (i + chunksize) > len(id_list): chunk = id_list[i:] else: chunk = id_list[i : i + chunksize] results = p.map(f, chunk) for j in range(len(results)): lock.acquire() try: print('The results is: ' + str(results[j]) + '\n') finally: lock.release() p.close() end_time = time.time() print(end_time - start_time) if __name__ == "__main__": print("Starting") main() print("Done")
- Can't zoom out in visual studio code
I accidentally hit CTRL + = and my IDE is too much zoomed now. I tried the shortcut to zoom out as stated in the official vscode doc, (CTRL + -) but this is not working.
Some help would be appreciated.
Thanks,
- Credential Provider V2 Combobox unexpected behavior
I've been developing our company's credential provider for windows 10 for almost a year now.
Now, I encountered a problem. I don't usually ask questions on forums, blogs, because in most cases I find the solution, but this time I've been struggling with an issue for a month now and I found the root of the problem.
Brief description of the problem itself: The credential provider uses a combobox, which worked before without a problem. Now, I rewrote the whole code to manage a big update, but a strange bug got into the system. The bug only occurs at a specific scenario. I'm developing and testing the code on my personal laptop.
The scenario:
1) The laptop is plugged in to my monitor / power, etc.
2) I make it go sleep.
3) I unplug all cables (including power).
4) I wake it up from sleep.
Than, the combobox doesn't show a default selected item, it's empty. When I drop it down, it shows all the necessary items. Than the credprov crashes and restarts, than everything is fine.
I know, that in similar "strange" scenarios, in most of the cases, a memory leak or something related causes the problem. When I check the event viewer it shows me c0000005, which is access violation. I started to debug where the violation is. Than I found out that the program refers the combobox item list array (actually vector in my case) at a very very high index (out of range could be the reason for the violation). The actual index is obviously stored in the "selectedComboItemIndex" variable (DWORD).
I was curious when did it change to this strange number, than I found an unexpected behavior. The SetComboBoxSelectedValue method randomly gets called once (when the bug happens) with an insanely high index value. I don't even call this method in my code, so I have no idea, why does it get called. The call happens even when I don't drop down the combobox.
I give it a chance that it could be a bug in the credprov itself. What do you think? Have you seen this problem before?
Thank you in advance!
- Regex: Search particular diacritics and replace it in particular tag with ASCII (notepad++)
I have many html lines with words that contains
ădiacritic such as:
creatăoare, singură, acasă, etc. from the tag
<p class="text_obisnuit"></p>
I want to find all those
ădiacritics from that tag, ant to replace it in ASCII with
ă
I made a regex, but the "replace" doesn't work.
- Matlab 2013b 32 bit, error while installing mcr_install_win32, invalid code lenghts set
I'm trying to install Matlab 2013b 32 bit (I need this precise version) with accademic license on my laptop with Windows 10 (64 bit), but when I try to install it, it stops (at 60% more or less) and it says "Extract error - The following error was detected while installing mcr_install_win32: invalid code lenghts set ". I tryed many other times to re-install it but I have the same problem, and I have no idea how can I solve it. I don't know if this info can be useful, but before I tried to install Matlab 2013b 32 bit, I had Matlab 2015 32 bit, and Matlab 2018b 64 bit, and I did not have any problem with these 2 versions (and of course I unistalled these 2 versions and I deleted the folders where were located Matlab files, before trying to install Matlab 2013b 32 bit following the instructions written here: ).
Please don't tell me to change Matlab version (it's not a decision of mine to use this precise version), and please try to explain in a simple and specific way. Any help and advice will be very appreciate. Thanks in advance.
Screen of the error during Matlab 2013b 32 bit installation as described above
- ssh-add in docker - Could not open a connection to your authentication agent
I am trying to create a docker image for my Python flask API.
I need git to install dependencies and I have already installed git in docker few times. But here, I cannot understand what I'm doing wrong.
With the docker:
FROM python:3.6-slim ARG ssh_prv_key ARG ssh_pub_key RUN apt-get update && \ apt-get install -y openssh-server &&\ && \ echo "StrictHostKeyChecking no " > /root/.ssh/config RUN eval "$(ssh-agent -s)" RUN ssh-add /root/.ssh/id_rsa" ]
I execute the command:
docker build --build-arg ssh_prv_key=.keys/id_rsa --build-arg ssh_pub_key=.keys/id_rsa.pub -t my-api -f Dockerfile .
Which gives me the error below:
Step 7/16 : RUN eval "$(ssh-agent -s)" ---> Running in be450cc39533 Agent pid 9 Removing intermediate container be450cc39533 ---> fb101226dc5f Step 8/16 : RUN ssh-add /root/.ssh/id_rsa ---> Running in 4288e93db584 Could not open a connection to your authentication agent. The command '/bin/sh -c ssh-add /root/.ssh/id_rsa' returned a non-zero code: 2
A PID is retrieved by the eval function for the ssh-agent but I cannot connect to it.
SOLVED
I finally found what I was doing wrong. First of all, my build args wasn't correct. The correct docker build command is as follow:
docker build --build-arg ssh_prv_key="$(cat .keys/id_rsa)" --build-arg ssh_pub_key="$(cat .keys/id_rsa.pub)" -t my-api -f Dockerfile .
Also, and I don't know why, git handle correctly my ssh keys without usage of
RUN eval "$(ssh-agent -s)" RUN ssh-add /root/.ssh/id_rsa
The commands above resulting into an could not connect to your agent error.
Then, the right file is
FROM python:3.6-slim ARG ssh_prv_key ARG ssh_pub_key RUN apt-get update && \" ]
- Deploy with Jenkins into CentOS 7.5 using pipeline script
I need help with pipeline jenkins deploy, I try to deploy a Java webapps from jenkins into CentOS, I always have this error :
FATAL: [ssh-agent] Could not find specified credentials
[ssh-agent] Looking for ssh-agent implementation...
[ssh-agent] FATAL: Could not find a suitable ssh-agent provider
[ssh-agent] Diagnostic report
[Pipeline] // sshagent
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
java.lang.RuntimeException: [ssh-agent] Could not find a suitable ssh-agent provider.
Thanks
- Git Bash asks for SSH passphrase on first run after every PC reboot
Every time I start up Git Bash after restarting my Windows 10 PC it asks me for the passphrase for my SSH key.
I didn't used to have this problem, and I've never seen it anywhere else; I use Git Bash at work and have never seen this problem there.
Initializing new SSH agent... succeeded Enter passphrase for /c/Users/User/.ssh/id_rsa:
If I close the Git Bash window and open a new one, the new window doesn't prompt me for a passphrase. Nor will any subsequent window. It doesn't seem to matter whether I enter a passphrase in the first window or not.
However, if I restart, the first Git Bash window will again prompt me for a passphrase.
I've tried uninstalling and reinstalling Git. I've also tried running
ssh-add -k path/to/key. Neither approach worked. | http://quabr.com/53294395/vscode-with-activated-ssh-agent-on-windows-10 | CC-MAIN-2018-51 | refinedweb | 2,349 | 63.59 |
Free for PREMIUM members
Submit
Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium
#include <wchar.h>
#include <malloc.h>
#include <locale.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
_wsetlocale(LC_ALL, L"arabic");
const char* text = "Arabic text";
wchar_t* p = (wchar_t*)malloc(200);
p[0] = 0;
mbstowcs(p, text, 200);
_wsetlocale(LC_ALL, L"");
free(p);
return 0;
}
Select all
Open in new window
Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.
Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.
A2T depends on the project settings: if there is Unicode character set selected, this A2T will convert the text to the wide characters.
Windows likes only Unicode (or their version of Unicode). Better to keep all translations/localization in Unicode and do not play with these A2W, mbstowcs, MultiByteToWideChar,...
Open in new window
Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.
the encode that come from internet page have windows-1256 encoding
pgnatyuk:
i used in the properties of the project unicode
Anyway A2T is not a solution. You can try to use your A2T with #pragma setlocale("arabic"), but I don't think it will be an acceptable solution for you.
Ok, that seems to imply the narrow encoding is ANSI not UTF8 so I would follow what pgnatyuk is suggesting.
Just because something is wide does not mean it is Unicode. Just because something is narrow don't mean it is not Unicode!
UTF8 and UTF16 are both Unicode transformation formats and both represent Unicode, the former is narrow and the latter is wide.
hen Microsoft speak of Unicode they are referring to UTF16 and when they speak of non-Unicode they are (usually) referring to ANSI. If you want to convert from narrow to wide you MUST know what the encoding of the narrow form is otherwise your conversion will not behave as you expect. This was the reason for my original question.
This is slightly off topic but I get very vexed at how Microsoft confuse people with their redefinition of terminology! :)
This multibyte character set from Microsoft is totally useless. They can rename it in simplified English. :)
i used setlocal
but it still not ok you can see the image to see the problem in arabic text
thank you
asas.png
If you already took one line, why you cannot apply wcstombs?
How I see it should be something like
_wsetlocale(LC_ALL, L"arabic");
TCHAR* urlcnw = (wchar_t*)malloc(1024);
urlcnw[0] = 0;
mbstowcs(urlscnw, urlcn, 1000);
Do not forget to delete this urlcnw when you will not need it. It is correct for your code with A2T too.
At least this system font used in the VS debugger can show the Arabic text. | https://www.experts-exchange.com/questions/26414400/when-i-use-this-function-in-c-the-text-have-arbic-it-destroied.html | CC-MAIN-2018-05 | refinedweb | 498 | 65.01 |
Most of you, like myself, have been watching the release of VS 2008 from its beta versions. I have already explored some features of Silverlight; as seen here.
From the perspective of this article Microsoft added generics, query operators and LINQ support. I always wondered why LINQ was added when the world was comfortable with ADO programming with its support extended to objects and XML too (and similarly, the use of generics/aggregations etc. in C # 3.0). This question created the purpose of this article. This article seeks to compare existing approaches with the new ones released with C# 3.0 and LINQ. As the scope of comparison is quite large, I will restrict our discussion to:
Before we jump into this article, I want to point out that there are many ways to accomplish a task programmatically. An effort has been made to write the best code possible, though, there are extra lines introduced so to make the comparison for writing LINQ and ADO functions more fair. As the code is shareware you are free to improve and build on it. The basic unit of measurement is counting the ticks which have been used in this article ( System.StopWatch). Each piece of performance code has been run 500 times so as to get the best performance values. Wherever possible I have added code to dispose/garbage collect objects. All the code explained in this article is available for download. The code is commented wherever required. Finally, all the performance values are added to an Excel file Graphs.xls and visually shown by Excel graphs.
System.StopWatch
Logic for running the function 500 times is given below
The configuration used for getting the current performance data is given below
If you are not familiar with LINQ, new features of C# 3.0 please read the following URLs
Function used for ADO is ADOInserting() in RetrieveUsingADO.sln. The LINQ counterpart of the same is LINQInserting() in RetriveUsingLINQ.sln.
ADOInserting()
LINQInserting()
Function used for ADO is ADOInsertingDirect() in RetrieveUsingADO.sln. The corresponding LINQ function is LINQInsertingDirect() in RetriveUsingLINQ.sln.
ADOInsertingDirect()
LINQInsertingDirect().
ADOReading()
LINQReading()
Function used for ADO is xmlReading() in RetrieveUsingADO.sln. The corresponding LINQ function is LinQXmlRead() in RetriveUsingLinQ.sln. These functions first read an XML file, then apply a filter in them (pass values > 250 in this case) and then add all the values of the first column.
xmlReading()
LinQXmlRead()
Function used for LINQ part is LinQObjects1(), for the traditional C# part is csharpObjects1() and for the C# 3.0 part is LINQObjects2() in RetriveUsingLINQ.sln.
LinQObjects1()
csharpObjects1()
LINQObjects.
LINQQueryDataset()
ADODataSetQuery()
I have referenced the median value rather then the mean to help reduce the effect of outliers in the graph because in a Windows OS there are always more processes running and spikes in the graph do not necessarily mean a fault in the code.
double sum = nums.Aggregate(delegate(double Cursum, double curNum)
{
if (curNum % 2 == 0)
{
return (Cursum + (curNum * curNum));
} else
{
return (Cursum + 0);
}
});
LINQObj1
temp%2 == 0
var getSquaresLessthen500 = from temp in nums where temp == newFunction(temp) select temp*temp; are better in LINQ, the read operation is superior in ADO. XML operations are by and large the same (not too much of a difference) and object access is basically depending on the type used a scope of improvement in each scenario, but since I have timed all the operations, this will give us better insights when we design or architect. | http://www.codeproject.com/Articles/26431/Performance-Comparisons-LINQ-to-SQL-ADO-C?fid=1355921&df=10000&mpp=50&sort=Position&spc=Relaxed&tid=2593671 | CC-MAIN-2014-52 | refinedweb | 576 | 54.42 |
Folks, is it possible to extract the IP address and MAC address of a VM managed by BSA ?
Thanks in advance.
Do you want to get these details for all the machines provisioned by BSA? Or just managed by BSA?
You could check these blcli commands:
ProvisionDevice : listAllPMDevices
ProvisionDevice : listAllImportedDevices
The details for these are on the blcli help.Also see
If you browse into the hypervisor object that hosts the guest in bsa you should be a be able to see this. this also may be possible w/ some blcli commands from the Virtualization namespace.
Marking thread as Answered. Please edit if issue is not resolved. | https://communities.bmc.com/message/245439 | CC-MAIN-2015-40 | refinedweb | 107 | 67.96 |
0
Hey whoever was good enough to take a look at this thread I have to stress I am a complete noob!
I picked up "Java programming for the complete beginner" five days ago and here I am with 50% less hair and stuck on a challenge at the end of chapter 2!:sad:
My problem is the sparse table in the book re String class methods.All I have is a page with 17 methods and a brief description,no worked examples etc.
Here is the code I've been trying to compile for two days,in its latest re-jig.
echo" /*Letters.java*/ /*I'm trying to create a program that capitalises the first letter of the user-defined input and parses the rest to lower case then adds a "." at the end(Java Programming for complete beginners pg 69 challenge 4)*/ import java.io.*; public class Letters { public static void main(String args[]) { String value = "", carA = "", restA = "";//strings loaded BufferedReader reader; reader = new BufferedReader(new InputStreamReader(System.in)); //the usual try { System.out.println("Please type a word :\t"); value = reader.readLine(); } catch(IOException ioe) { System.out.println("IO ERROR"); } carA = value; value = value.charAt(0);//these lines are my problem according to javac restA = carA.substring(1);//"found char, required java.lang.String" System.out.println(carA.toUpperCase() + restA.toLowerCase() + "."); } }"; | https://www.daniweb.com/programming/software-development/threads/63488/anyone-mind-helping-out-a-stuck-noob | CC-MAIN-2017-26 | refinedweb | 224 | 57.87 |
I am trying to convert an Open Core from Verilog to VHDL, doing this I converted one to one modules then cheked them till code work by step.
After last packet conversion, (transmit logic) I seen a strange behaviour, If condition then .. elsif (not true)
execute elsif statement also if not true, is this correct and am wrong interpreting if syntax or quartus version s wrong?
I am observing a lot of strange errant on my IP cores...
packet type is this case (LA checked) UDP, so it must respond 0x11:
this code load paket data with val x11
if Local_IsARP = '1' then Local_pkt_data<= HostMAC(39 downto 32); -- ARP else if SendPacketType = IPPKT_ICMPReply then Local_pkt_data<= 8x"01"; -- ICMP Reply else Local_pkt_data<= 8x"11"; -- ICMP/UDP/TCP end if; end if;
this code load paket data with val 01
if Local_IsARP = '1' then Local_pkt_data<= HostMAC(39 downto 32); -- ARP elsif SendPacketType = IPPKT_ICMPReply then Local_pkt_data<= 8x"01"; -- ICMP Reply else Local_pkt_data<= 8x"11"; -- ICMP/UDP/TCP end if;
Packet type is set to UDP or 01
constants are here:
--- *** ***** **** **** *** *** *** ------------- -- USAGE -- --- *** ***** **** **** *** *** *** ------------- --library work; --use work.package_ipconstants.all; --- *** ***** **** **** *** *** *** ------------- library ieee; use ieee.std_logic_1164.all; -- Package Declaration Section package package_ipconstants is -- constant c_PIXELS : integer := 65536; -- Packet Types constant IPPKT_Unknown : Std_logic_vector(2 downto 0) := 3x"0"; constant IPPKT_UDP : Std_logic_vector(2 downto 0) := 3x"1"; constant IPPKT_ARPReq : Std_logic_vector(2 downto 0) := 3x"2"; constant IPPKT_ARPReply : Std_logic_vector(2 downto 0) := 3x"3"; constant IPPKT_ICMPReq : Std_logic_vector(2 downto 0) := 3x"4"; constant IPPKT_ICMPReply : Std_logic_vector(2 downto 0) := 3x"5"; -- constant IPPKT_new : Std_logic_vector(3 downto 0) := 3x"0"; --// Commands constant IPPKT_CmdDone : Std_logic_vector(7 downto 0) := 8x"0"; constant IPPKT_CmdStatus : Std_logic_vector(7 downto 0) := 8x"1"; constant IPPKT_CmdLEDCtrl : Std_logic_vector(7 downto 0) := 8x"2"; constant IPPKT_CmdSetConfig : Std_logic_vector(7 downto 0) := 8x"3"; constant IPPKT_CmdSwChanged : Std_logic_vector(7 downto 0) := 8x"4"; constant IPPKT_CmdDataEcho : Std_logic_vector(7 downto 0) := 8x"5";
regards
Roberto
Link Copied
missing LA Image
about this I can save and post on Saleae LA file format, it is huge so I do it on demand.
Regards
Roberto
Try to compile your design and simulate it in Modelsim. This way, you can see if the code is written in the correct way.
Thank for answer, I spent a lot of time to figure what was wrong, this is a long long time ago flash about.. Hmmm A competitor rewrote old Unix workstation code with M$ tools .. COde was creating a lot of similar mess, input where output and signal not coherent. At last solved with some hack then changed CPLD firm on mass production... They rewrote their tool M$ free.
Why "try" to compile? On release 15.0 of Quartus every IP core was fine, new Linux version are slower.
Current 18.1 Release compile fine, then and elsif selector are both false but result are as elsif true.. Is LRM no more valid or i was wrong for a long time?
I never try see windows version, TOOO SLOW and unreliable.
if elsif elsif end if seems as it is ok.
if elsif else endif seems errant.
TO avoid this I changed structure to nested or case selection.
I cannot rewrite all IP core if this is a tool failure.
I MUST rewrite if I am wrong.
So which one s the offending?
LRM section 8.7 If statement
An if statement selects for execution one or none of the enclosed sequences of statements, depending on the value of one or more corresponding conditions.
if_statement ::=
[ if_label : ]
if condition then
sequence_of_statements
{ elsif condition then
sequence_of_statements }
[ else
sequence_of_statements ]
end if [ if_label ] ;
If a label appears at the end of an if statement, it must repeat the if label.
For the execution of an if statement, the condition specified after if,and any conditions specified after elsif, are evaluated in succession(treating a final else as elsif TRUE then) until one evaluates to TRUE or all conditions are evaluated and yield FALSE. If one condition evaluates to TRUE, then the corresponding sequence of statements is executed; otherwise, none of the sequences of statements is executed.
Best regards.
Roberto
Can you create a snippet of code with the design that able to compile? Attached the design.qar here so that I can look into it and get back to you. A simple design will do since it only involve ifelse statement.
code now is compiled removing elsif, old file still is on HDD, this is an Ethernet 10Base T module, now it is working, as I wrote.
Where can you host my code? This run on proprietary board with RJ45 magnetics and protection, normally is not used on Ethernet but proprietary biphase manchester at higher speed, this is not shareable.
This module got addressed to have a direct fast debug tools due to reduced pin count on device and consquently trouble to use internal/external Logic Analyzer.
The two code snippet on top are the trouble, it generate packet identifier, it is an UDP but is treated as ICMP reply.
Constants are for sure set to 1 not 5, development board has a lot of free pin where I connected the LA probe, Saleae has limit on decoding Manchester when more than 3 input get used but I used Agilent too and I confirm the trouble.
Code where it fail is a rudimental state machine driven by a counter, counter work, using original Verilog module it work, using new pathced module work.
Please give me some time to review old errant module to be compiled on and I send. I have to leave office now, I return back in two hour then I try post code and some images of board, one board is closed, the other can be freely shared with schematics too.
How large can be attached file? I am not ready now to publish back on Open IP Core.
Regards.
Roberto
Its fine, you can send the design using email. One things is that can you check what is your VHDL version that you were using? Are you using VHDL 2008?
The settings is in assignment -> settings -> compiler settings -> VHDL input | https://community.intel.com/t5/Intel-Quartus-Prime-Software/Is-quot-If-elsif-else-quot-in-this-case-errant/td-p/641869 | CC-MAIN-2021-39 | refinedweb | 1,010 | 60.35 |
In a previous tutorial, we talked about creating an express project using Typescript. It had some of the default routing features built into express and we were able to return JSON from different user requests. In this tutorial, we’ll rewrite that but will Typescript controllers. There is an awesome package called ‘routing-controllers‘ that helps to add this functionality to express. Please click here if you want to gain access to Typescript videos and ExpressJS courses.
Typescript Model
In the previous tutorial, we created a model called User. We were able to serialize this Model to JSON and display it when hitting our ‘/users’ route. We’re going to make a modification to that model and add an id field. It’ll be optional.
export default class User { id?: number; username: String; name: String; email: String; constructor(name: String, username: String, email: String, id?: number) { this.id = id; this.name = name; this.username = username; this.email = email; } getUsername() { return this.username; } getName() { return this.name; } }
Adding Typescript Dependencies
The next step is to add the necessary dependencies to our project. We will add routing-controllers and reflect-metadata. Reflect-metadata allows us to use decorators in our typescript class and add augmented features to a class, it’s properties and it’s methods.
npm install --save reflect-metadata routing-controllers
We’ll also modify our server file to add routing-controllers.
import express from "express"; import bodyParser from "body-parser"; import "reflect-metadata"; import { useExpressServer } from "routing-controllers"; import { UserController } from './controllers/user'; const server = express(); server.use(bodyParser.json()); server.use(bodyParser.urlencoded({ extended: true })); useExpressServer(server, { // register created express server in routing-controllers controllers: [UserController] // and configure it the way you need (controllers, validation, etc.) }); server.listen(3000, function () { console.log('Example app listening on port 3000!') });
You’ll see that I import UserController and place it in a controllers array.
Creating A Typescript Controller
To make sure that we can run REST requests, we’ll also need to create our UserController.ts file. Inside of that file, import routing-controllers as well as its decorators.
import { JsonController, OnUndefined, Param, Body, Get, Post, Put, Delete } from "routing-controllers";
You can see that JsonController specifies that a class is a controller that returns JSON. You also have decorators for the common HTTP requests and another decorator for what to do is an object is undefined and to get an error.
Once that is done, you can create your controller with all of you CRUD methods. There is a mock data store in this example to simulate some of these functions.
import { JsonController, OnUndefined, Param, Body, Get, Post, Put, Delete } from "routing-controllers"; import User from '../models/user'; @JsonController() export class UserController { userStore: User[]; constructor() { this.userStore = [ new User("James Coonce", "jcoonce", "james@none.com", 1), new User("Jim Coonce", "jimcoonce", "jim@none.com", 2), new User("Norman", "jcoonce", "norman@none.com", 3) ]; } @Get("/users") getAll() { return this.userStore; } @Get("/users/:id") @OnUndefined(404) getOne(@Param("id") id: number) { let users = [ new User("James Coonce", "jcoonce", "james@none.com", 1), new User("Jim Coonce", "jimcoonce", "jim@none.com", 2), new User("Norman", "jcoonce", "norman@none.com", 3) ]; let user = users.find(x => x.id === id); return user; } @Post("/users") post(@Body() user: any) { const newUser = new User(user.name, user.username, user.email); return newUser; } @Put("/users/:id") put(@Param("id") id: number, @Body() user: any) { let currentUser = this.userStore.find(x => x.id === id); if (currentUser != undefined) { currentUser.name = user.name; currentUser.username = user.username; currentUser.email = user.email; return currentUser; } return "No user found"; } @Delete("/users/:id") remove(@Param("id") id: number) { return "Removing user..."; } }
Rest Typescript Node.JS Controller
Conclusion
Adding simple controller functionality to Typescript and ExpressJS is simple. You can use packages like routing-controllers or even frameworks like NestJS to build out more structured applications. Click here for more information as well as video courses on Node.JS development. | https://codebrains.io/express-typescript-routing-controllers/ | CC-MAIN-2019-51 | refinedweb | 656 | 51.75 |
Varsnap
Project description
Varsnap Python
Installation
Install from PyPI -
pip install varsnap
Requirements
The client depends on three environment variables to be set:
VARSNAP- Should be either
trueor
false. Varsnap will be disabled if the variable is anything other than
true.
ENV- If set to
development, the client will receive events from production. If set to
production, the client will emit events.
VARSNAP_PRODUCER_TOKEN- Only clients with this token may emit production snapshots. Copied from
VARSNAP_CONSUMER_TOKEN- Only clients with this token may emit development snapshots. Copied from
Usage
Add the varsnap decorator in front of any function you'd like to make better:
from varsnap import varsnap @varsnap def example(args, **kwargs): return 'output'
Testing
With the proper environment variables set, in a test file, add
import unittest from varsnap import test class TestIntegration(unittest.TestCase): def test_varsnap(self): matches, logs = test() if matches is None: raise unittest.case.SkipTest('No Snaps found') self.assertTrue(matches, logs)
Troubleshooting
Decorators changing function names
Using decorators may change the name of functions. In order to not confuse
varsnap, set the decorated function's
__qualname__ to the original
__qualname__:
def decorator(func): def decorated(*args, **kwargs): func(*args, **kwargs) decorated.__qualname__ = func.__qualname__ return decorated
Publishing
pip install twine python setup.py sdist bdist_wheel twine upload dist/*
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/varsnap/ | CC-MAIN-2021-04 | refinedweb | 242 | 55.24 |
> I think it would be nice to have the pixmap hard-coded (option?)
> as the .xpm files are already in C syntax, that would solve
> the above problem in a natural way (IMHO) without using the
> 'data' functions (???).
The function fl_set_pixmapbutton_data() does what you want. I'm not
sure I understand why using it would be a somehow "unnatural" act.
The usage is as follows:
#include "some_pixmap.xpm"
[...]
fl_set_pixmapbutton_data( pixmap_button, some_pixmap );
assuming, of course, the standard construction of the include file
`some_pixmap.xpm'.
There are analogous functions for the other Pixmap objects.
> So, did I do something wrong? ...
Not read the manual carefully enough, perhaps? :-)
Actually, not really.
The manual should probably not assume that the reader has made the
inference that "unsigned char **bits" refers to the array of an Xpm
pixmap. While reference to the demo code is probably a Good Thing,
it's not always easilty available to J. Random Application Programmer.
spl
_________________________________________________
To unsubscribe, send the message "unsubscribe" to
xforms-request@bob.usuf2.usuhs.mil or see
Xforms Home Page:
List Archive: | http://xforms-toolkit.org/old-archive/1997/1347.html | CC-MAIN-2022-05 | refinedweb | 177 | 68.67 |
This post walks through creating a very simple Flask app using the factory pattern. It then creates a simple health check controller in a Blueprint by using Test Driven Development with pytest. At the end of this post, you have an extremely simple webserver with complete test coverage!
The Topics:
- Flask Factory Pattern
- Docstrings
- Type Annotations
- Test Driven Development
- pytest
- Flask Blueprints
Flask Factory Pattern
The entirety of Flask is centered around the
Flask app object, the first thing you have to do to start using Flask is to create one of these objects somewhere in your project. There are two common methods for doing this that you'll see in tutorials:
Create the object in a file (usually called "app.py") which will later be imported by whatever server is serving it. The primary benefit to this method is that there is less boilerplate and you can get up and running quickly, thus why it's a popular choice for tutorials.
Declare a "factory method" which returns an instance of an app. This method requires a bit more typing, but has a lot of benefits:
- Delay imports by putting them in the factory method to avoid circular dependencies (very important when you start using extensions)
- Delay initialization of extensions (makes patching easier for unit tests)
- Allows you to dynamically configure the app for different use-cases (e.g. testing vs development vs production)
- Many more, check out the docs here
I always recommend using the factory method, it's pretty easy to get started. First, create the method itself in the base
__init__.py for your module.
# python_rest/__init__.py from flask import Flask def create_app(): return Flask(__name__)
That's all the code there is for declaring the app! Now we just need to run it with the Flask development server.
Running on the command line
We can easily run the app with Poetry on the command line, but first we have to tell Flask what to run. Luckily, it comes with built in support for environment files which let us declare all sorts of stuff. First, add
python-dotenv as a development dependency.
$ poetry add -D python-dotenv
Now create a file in the root of the project called ".flaskenv" which sets the environment variable "FLASK_APP" to the name of your module.
Note: The Flask recommendation is to check the ".flaskenv" file into the project with any non-sensitive, default values. You can then override them with the more standard ".env" file which should never be checked into source control.
# .flaskenv FLASK_APP=python_rest
Now you're ready to run the development server. Make sure you run it under Poetry!
$ poetry run flask run
Running in PyCharm
- At the top of the screen, click "Add Configuration"
- Click the "+"
- Choose "Flask server"
- Set "Target type" to "Module name"
- Set "Target" to your module name (e.g. "python_rest")
- Click "OK"
- With your new configuration selected, click the green arrow to start running
🎉 Hooray! You now have a webserver running on port 5000 (by default) of your local machine! It doesn't do anything yet, but I promise it's running.
Docstrings
Now that you've written a Python function, you should definitely write a docstring for that function. The reasons to document your code are endless, I find it best practice to give every function a docstring with at very least a couple word summary. Docstrings will be important later on for creating good documentation for your API, so it's best to get in the habit right off.
There are a bunch of formats out there for docstrings, most are supported by and can be rendered in PyCharm. This page gives a nice overview of the different formats. I use ReStructuredText strings just because they're natively supported by Sphinx which I use in other types of projects. They look something like this:
def create_app(): """ Creates an application instance to run :return: A Flask object """ return Flask(__name__)
Type Annotations
I cannot stress how important I think type annotations are. Python's dynamic typing system is awesome and makes writing code very fast. However, it can easily lead you to making simple mistakes as your project becomes more complex. I type hint all the things so that PyCharm can tell me when I'm doing something dumb (like forgetting a return somewhere) and so a static analysis tool (like mypy) can catch some common bugs. The type annotation for our
create_app function looks like this:
def create_app() -> Flask:
Test Driven Development
Test Driven Development, or TDD, is very simply the act of writing tests for your code before you write the code itself. There are entire books written on why this is a good idea, but very simply, this is why I do it:
- You always know when you're done
- You can refactor with more confidence
- Helps you to think through edge cases and unhappy paths before you start
- Encourages modular and decoupled designs
Pytest
In order to write tests, you need to use some sort of framework. There is one included in the Python standard library called "Unittest" but I much prefer pytest. There are a bunch of reasons to use it but the basics are:
- Very little boilerplate
- Loads of community plugins
One of the aforementioned plugins that I always use while testing Flask apps is pytest-flask which provides a bunch of useful fixtures. To get started with testing, install both pytest and pytest-flask as development dependencies.
$ poetry add -D pytest pytest-flask
Now, if you're using PyCharm, you'll want to configure it to use pytest
- Open Preferences
- Click Tools
- Go to Python Integrated Tools
- Change "Default test runner" to "pytest"
Note: you can change Docstring format here too
Next, create the configuration file for pytest (called conftest.py) in the tests dir. This file is always imported before tests are run and it's where you'll want to define any fixtures you intend on using and perform any other pre-test setup. To use pytest-flask, we have to define an "app" fixture which returns an instance of our
Flask object.
# tests/conftest.py import pytest from flask import Flask @pytest.fixture def app() -> Flask: """ Provides an instance of our Flask app """ from python_rest import create_app return create_app()
Blueprints
Now it's time to create an endpoint that we can hit. A very common practice is to have some sort of health check endpoint to verify that your application is running. In order to create this endpoint, we'll need to create a controller (the function which handles the request) which will be registered to a blueprint (a collection of controllers under a path) which will in turn be registered to our app object.
First, let's figure out where to put this new code. I like to keep any blueprints I create in a module called "blueprints" under the main module. This blueprint will be for managing the root path ("/") so I'll put it in a file called "root.py" under the "blueprints" module.
Next, we should mirror this directory structure in the tests directory by creating "tests/test_blueprints/test_root.py". Along with the appropriate
__init__.py files, the whole project structure should now look like this:
python-rest |-- README.md |-- poetry.lock |-- pyproject.toml |-- python_rest | |-- __init__.py | `-- blueprints | |-- __init__.py | `-- root.py `-- tests |-- conftest.py `-- test_blueprints |-- __init__.py `-- test_root.py
Let's write the test for the endpoint we're about to create. We can use the client fixture provided by pytest-flask to execute the request appropriately. We'll want the health check to return a status of 200 (OK) with some JSON body. Here's the test:
# tests/test_blueprints/test_root.py from http import HTTPStatus def test_health(client): response = client.get('/health/') assert response.status_code == HTTPStatus.OK, 'Health check failed' assert response.json == {'message': 'Healthy'}, 'Improper response'
Note that those assert statements are the things that will cause the test to pass or fail when run. The string after the comma after the assert is the message that will be displayed if the check fails. Run the test either by clicking the little green arrow next to the function definition in PyCharm, or by running
poetry run pytest on the command line. Either way, you should see it fail.
Now let's create the root blueprint and the actual endpoint.
# python_rest/blueprints/root.py from flask import Blueprint # Declare the blueprint with whatever name you want to give it root_blueprint = Blueprint('root', __name__) # This is how you register a controller, it accepts OPTIONS and GET methods by default @root_blueprint.route('/health/') def health(): return {'message': 'Healthy'} # This will return as JSON by default with a 200 status code
Now we need a way to register this blueprint to the app so we can actually reach the controller. They way to do this is with a function called at app creation which registers the blueprint to the app. The convention is to name this function "init_app", and I like to have one "init_app" function which registers all blueprints at once. The logical thing is to put this function in the
__init__.py of the blueprints module.
# python_rest/blueprints/__init__.py from flask import Flask def init_app(app: Flask): from .root import root_blueprint app.register_blueprint(root_blueprint)
Now you just need to call this function from your create_app factory function.
# python_rest/__init__.py from flask import Flask def create_app() -> Flask: """ Creates an application instance to run :return: A Flask object """ app = Flask(__name__) from . import blueprints blueprints.init_app(app) return app
That's it! If you run the test again it should now pass! You can also run the flask app, then navigate to
localhost:5000/health/ in your browser to see your JSON response.
Posted on by:
Dylan Anthony
Backend Dev obsessed with security
Discussion | https://dev.to/dbanty/python-rest-api-flask-basics-3ffn | CC-MAIN-2020-40 | refinedweb | 1,638 | 70.94 |
Aug 15, 2019 05:07 PM|fmrock164|LINK
So my EDMX has roughly 60-70 tables/stored procs. The first time I load my application after it is published to the server its slow. Once that section has been viewed once.. the application is much faster.
I found this link and added this to my solution.
public class MyDbConfiguration : DbConfiguration { public MyDbConfiguration() : base() { var path = Path.GetDirectoryName(this.GetType().Assembly.Location); SetModelStore(new DefaultDbModelStore(path)); } }
However, it still seems slow and I feel like I am missing a step. What has everyone else done? All my google searches point back to this same type of solution.
Contributor
3781 Points
Aug 16, 2019 12:05 AM|DA924|LINK
Contributor
3650 Points
Aug 16, 2019 02:44 AM|Yuki Tao|LINK
Hi fmrock164,
It seems that only this method is currently being promoted.
What is your EF version?
I suggest to use EF 6.2,you can use a Model Cache which loads a prebuilt edmx when using code first;
If is earlier version,here are three suggestions mentioned in this post:
If you still feel very slow,I suggest you could find the reason by F12 performance or optimize sql algorithm, and optimize query statement...
Best Regards.
Yuki Tao
Star
9461 Points
Sep 02, 2019 09:05 AM|Brando ZWZ|LINK
Hi fmrock164,
As far as I know, the model cache which loads a prebuilt edmx when using code first not database first.
If you want to speed up Entity Framework, I suggest you could refer to below ways:
1.Turn off the LazyLoading (EDMX => right click the UI => properties => Lazy Loading Enabled set it to false)
2.Split your Edmx into many smaller, only include the ones you need in your page.
Best Regards,
Brando
4 replies
Last post Sep 02, 2019 09:05 AM by Brando ZWZ | https://forums.asp.net/t/2158801.aspx?Entity+Framework+Slow+first+query | CC-MAIN-2019-39 | refinedweb | 308 | 64.1 |
Details
- Type:
New Feature
- Status: Closed
- Priority:
Minor
- Resolution: Fixed
- Affects Version/s: None
-
- Component/s: Client, regionserver
- Labels:None
- Hadoop Flags:Reviewed
Description
HBASE-1845 introduced MultiGet and other cross-row/cross-region batch operations. We should add a way to do that with increments.
Issue Links
- is related to
HBASE-2946 Increment multiple columns in a row at once
- Closed
Activity
- All
- Work Log
- History
- Activity
- Transitions
Changes Increment to implement Row and adds the check for instanceof Increment in HRS.multi
Will work on a unit test and javadoc additions/cleanup.
(Partial) dup of
HBASE-2814? HBASE-2814 seems to only be about thrift. This is to make Increment a Row operation so it can be used with the existing MultiAction stuff.
@Jon: Are you still working on this? Patch looks good to me and we have recently found some need for this.
I'm happy to commit, unless there's opposition.
Not working on it but no reason not to commit that I recall.
Cool... I'll add a test.
While I am at it, I am also going to this for Append.
Patch for trunk, includes changes for Append and a test.
79 new Findbugs (version 1.3.9) warnings.
+1 release audit. The applied patch does not increase the total number of release audit warnings.
-1 core tests. The patch failed these unit tests:
org.apache.hadoop.hbase.regionserver.wal.TestLogRolling.
I ran the four failing tests locally and they all pass.
I would like to commit this today (the change itself is pretty uncontentious I think).
Any objections?
Is this safe to do Lars?
-public class Increment implements Writable { +public class Increment implements Row {
Should you leave Writable in place?
Else LGTM
Good point... I just checked, and Row extends WritableComparable, which in turn extends Writable... So should be good.
Maybe than Append can be simplified to only implement Row and not also Writable.
Patch that I committed (based on Stack's comment Append does not actually need to implement Writable, since Row already extends Writable).
Thanks for the review Stack!
Integrated in HBase-TRUNK #2612
Integrated in HBase-TRUNK-security #65
Most of what needs to be done is (trivially) make Increment implement Row. | https://issues.apache.org/jira/browse/HBASE-2947 | CC-MAIN-2017-22 | refinedweb | 372 | 68.26 |
fuse-d 0.5.0
A D binding for libfuse
To use this package, run the following command in your project's root directory: fused/fuse.d for implementation specific details.
To mount a filesystem use a Fuse object and call mount:
import fused fuse.d fuse.d,.
- Registered by Sebastiaan de Schaetzen
- 0.5.0 released 5 months ago
- seeseemelk/fuse-d
- github.com/facebook/dfuse
- BSL-1.0
- Authors:
-
- Dependencies:
- none
- Versions:
- Show all 3 versions
- Download Stats:
0 downloads today
0 downloads this week
1 downloads this month
15 downloads total
- Score:
- 0.6
- Short URL:
- fuse-d.dub.pm | http://code.dlang.org/packages/fuse-d | CC-MAIN-2019-35 | refinedweb | 103 | 59.6 |
conn, ife, sop & try
conn, ife, sop & try
Oh, weird
language, isn't it.
These are the code templates I use
most often.
A code template is a nice feature of
JDeveloper.
You type a shortcut, eg try, followed by the
CTRL+Enter key combination and the equivalent template code
is added in the source editor,
at the point where your cursor was.
It
will also bring any associated imports.
For example,
typing conn in the source editor followed by the
CTRL+Enter key combination will add the following code:
String username = "scott";and the following imports:
String password = "tiger";
String thinConn = "jdbc:oracle:thin:@localhost:1521:ORCL";
DriverManager.registerDriver(new OracleDriver());
Connection conn = DriverManager.getConnection(thinConn,username,password);
conn.setAutoCommit(false);
return conn;
import java.sql.*;
import oracle.jdbc.OracleDriver;
I think it's worth you have a look at all the avalable shortcuts:
select menu Tools --> Preferences..., expand Code Editor and click Code Templates.
You can see there the shortcuts with a small description.
Selecting any shortcut displays the code as shown in the followin picture:
I had never defined my own template before, but I'll certainly do, after having read Frank's post in his blog:
How to automatically add the class name and creation date to a Java file
Frank explains there how you can create your own template, and take advantage of variables (new in JDeveloper 10.1.3).
In his example, a variable $file$ will automatically get assigned the name of the Class and $date$ the current date.
By googling, I see that Steve also explained How to Create a Code Template for JSTL Choose.
Great ! | http://blogs.oracle.com/Didier/2006/06/17/ | crawl-002 | refinedweb | 273 | 53.51 |
I would file a bug on the GHC bug tracker: You will need to use the guest login to trac, though (in grey text at the bottom of the page). I've also CCed the GHC-users list, as there are folks over there that might have knowledge of the concurrency libraries. Take care, Antoine On Sat, Jan 1, 2011 at 7:03 PM, Eric Stansifer <eric.stansifer+haskell at gmail.com> wrote: > Hi, > > I didn't get a response to my question on haskell-cafe, perhaps > libraries is a more appropriate place to ask. > > > doc: > source: > > The isEmptySampleVar function, > > isEmptySampleVar :: SampleVar a -> IO Bool > isEmptySampleVar (SampleVar svar) = do > (readers, _) <- readMVar svar > return (readers == 0) > > returns False whenever readers < 0. However, readers < 0 occurs when > there are threads waiting on an empty SampleVar. > > The documentation on SampleVar is a bit sparse on explaining the > intended behavior; I wouldn't have expected this behavior if I hadn't > read the source. Can someone clarify the semantics of SampleVar? > > For a contrived example, consider > > > do_something = threadDelay 100000 -- 100 ms > > produce, consume :: SampleVar Int -> IO () > produce svar = do > do_something > b <- isEmptySampleVar svar > if b then randomIO >>= writeSampleVar svar else return () > produce svar > > consume svar = do > x <- readSampleVar svar > print x > consume svar > > main = do > svar <- newEmptySampleVar > forkIO $ produce svar > forkIO $ consume svar > threadDelay 1000000 -- one second > > This code deadlocks instead of printing random numbers. > > Thanks, > Eric > > _______________________________________________ > Libraries mailing list > Libraries at haskell.org > > | http://www.haskell.org/pipermail/libraries/2011-January/015452.html | CC-MAIN-2013-48 | refinedweb | 242 | 50.16 |
The XBee module is one of the most popular wireless platforms around. It allows data to be passed over the air to another device hundreds of feet away. addresses.
What is XBee?
Before we start tinkering with the wireless kit, let us introduce you to the XBee. The XBee Module was created by Digi International and is primarily used as a radio communication transceiver and receiver. It is a mesh communication protocol that sits on top of the IEEE 802.15.4 ZigBee standard. XBee supports peer-to-peer as well as point-to-multipoint network communications wirelessly with a speed of 250 kbit/s.
Required Hardware
- Sparkfun XBee Wireless Kit (includes XBee shield, XBee Explorer USB, and 2 XBee modules)
- Jumper Cables
- Soldering Iron
- SCTU
- Computer
To use your XBee Shield with an Arduino, you'll need to solder in some stackable headers.
You will need to solder stackable headers onto your XBee.
XBee Shield LED Indicators
The XBee shield has five LEDs connected to a pin on the XBee which indicates the different operations on the shield. You should be familiar with what each indicator means, this can be very useful when debugging later on. The table below will guide you through each operation the LED indicates:
The DIO5 LED should blink once the XBee is paired with a compatible device. This also happens when you first connect your XBee modules. The RSSI LED, on the other hand, will shine brighter once the paired XBee is nearer indicating a stronger signal strength.
The RSSI LED.
Plugging your XBee to the Shield
At first, plugging the XBee to the shield can be quite confusing especially without proper markings. Luckily, the shield has some white silkscreen to help orient your XBee as you're plugging it in. The XBee's two diagonal edges should match with the two diagonal lines on the PCB. Now your XBee is all set.
How your XBee will look on top of the shield.
Starting with XCTU
XCTU is a free multi-platform application with an easy-to-use graphical interface designed for developers working with Digi RF modules. It is equipped with new tools that make it easy to set-up, configure, and test XBee® RF modules.
Once XCTU is done installing, open it. You'll see this window:
The homepage of XCTU.
Make sure you've plugged an XBee (correctly) into your Explorer before, and have the Explorer plugged into your computer.
Now we are ready to add your XBee(s). To add, click the add device icon in the upper-left portion of the window.
The add device window in XCTU.
Click the new module button and wait a few seconds as XCTU reads the configuration settings of your XBee. You should then be presented with the entire configuration of your XBee.
The full configuration of XBee on XCTU.
There are a lot of configurable settings listed, but for now, use the following listed below:
- Channel = C
- PAN ID = 3332
- DH = 0
- DL = 0
- MY = 0
If you have changes in the settings that you want to have written on your device, just change the values and click on the pencil symbol beside it. Now you are ready to test your connection.
Software Serial Passthrough
Here is a sample sketch we'll use to create communication between your Arduino's serial monitor and another XBee using XCTU.
#include <SoftwareSerial.h> SoftwareSerial XBee(2, 3); void setup() { XBee.begin(9600); Serial.begin(9600); } void loop() { if (Serial.available()) { XBee.write(Serial.read()); } if (XBee.available()) { Serial.write(XBee.read()); } }
What You Should See
After you've uploaded the code, verify everything is working by following these steps:
- Open the Arduino's Serial Monitor. Make sure the baud rate is set to 9600.
- On your XCTU and click over to console mode. Also click the plug icon to close the serial connection with the radio module.
- Type something in the console view, it should show up on the Serial Monitor.
- Now try typing something into the Arduino's Serial Monitor (and press "Send"), it should show up in the console view.
- Yay!
A successful XBee sample sketch!
Now you are ready to do a variety of projects using an XBee Module with your Arduino! | https://maker.pro/arduino/tutorial/interfacing-xbee-module-with-arduino | CC-MAIN-2020-40 | refinedweb | 710 | 65.12 |
Technical Support
On-Line Manuals
CARM User's Guide
Discontinued
#include <math.h>
double modf (
double val, /* value to calculate modulo for */
double *ip); /* integer portion of modulo */
The modf function splits the floating-point number
val into integer and fractional components. The
fractional part of val is returned as a signed floating-point number.
The integer part is stored as a floating-point number at ip.
The modf function returns the signed fractional part of
val.
#include <math.h>
#include <stdio.h> /* for printf */
void tst_modf (void) {
float x;
float int_part, frc_part;
x = 123.456;
frc_part = modf (x, &int_part);
printf ("%f = %f + %f\n", x, int_part,frc. | http://www.keil.com/support/man/docs/ca/ca_modf.htm | CC-MAIN-2020-16 | refinedweb | 108 | 59.19 |
I'm happy
Post your Comment
J2ME Form Class
J2ME Form Class
In this J2ME Extends Form example, we are going to discuss
about form... that is appended in this form using append method.
Syntax of J2ME Form Class File name
login form
login form sir my next form consists logout button when i click on it it showing login form but next form window is not closing but the components prepsent in that form are getting clearedup using frameobject.setVisible(false
registration form
;p>public class CreateUser extends HttpServlet {</p>
<pre class...=null;%></p>
<pre class="prettyprint"><% connection.../javascript">
function valid()
{</p>
<pre class="prettyprint">
form
form Can I prevent a form from being submitted again
disable the form - JSP-Servlet
are different.when I click the form button,one function is calling and the input values(only one input value is going to servlet) are going to servlet class using Ajax. after response is coming to the jsp page,particular form button
login form - JSP-Servlet
login form Q no.1:- Creat a login form in servlets? Hi Friend,
Try the following code:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Login extends HttpServlet
Design of java form
Design of java form sir
can u plz help me i want to design a interactive java form mins some thing diffrent in form is it possible in java if yes... java.awt.event.*;
class CreateAccount extends JFrame{
JTextField
convert this html form to jsp
convert this html form to jsp <html>
<head>
<script...;
<td valign="top" align="center" bgcolor="#2a5865"><font class...;/tr>
<form name="VillageDetailsForm" action="AddVillage.jsp" method
Developing Forgot Password Form
Developing Forgot Password Form
... Form code for our application.
Developing Forgot Password Form
The forgot password form will be used, when user forgot their password. This
form
Form processing using Bean
to each field in the form. The class fields must have
"setters"... the data entered in form, we define a Java class with fields "username"...Form processing using Bean
In this section, we will create a JSP form using
Login Form in SWT
Login Form in SWT
This section illustrates you how to create Login Form.
To create a login form in SWT, the Label class set the labels User
Name and Password and Text
HTML form validation using jquery
HTML form validation using jquery Is there any way for validating html elements common under a class by giving its class name in jquery validation code..that means validating all elements by using its class name if those
Simple Form Controller Example
Example of using Simple Form Controller
Page 2
In this page we... it at Example of using Simple Form Controller
Step 7:
Now we will create a UserValidator.java class inside the project src folder
to validate
Form validation Using Jquery Plugin
<div class="form-row"><span class...;/div>
<div class="form-row"><span class="label">E-Mail *<...;
<div class="form-row"><span class="label">URL</span><input
Simple Form Controlle Example
Simple Form Controlle Example
... provides SimpleFromController for control a form data in the web
application. If you want to handle form in spring then you need to use
SimpleFormController
Creating Canvas Form Example
Creating Canvas Form Example
This example shows that how to use the Canvas Class in a Form. In this example
we take two field in which integer number passed from the form
JSF form tag
JSF form tag
This tag renders html form element which contains the
data that is submitted with the form. This tag uses "POST" method. The
components under the particular
Login Form in Java - Java Beginners
*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
class Form...Login Form in Java Hi,
In my Project, I am using Java-JDBC-Mysql...)
How to create frontage form in java to validate it.
regards,
Prashant
Example of HashMap class in java
Example of HashMap class in java.
The HashMap is a class in java collection framwork. It stores values in the
form of key/value pair. It is not synchronized
how to featch data form db?
;
</a>
<div class="search" <form class="form-search">
<div class="input-append">...;
<form id="fbForm2" class="form-horizontal cmxform" name
HTML form example
HTML form example
In this section we will develop HTML form example and show you how to
performance form validation using JavaScript.
The HTML <form>...; HTML Form Example </title>
<script type="text/javascript">
Struts 2.1.8 Login Form
Struts 2.1.8 Login Form
In this section we will learn how we can create form based application...
easily.
After completing this session you will be able to develop form based
SWT login form - Swing AWT
SWT login form Hi,
I want code to create a login form in SWT.
My...*;
public class LoginForm {
Display display = new Display();
Shell shell...(2, false));
shell.setText("Login form");
label1=new Label(shell
Login Form
for a
login form using struts.
UserLoginAction Class: When you download Login... generated by Action
Class or Action Form.
Action Form returns ActionErrors and Action Class returns errors
saved in the form
JSP error: class UserForm not found in class model.UserAction
JSP error: class UserForm not found in class model.UserAction etting... org.apache.struts.actions.IncludeAction;
public class UserAction extends DispatchAction
{
private... mapping, ActionForm form,
HttpServletRequest request
Simple Form in Java
Simple Form in Java
... a form by using various java component. In this
section, you will learn how... on the
frame). These are explained as follows:
Panel: This is the class of Java Awt
registration form using oop concept
registration form using oop concept I would like to write a program student registration form at kindergartens and display the information of students that register to the kindergarten. How to make the form and display
operating system phoneBobo May 14, 2012 at 5:34 PM
I'm happy
Post your Comment | http://www.roseindia.net/discussion/22713-J2ME-Form-Class.html | CC-MAIN-2015-48 | refinedweb | 984 | 64.51 |
ConnectDetach(), ConnectDetach_r()
Break a connection between a process and a channel
Synopsis:
#include <sys/neutrino.h> int ConnectDetach( int coid ); int ConnectDetach_r( int coid );
Since:
BlackBerry 10.0.0 a client thread is SEND-blocked on the connection (e.g., it's called MsgSend(), but the server hasn't received the message), the send fails and returns with an error.
- If a client thread is REPLY-blocked on the connection (e.g., it's called MsgSend(), and the server received the message), the kernel sends an unblock pulse to the server..
Classification:
Last modified: 2014-06-24
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/c/connectdetach.html | CC-MAIN-2017-17 | refinedweb | 113 | 60.31 |
Hello,
I have a requirement to prepare quantitaive analysis at BPC 10.0 NW.
Q1. As in BEx Query Designer we create a structure node with restriction of Multiple hierarchy, same can be achieved in BPC 10 ?
Eg. My Sales Revenue Node is depend on two hierarchy 1. G/L Account and 2. Profit Center. So in BEx we were creating on Selection Node and restricting Amount field with both Hierarchy nodes. Same Can I replication at BPC 10 ?
Q. 2 Can BPC 10 support BEx Query ?
Thanks,
Gaurav
Hi Gaurav,
BEx query cannot be directly executed on BPC cubes. BPC exposes its data through virtual provider. Check "Use as Source of Data", by selecting the model and clicking the Edit button in admin console. Once this is done the virtual provider is created in BPC namespace. Please refer note 1730125 for details.
Regards,
Kalyan.
Help to improve this answer by adding a comment
If you have a different answer for this question, then please use the Your Answer form at the bottom of the page instead.
Add a comment | https://answers.sap.com/questions/10253572/can-bpc-100-support-bex-query.html | CC-MAIN-2020-50 | refinedweb | 180 | 75.5 |
Type: Posts; User: AlanGRutter
Hi gurus,
I have a web site that uses the AJAX Control Toolkit v3.020820.28853 and master pages. Everything works absolutely perfectly on my development machine, however when I deploy the site to...
I believe it should get picked up by the garbage collection.
Personally, IMHO, I believe responsibility for closing the FileStream lies within the scope of the object that created it. If used on a...
What you are doing is multicasting which requires a UDP connection and special IP address ranges. I suggest you start with a Google search for UDP multicast and see what turns up.
Regards
Alan
The linker is telling you that your function is defined twice in different object modules.
It has already encountered a publicly visible function body for CallbackProc that takes two longs as...
An ABC acts solely as a base class for inherited classes. You cannot instantiate an ABC - you must instantiate one of the derived classes using new and assign it to a pointer to the base ABC.
...
Is your code running server side or client side?
ASP.NET 2.0 ?
I'm not very familiar with this stuff but on client-side don't you just need to get the element by id (getElementById) and then set...
You could use the strtok() function to split up your line into tokens.
Regards
Alan
Here's my attempt - took me about 1 hour
//Narrative: This is a program that -
// 1) reads in the number of salespeople
// 2) reads in the name of the salesperson
// 3) reads the quota for...
This is different to what you originally posted and is why I couldn't make any sense of the statement you did provide. It is still ambiguous
2 times first minus z
is that
(2 * first) - z
...
When you type a message, the toolbar has a 'Code' icon - if you click it it pops up a box showing HTML style tags. Use these around any code that you post and it will keep the formatting - you can...
Submit or attach your full code.
a)
int FunctionOne(int x, int y)
{
return (x > y) ? (x + y) : (x - (2*y));
}
b) Item 5 makes no sense to me. Whose previous value? Did you mean z greater than twice value of x?
Post your whole code - otherwise no-one can see exactly what you're doing.
Regards
Alan
You will not get many replies if you don't use code tags. Also post your whole code and any sample data you are using.
Just create a loop (either a for or a while) for the number of salespersons...
I have a couple of questions which may help you get some replies
1) Which order are the bits in the file in (Little Endian or Big Endian) ?
2) You ask 'What am I doing wrong?', yet you provide no...
1. You need to use the array form of delete
delete [] addrs;
since you declared an array. You should also have a copy constructor.
2. There's nothing wrong with the declaration - you...
Well you haven't searched around much on the net then since in less than 1 minute I've found loads of resources on debugging.
Try this one for starters
Visual Studio Debugging
As Paul said...
I have been programming for at least 25 years and in all that time I can honestly say I have never ever used a goto statement. I've always found a cleaner way.
If you were working for me and you...
cin is for 'C++'. The poster said originally that it's a 'C' assignment.
As it says in the KB article, the include file you require can be found in the DDK (Driver Development Kit) in the following location \Ddk\Src\Storage\Inc
So you need to get a copy of the DDK from...
Are you saying you replaced
char st[]; by
char *st;
You haven't allocated any memory for the variable - you need to do this in both cases. I think you are lucky in the first case.
Try
Exterminator - the below description is what I was hinting at
Regards
Alan
What is being said about alignment is true however you generally do not need to specifically pad out your data structures so that they align on word boundaries as the compiler will do this for you.
...
AFAIK you can't initialise static members inside the class. You need to have
class Movie
{
...
static Graph actorGraph;
}
Your macro is turning MIN into 7;
#define statements do not ordinarily end in a semi-colon. Additionaly your main should return something.
The correct code is
#include <iostream>
#include... | http://forums.codeguru.com/search.php?s=0824e9ef79dbcc90d5620bdf4f1d14c6&searchid=7941515 | CC-MAIN-2015-40 | refinedweb | 776 | 73.47 |
Web Parts and Caching
Web Part developers can use the Web Part cache to store property values and to expedite data retrieval. Values are stored in the Web Part cache on a per-part or per-user basis by specifying the storage type in the call to the PartCacheRead and PartCacheWrite methods.
You can determine the type of cache to use—either the SharePoint database or the ASP .NET Cache object—by the setting of the WebPartCache element in the web.config file. Possible settings follow:
- None disables caching.
- Database uses the SharePoint database.
- CacheObject uses the ASP.NET Cache object (the default).
For example, to use the SharePoint database for caching, create the following web.config file entry:
<SharePoint> <WebPartCache Storage="Database"/> </SharePoint>
Cache details
You use the PartCacheWrite and PartCacheRead methods of the WebPart class to manage caching, and the PartCacheInvalidate method to invalidate part or all of the Web Part cache (for example, if a property changes on the Web Part). To obtain information about the cache type at run-time, use the CacheType property.
A key is used to find cache entries, allowing an arbitrary number of name-value pairs to be stored.
Note Cached data may not be available on subsequent invocations of the Web Part, as the system can expunge values from the cache at any time.
During cache storage in in the database, the following occurs:
- If parts are not personalized, Personal cache entries (a call to the PartCacheWrite method with storage set to Storage.personal) are not stored.
- If parts are Personal (added to the page in personal view), the Shared and Personal cache entries are stored in the same place. If the PartCacheInvalidate method is called with a storage value of Shared or Personal, all the cache is cleared.
When using the database for storage, both the Shared and Personal cache are limited to 2 MB. If this limit is exceeded, no error is displayed, but the cache entry will be lost. Additionally, if the storage type is Personal, it is charged against the user's quota.
Any object placed in the database cache must be marked as serializable (System.SerializableAttribute).
ASP.NET also provides caching functionality that the Web Part can use through the Cache object.
Caches stored using ASP.NET are limited by the size allowed by the Cache object. For more information about the Cache class, see the System.Web.Caching namespace.
Note Static Web Parts can only use caching if WebPartCacheStorage is set to CacheObject. No exception is raised if the setting is Database, but no cache entry is stored. Changes to the .aspx file cause the Web Part cache to get purged for static Web Parts.
For more information about the WebPartStorage attribute, see Web Part Storage. | http://msdn.microsoft.com/en-us/library/dd585600.aspx | CC-MAIN-2014-52 | refinedweb | 461 | 64.91 |
#
>>
how to mock http client c#
“how to mock http client c#” Code Answer
how to mock http client c#
csharp by
Upvote answer :-)
on Mar 13 2022
Comment
0
//To really understand please read source blog // //>() );
Source:
gingter.org
Add a Grepper Answer
C# answers related to “how to mock http client c#”
https request c#
c# make request to rest api
httpclient soap request c#
how to mock abstract httpcontext using moq .net core
adding values to mock IHttpContextAccessor unit test .net core
mock async method c# reutrnd
simple code to call rest api c#
ioptions mock c# unittest
how to controller request in c#
HttpWebRequest C# example
make http request c#
simple http request c#
C# queries related to “how to mock http client c#”
c# mock http response
how to mock httpclient in c#
mock http request c#
createclient c# mock http
mock httpclient methods c# example
how to mock rest client c#
c# mock http response message
httpclient mock c#
Browse C# Answers by Framework
Unity
More “Kinda” Related C# Answers
View All C# Answers »
but dotnet-ef does not exist.
dotnet install ef
dotnet ef install global
asp.net data annotations email
ms crm set state request dynamics 365 set state request
vb.net yes no cancel
ngrok for asp.net core
asp.net validate web.config
net core get remote ip
blazor get current url
The term 'Scaffold-DbContext' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again
visual studio reinstall all nuget packages
check version of asp.net core
check dotnet version command line
adb get android version
restclient basic auth c#
how get url in laravel
Retrieve url path
laravel get current url
url()- full() laravel
asp.net core get request ip address
The name 'JsonConvert' does not exist in the current context
asp.net core .gitignore
how to get the startup path in console app
get request url in asp.net core
urlreferrer in asp.net core
Publishing A Single EXE File In.NET Core
laravel route redirect
usermanager change password without current password
The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" could not be located.
reinstalar dependencias net core
Reinstalar packetes net core
serilog loglevel order
serilog log level hierarchy
get host ip address asp.net core
In Asp.Net Core core how to I get the web site's IP address?
easily start admin process from service c#
setup authorize in swagger .net core
how to solve error CS0619: 'GUIText' is obsolete: 'GUIText has been removed. Use UI.Text instead.'
c# debug console log
.net core Enable-Migrations' is not recognized as the name of a cmdlet
prettier isnt working c#
prettier c#
prettier inst working c#
error CS0619: 'GUITexture' is obsolete: 'GUITexture has been removed. Use UI.Image instead.'
.net core System.InvalidOperationException: No service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' has been registered
solution to fizzbuzz c#
fizzbuzz c#
fizzbuzz in c#
how to do fizzbuzz in c#
c# fizzbuzz
solve fizzbuz c#
c# System.Resources.MissingManifestResourceException error
asp.net core redirecttoaction with parameters
No IUserTwoFactorTokenProvider<TUser> named 'Default' is registered.'
c# socket bind to localhost
c# ipaddress from localhost
c# ip address translate localhost
dotnet dev-certs https --clean
headless chromedriver C#
this site can’t be reachedlocalhost unexpectedly closed the connection. .net framework
how to update a project to cross target .net core
dynamics 365 update record c#
Set value into lookup field in console app using dynamic CRM 365
read configuration workerservice
core Request.CreateResponse
.NET Microsoft.dotnet-httprepl
Considerando um projeto C# e o uso do Entity Framework, após realizar uma alteração em um registro, qual o método que deve ser chamado para salvar as
C# socket bind to dns name
how check if variable is send to page or not in laravwel
Transfer Ownership photon2
why vue cli do not refresh auto in local host
dyncmics 365 setstate request
fair division
application server types in .net
ef core dbfirst
generate model from database entity framework
asp.net core entity framework database first
ef database first generate models entity framework core
Entity framework Sql connection string for windows authentication
Scaffold-DbContext
net core 5.0 create model from database
scaffold-dbcontext sql server
how to generate entities from an existing database in entityframework core
db scaffolding ef core
c# close all threads application exit
protected override void OnExiting(Object sender, EventArgs args) { base.OnExiting(sender, args); Environment.Exit(Environment.ExitCode); }
No migrations configuration type was found in the assembly
Get Hard disk serial Number
InvalidOperationException: Calling Scene Raisefrom assembly reloading callbacks are not supported.
an entry with the same key already exists asp net
bower azure repository tag
Request.ServerVariables["HTTP_X_FORWARDED_FOR"] get only one ipaddress
ensuresuccessstatuscode exception
asp.net throw unauthorized exception
iactionresult
how to set progress openedge driver name for odbc connection c#
typeahead causing validation error asp
asp.net core can't load custom values from appsettings.json
error provider c#
tests not showing in test explorer
get web config key value in c# razor view
c# connect to mongodb
c# mongodb connection
redirect to another controller page in asp.net core
unityWebRequest get returned data
how create another new app file in laravel
c# request run as administrator
The name 'JObject' does not exist in the current context
httpclient jwt token c#
swagger authentication bearer .net core
meta keywords tag mvc .net core
ldap check user exists
unity vscode launch.json
defaultconnection appsettings.json
.net core add header to soap request
js invoke async function blazor
valid url in .net
asp core asp for not working
add tag helpers asp.net core in viewimports
scaffold db ef core
asp.net core identity get user id
artisan command in route
Animator.GotoState: State could not be found UnityEngine.Animator:Play (string)
Animator.GotoState: State could not be found
uuid generator asp.net
dotnet build to exe
net.core "a path base can only be configured using iapplicationbuilder.usepathbase()"
csharp check if env is development
c# entity framework code first connection string
C# HttpClient POST request
how to configure session timeout in asp.net core
.net core check if user is logged in'.
mvc list to jsonresult
remove session in dotnet core
fluentassertions force exceptions
http error 502.5 asp.net core 2.2
Attribute [livewire] does not exist.
Unable to resolve service for type 'Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole]' while attempting to activate 'PathApp.Controllers.SearchPathController'.
{"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."}
dotnet ef migrations to folder
rb.addforce c#
httppostedfilebase in .net core 3.1
initialize ConsoleLoggerProvider in EF core
https port
No context type was found in the assembly
no context type was found in the assembly enable-migrations
increase timeout in .net core web app
NET Framework 4.7.1 or a later update is already installed on this computer.
how to deal with ERESOLVE unable to resolve dependency tree
asp.net 5 iis HTTP Error 500.19 - Internal Server Error
ajax asp.net core
get connectionstring from web config c#
asp.net core 3.1 ajax partial view
c# how to get connection string from app config
how to redirect to extern page in .net core
No context type was found in the assembly 'AuthenticationApp'.
razor confirm password validation
connection string in asp.net with username and password
c# read authorization header
monodevelop ubuntu 20.04
add dependency injection .net core console app
c# make request to rest api
ef core set identity_insert off
httpclient soap request c#
.net framework get configuration value from web.config
Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager
swaggergen add service not getting info in .net core
no entity framework provider found for the ado.net provider with invariant name
dotnet new project
defaultrequestheaders.authorization basic auth
httpcontext.current.session null c# in class library
database update dotnet
Net.ServicePointManager.SecurityProtocol .net framework 4
blazor swagger setup
asp.net core get root url in view
https request c#
calling stored procedure in c# entity framework
The server requested authentication method unknown to the client
dotnet core update migration on startup
RelayCommand
c# connect tcp
c# consuming post rest service
WebClient c# with custom user agent
Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'
dotnet ef database update connection string
'Using a Hub instance not created by the HubPipeline is unsupported.'
change dot net core web api routing
asp.net core 3.1 routing
dotnet call webapi
dotnet new api
httpcontext in .net standard
failed to read the request form. missing content-type boundary .net core
deserialize object to dictionary c#
como usar a função SelectToken em vb net
razor can't refresh pages without restarting project
asp.net model
upgrade asp.net core to 5.0
.net core check if linux
fluent api
where to write fluent api
System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger`1
c# webrequest cookies
dota2
dotnet core 3.1 get the user that just logged in
dotnet automapper.extensions.microsoft.dependencyinjection
c# .net core memory cache
swagger skip endpoint .net core
Run C# project in VS Code
.net framework with vscode
simple code to call rest api c#
get appsettings from app.config c# .net core
how to get previous page url aspnet core
check if internet is connected with c# winforms
socket io connect to namespace
how to install jdk on linux manjaro
.net get system environment variable
an existing connection was forcibly closed by the remote host. .net core
basic auth swagger .net core 5
authentication and authorization in asp.net c# with example
missingpluginexception (missingpluginexception(no implementation found for method firebase#initializecore on channel plugins.flutter.io/firebase_core)
.net core web app get dll name
speedtest.net cli
qwertyuiopasdfghjklzxcvbnm
qwerty
vb.net console log
c# signalr console app client example
bundle.config in mvc is missing
mvc write to console
the request was aborted could not create ssl/tls secure channel. c# restsharp
get controller name from ActionExecutingContext .net 4.x
.net core identity get user id
msbuild publish to folder command line .net
.net core authorizationhandlercontext
.net console arguments
how get the user show mvc controller core 3.1
encrypt with public key and decrypt with private key c#
asp.net core mvc jsonresult example
adding values to mock IHttpContextAccessor unit test .net core
aspx import namespace
jenga db connection
linq to json
mvc session key exists
adding a dependency injection service in windows forms app
published net core did not have wwwroot
enable cors asp.net mvc
c# use api rest
webclient c# example post
asp.net core get previouse url
integer required asp.net core
dotnet build command
get processor id c# web application
route( controller ) c#
deploy .net core
password regex asp.net
Entity Framework Core 3.1 Return value (int) from stored procedure
useinmemorydatabase not found c#
Metadata publishing for this service is currently disabled
how to reload app.config file at runtime in c#
Install Mono project on Ubuntu 20.04
c# .net 3.5 post json httpclient
set the page that FormsAuthentication.RedirectFromLoginPage redirects to
C# redirecttoaction with area
asp.net core mvc redirecttoaction area
exception handling in c# web api
ef core include
how to pass id from view to controller in asp.net core
The terminal process failed to launch: Path to shell executable "dotnet" is not a file or a symlink.
how to write web service for API in c#
System.Data.Entity.Core.EntityException: The underlying provider failed on Open
get ad user using email address microsoft graph C#
Failed to generate swagger file. Error dotnet swagger tofile --serializeasv2 --output
asp net mvc 5 return view from another controller
asp.net core miniprofiler
vscode snippet custom
custom vs code snippet
custom vscode snippet
how to use buildcontext in initstate flutter
asp.net core api Self referencing loop detected for property
how to disable device guard or credential guard vmware
Plugging a Third-Party IoC Container (e.g. AutoFac) into .NET Core 6
autofac asp.net core 6
autofac .net core 6
autfac .net 6
.net 6 autofac
.net core 6 autofac
asp.net core 6 autofac
how to use curl in asp.net c#
mvc refresh page from controller
405 - HTTP verb used to access this page is not allowed
mysql: [warning] using a password on the command line interface can be insecure.
while coding c# i get the error : "Duplicate 'global::System.Runtime.Versioning.TargetFrameworkAttribute' attribute [first_better_project]"
.net core change localhost port
serilog asp.net 5
remove header visual studio android
get android model adb
.net json result status code not working
pubxml environment variables
.Net Core Bundling & minification 02 : .net core The name 'Scripts' does not exist in the current context
ASP.NET Core using of ValidationScriptsPartial
aspx receive variable from url
give an alias in model .net
asp net saber ip address of client machine IIS
map user to ConnectionId SignalR
ASP.net ApplicationUser referance not found
c# caractère cacher mot de passe
c# windows service .net core
Could not load file or assembly 'Ubiety.Dns.Core, Version=2.2.1.0
c# centos Regex Username
c# allowedusernamecharacters
EventSource Web API C#
httpclient
Send Hotmail/Outlook Email C# (Win/ASP.NET)
asp.net core authorization default policy
Send Hotmail, Outlook, Office365 Email using SMTP C# .NET
cache trong mvc
How to create a Blazor server-side application in command prompt
net user add ne user windows 10
generate entity model dot net core
verifyusertokenasync password reset token
cdn providers
encrypt password easiest way in web app .net
httpclient getstringasync
How to create a Blazor client-side application in a command-line interface
How to decode Microsoft Local token in service
ActionExecutingContext result response return
c# change language version to 9.0
vb.net windows version check
xamarin check if ios or android
web client ignore ssl error
Response.Redirect cannot be called in a Page callback
Replaced OS is obselete
install nuget package for S3
how to mock http client c#
C# BCrypt
dotnet core encryption and decryption
HTTP Error 500.35 - ASP.NET Core does not support multiple apps in the same app pool
KeyValuePair is default
kube dashboard expose access port
serilog .net 6
query parameters sending to controller action asp.net core
JavaScriptSerializer() and convert to base64
NewtonSoft get base64 string
how to make rabbitmq start and stop base on c# services
Severity Code Description Project File Line Suppression State Error MSB3021
c# httpclient post no content
disable version header c#
install active directory windows server 2019 powershell
.net core get runtime version
ocr library for c#
entityframework command to build model from database
The Project's target framework does not contain Entity Framework runtime assemblies. Please review the target's framework information in the project's property page.
ef core database first on Visual Studio package manager console
entity framework core genetare class using existing database
command to add entity framework layer in existing database
.net core login redirect loop
the same schemaid is already used for type swagger
The request was aborted: Could not create SSL/TLS secure channel.
asp.net core update-database specify environment
oauth API with the Access Token to retrieve some of users information.
Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding
.net 4.5 use tls 1.2
You are trying to create a MonoBehaviour using the 'new' keyword.
the underlying connection was closed nuget
search of specified registry key
C# loop through the registry searching for keys containing
searching for keys in the registry
registry keys and values
finding values in the registry
dotnet core webapp
finding keys in the registry
working with registry in c#
How to search values in the registry
asp.net core identity get all roles
force asp.net https
C# The request was aborted: Could not create SSL/TLS secure
dotnet create web api
dotnet add package
.net 6 get appsettings value
appsettings in console application c#
symfony debug bar
asp.net call controller from another controller
How to invoke an AWS Lambda function asynchronously
connection string .net core
crud operation in asp.net
asp net core send email async
c# cancellationtoken example
add-migration is not recognized
.net using appsettings variables
Convert xml to json
get xml from URL
what dotnet command does
c# webclient vs httpclient
qrcode c#
register all services microsoft .net core dependency injection container
ASP.NET Core Web API - Cannot instantiate implementation type 'System.Net.Http.IHttpClientFactory' for service type
C# HttpUtility not found / missing C#
An unhandled exception of type 'System.ArgumentException' occurred in System.Private.Xml.dll: 'The node to be inserted is from a different document context
cassandra Keyspaces repository .net
If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata publishing at the specified address.
Library dll unless netloaded by AutoCAD
forcedirectory C#
c# selenium xunit testing
how to add an embedded resource in visual studio code
asp.net framework mvc cors error axios
custom attribute for auth permission check .net
Get the Default gateway address c#
Get the current culture in a controller asp.net-core 6
how to add serilog to your asp.net project
Enviar correos en C# con MailKit
asp.net session empty cehck
asp.net core identity scaffold error
deploy c# applications on ubuntu
An unhandled exception occurred during the execution of the current web request
flutter failed asertion
How to set default page asp.net MVC
using Tls12 .net 3.5
global variable startup file .net core api
Open API support for ASP.NET Core Minimal API
What is the best way to lock cache in asp.net?
In ASP.NET Core how check if request is local
c# user name session
Get dwgexport setting reivit api
How to set a Printer Port in C# on a specified Printer
secret
jtoken value is not exact double
Unable to Write json variable c# getting an error
conditional middleware .net core
dotnet core vue in subdirectory
runner dotnet trace inside docker container
ef core many to many fluent api
docker Test a Connection using Curl
blazor clientside cookies
@using System,System.Core
asp net core dependency injection factory with parameters
IExtensionApplication autocad
how to controller request in c#
if session is not active then redirect to login page mvc.net
how to get the dynamic year for your web app in mvc
chaine de connexion sql server c#
c# md5 hash bouncycastle encypt decrypt with key
IAuthorizationFilter OnAuthorization AuthorizationContext MyAuthorizeAttribute HttpUnauthorizedResult HttpContext
The anti-forgery cookie token and form field token do not match.
asp.net core get current culture in controller
id dublication exception c# .net core
c# SQLite execute Command
WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).
iis services in asp.net
convert console app to linux
how to integrate a c# and angular 9
virtual properties and lazy loading in c#
c# use cefcharp and selenium can?
How do I identify the referrer page in ASP.NET?
asp.net store list in web.config
Server Error in '/' Application. An item with the same key has already been added. json asp
ExceptionFilterAttribute exception-handler-middleware-not-catching
run a command line from vb.net app
difference between eager and lazy loading entityframwork
pyqt send message to another instance
downloading a large file asp boilerplate (abp)
default route in asp.net core
run as administrator vs 2019
jtoken toobject is not exact double
how to add a ddos api to a c# console app
c# please build the project and retry
vb.net read registry key as string
blazor oninitializedasync
flutterwave c# api integration
stuck.hypixel.net ip
how to modigy login page asp.net core
mydata api .net
asp.net core reverse engineer database
aps.net core mvc chek box
Package manager or PM cmd for dbcontext migration
aws asp.net tutorial
fivem get control key icon
ASP.NET Core set update clear cache from IMemoryCache (set by Set method of CacheExtensions class)
How to solve error in ExecuteNonQuery() in asp.net
get current culture in controller asp.net core
core ui switch
how to get user browser information in .net core
.net core 3 entity framework constraint code first image field
blazor ref to component in if
serenity.is required field
instance vs initiate
1.1 0da14962afa287e5ba55c7d30c902392.cloudfront.net w
##[error]dotnet command failed with non-zero exit code on the following projects
convert web app to linux
Could not load file or assembly 'Newtonsoft.Json, Version
web.config customerrors not working
how to export xml in linq c#
.net mvc redirect to action with id
addssdawsdawdsdawasdawasdawdswsddsdawssd
how to add multiple values in session in asp.net visual studio
c# core deploy on gcp with powershell
IOException: Failed to prepare target build directory. Is a built game instance running? UnityEditor.WindowsStandalone.WindowsDesktopStandalonePostProcessor.DeleteDestination (UnityEditor.Modules.BuildPostProcessArgs args)
How to convert output of HttpClient PostAsJsonAsync() into user defined list of object
asp.net unregister client script
k8s You must be logged in to the server (Unauthorized)
c# error CS0515
System.InvalidOperationException: The AuthorizationPolicy named: 'View All Roles' was not found.
iserviceprovider vs iservicecollection
asp .net core 3 mvc select with default value
even configuration custom errors page is not working asp.net MVC
set custom default file in startup
add auto mapper in startup
most popular products code using asp.net core in visual studio code
Difference between PhotonNetwork.Ismasterclient and PhotonView.ismasterclient
System.InvalidOperationException: No owin.Environment item was found in the context.
DisplayUnitType revit api
WixSharp-FirewallException
how to use display attibute .net core
.net 6 minimal api authorization net 6
visual studio 2019 problem create new .net framework class library
cache.TryGetValue in MemoryCache c# .net
.net core executenonqueryasync transaction
process run teamviewer address parametr c#
how to detect ajax request in asp.net core
get current culture in controller asp.net core 6
blazor use static json files
eleventy set default layout
Store Images In SQL Server Using EF Core And ASP.NET Core
viewsheet location revit api
excute same code mvc
system.text.json ways to go about getting to the data how to get the data text.json you should use JsonDocument when
publish web app to linux or ubuntu
create entity c# d365
export xml
erlang start net kernel
ExecuteResultAsync
Photon Register Callbacks
create new .net core project visual studio
viewstate in asp.net demo \
create blazor server
xunit setup throw exception
ef core save keyless entity
asp.net issue
.net return manual status code
AutoMapper Add Assemblies
generate an mvc controller when dotnet core command line
lock a cache in asp.net
Connect secretclient to proxy
firepower 4125 License update
NetConnectionDispatch
.net core get exe path
nuget package TSETMC guide
conflictingactionsresolver as a workaround
how to make build events always run visual studio
asp.net core 6 get current culture in controller
detect location from ip address .net core
how to delete dotnet project
create viewport revit api
channel.writeandflush doesn't work netty
asp.net response.redirect new tab
GET and POST methods with the same Action name in the same Controller
dynamics 365 create record c#
dotnet.com
C# Http.HttpRequestMessage
ExecuteResultAsync ActionContext statuscode
dotcms contentidentifier
fetch post .net
c# signalr console app server example
create blazor web assembly
dotnet target specific framework
convert object to jtoken
firefoxoptions setpreference to trust certificates
c# entity mvc get user from razor layout
blazor OnInitializedAsync Unhandled exception rendering component: Cannot wait on monitors on this runtime.
tempdata serializer cannot erorr
android.content.res.Resources_Delegate.throwException(Resources_Delegate.java:1145)
get patht bim 360 revit api
how to pass id to modal in asp.net mvc
Internet Connection Sharing
curl rest api keycloak
asp.net core mvc not triggering client side validation
redis cache repository .net
.net framework cheat sheet
CS0103 C# The name 'Request.Url.Scheme' does not exist in the current context
umbraco cannot start. a connection string is configured but umbraco cannot connect to the database.
settings save c# visual studio doesn't work
retrive the last record dynamics 365 by c#
qget ViewSchedule revit api
Uninstall-SPSolution: This solution contains resources scoped for a Web application and must be retracted from one or more Web applications.
mongodb custom IIdGenerator
build url mvs view
How to read key from web config in JavaScript
httprequestmessage with authorization .net 5
blazor wasm roles not working
activeNetworkInfo depricated
CRUD configuration MVC with Firebase
c# get or create firewall inbound rule ports
ow-to-return-http-500-from-asp-net-core-rc2-web-api
MissingMethodException: PlayerManager.OnPlayerLeft Due to: Attempted to access a missing member.
c# azure get vm get cpu usage
{"receipts":[{"header":{"dateTimeIssued":"2022-06-24T08:06:54Z","receiptNumber":"EG02POS010000000062","uuid":"e420c161f9d76fd3bd5b45848b71f55148be60a9565fa36ebfb1dc5aecd56940","previousUUID":"","referenceOldUUID":"","currency":"EGP","exchangeRate":"0.00",
BOTON PARA CAMBIAR DE VIEW ASP.NET
mvc .testing nuget
c# .net core 3.0 trying Exception The transaction log for database is full due to ACTIVE_TRANSACTION
DateTime2 error in EF Blazor Web Application
dapper extension
entityframework index
asp.net core url parameter
nuget Microsoft.EntityFrameworkCore.InMemory": "1.0.0"
crystal report error webconfig reference
System.InvalidOperationException: 'Transaction has already been rolled back or is not pending'
vb.net check operating system
json serialize object capitalization config
ActionExecutingContext result response return objects
dotnet DB context register
create circumference with nettopologysuite
Max upload size for ASP.MVC CORE website
get all viewsheet revit api
Cannot resolve scoped service 'Mango.Services.Identity.Initializer.IDbInitializer' from root provider
MVC 5 identity SignOut Everywhere for specific user
delay activity in uipath
.net core best package for scheduler
mvc dotnet core how does the view pass parameters to controler
c# webclient accept all certificates
netmath hack console
decode token to get claims value
create new directory netrw
check .net installing
how to set the current user httpcontext.current.user asp.net -mvc
element click intercepted exception in selenium C#
notification platform not available c#
"The reference assemblies for .NETFramework,Version=v6.0 were not found"
eager loading singleton c# dependency injection
what error code i should return in asp.net core whether user name or password are incorrect
asp.net core user.identity.name is null
.net 3.1 bind json config
cqrs design pattern .net core
Visual Studio - Summary Tag Comments - Optional Params
asp.net core httpdelete with body
DefaultContractResolver .net exclude null values JsonSerializerSettings ContractResolver DefaultContractResolver
c# faker
CefSharp.Core in clickones application
store data between razor pages
how to set the server url in dotnet core
how to authorize token when consuming api in c#
[Package Manager Window] Error while fetching labels: User is not logged in or user status invalid. UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
System.Security.Permissions.FileIOPermission, mscorlib, ..., PublicKeyToken=b77a5c561934e089' failed.
WCF service dependency injection
technische vragen c#
kentico 13 api save attachment
net user windows command with password
ArgumentException: Input Key named: Fire1 is unknown
localhost ssl certificate error in visual studio 2022 .net 6
spring jar debug level running
c# webclient ssl bypass
list of countries in .net mvc 5
C# .net JwtSecurityTokenHandler jwttoken claims to object
unittest servicector automapper
.net new template
username and password into base64 encoding c#
scaffolding in vs22 asp.net 6
using (SqlDataReader sdr = cmd.ExecuteReader())
VSIX Project Context Menu
c# Unit Test IDbContextFactory
c# use meditor from service
Type already defines a member called 'Get'
check the request comes from which operating system used by user in asp net core
Get visitor count in asp.net
error:1408f10b:ssl routines:ssl3_get_record:wrong version number
parse error message: could not create type webservice.webservice asp .net
visual studio private field underscore
c# sha512 salt
salary, overtime, deductions, gross pay and netpay in console C#
asp.netcore: develop on win10 run on ubuntu
Get logged in user in ASP.Net
netlifycms disable preview
blazor webassembly .net standard 2.1
does Registry.CurrentUser.OpenSubKey create the key if it does not exist?
download xml file asp.net web api
resharper render pages folder asp.net core
internal working of ioc container c#
predicate builder ef core
fix autofill issue asp.net mvc
send to main args dotnet debug
HttpClient .net Core add Certificate
DotNet web Api Token based Authentication
c# task call more web api in parallel
You intended to execute a .NET program, but dotnet-ef does not exist
visual studio auto generate and setters
UnitType parameter revit 2022
how to list all registered users asp net
C# encrypt folder SHA512
ip validation .net core
IdentityServer vs JWT vs OAuth?
jobject alternative in system.text.json
GetNetworkTime
asp.net web hooks
enable asnotracking in asp.net core at global level
Error: Your project file doesn't list 'win' as a "RuntimeIdentifier". You should add 'win' to the "RuntimeIdentifiers" property in your project file and then re-run NuGet restore.
asp net route attribute vs httpget
invalid object name 'aspnetroles'.
generate jwt token authorize(roles = admin ) not working .net core 403
asp.net core web api Microsoft.Data.SqlClient.SqlException (0x80131904):
quartz .net core execute controller
System.Data.SqlClient.SqlException: 'Execution Timeout Expired.
how to unit test dbcontext in .net core
add header in action asp.net mvc
c# servercertificatevalidationcallback
c# interoperability with linux or bash script
no authenticationscheme was specified and there was no defaultchallengescheme found. .net core
exception meaning in .net core
difference between all logging framework .NET Core?
context.Response.Body read stream .net
c# api bypass ssl certificate
get web api relative path
how to start commvault services on linux
vb.net ionic zip examples
Difference between UnitOfWork and Repository Pattern
IdentityModelEventSource.ShowPII
C# verify "no other" call xunit
'KeyValuePair<int, int>.value' is inaccessible due to its protection level
Startup.cs class is missing in .NET 6
user (current login user) in viewcomponent
c# .net RemoveClaim auth
how to configure asp.net core on ionon 1&1 hosting
conncet oracle database in c# visual studio
fluent api c# hasmany withmany
taskcontinuationoptions.onlyonfaulted
visual studio pre build event not working
SonarQube UnitTests
vs 2022 access to path denied
mesh data optimization resolving used channels
how to get angular on visual studio mac
Moq Unittest with ILogger
AuthenticationTicket authenticationProperties C# .net
log4net.dll
psobject get service name
c# write to registry hkey_current_user
.Net Core Bundling & minification : .net core The name 'Scripts' does not exist in the current context
publish applications for linux
how to add the ssl certificate in vb.net application
c# ile ürün çekme - htmlagilitypack
mvc invalidOperationException: Method 'InvokeAsync' of view component should be declared to return Task<t>
viewresolver cyrillic
identity-1.us-south.iam.test.cloud.ibm.com:443
add dynamic value in startup file in .net core api
Modify middleware response c# .net
asp net identity login failed for user
RestRequest AdvancedResponseWriter site:stackoverflow.com
C# Create Swiss QR-Bill API
best free Modern Design frameworks C#
constant interpolated string
403 forbidden error using Windows Forms
asp.net core mvc razor page call pagemodel actio
constructor in protobuf-net
log4net rollingfileappender c#
jtoken value is not exact
stateteach.net
check if app have administrator rights c#
net use error 67
asp.net core logger in startup
response to preflight request doesn't pass access control check it does not have http ok status. c#
java.sql.sqlexception: access denied for user 'root'@'localhost' (using password: no)
dotnet
unity NetworkBehaviour the type or namespace could not be found
c# blazor in .net framework
devexpress objectspace to session
build a project from dotnet using cli
multithreading in .net core
urp set postprocessing value
MailChimp C# Api calls
.net directorysearcher get manager accountname
authenticatecoreasync owin not hadling exception handlers
don't want to update revision while updating field by code in sitecore c#
read administrator account remote machine C#
forces the user to enter his password before submitting the form asp.net core
cancellationtoken.linkedtokensource c# example
como guardar archivo en un botón asp.net
C# webclient immitate browser
getawaiter and no extension method
student roll mvc
how to mock abstract httpcontext using moq .net core
how crate cron netapp
webbrowser control feature_browser_emulation compatible#
model in bootsrap 4
bootrap modal
bootstrap modal
bootstrap popup
modal dismiss
bootstrap modal popup
boostrap 4 modal
small modal popup bootstrap
abril modal boostrap
modal bootstrap style
string to int c#
Text Split
c sharp split string
string to date vb
string to date
c# random int
text wrap
raycast unity
unity instantiate
Generate Random String
c# random string
how to generate random letters in C#
csharp datetime string format
dictionary c#
unity coroutine
how to delete from a list c#
print in c#
hello world c
writeline c#
how to print in c#
google drive c#
c# serialize json
c# MessageBox
c# initialize array
string to json c#
unity mouse position to world
get mouse position unity
c# read json file into object
c# check if string is empty
bash if null
how to do cmd command c#
how to make c# program run cmd commands
make command calls from c#
unity find gameobject by name
how to create a list in c# unity
unity change text
instantiate list C#
Create list C#
Create list with values C#
instantiate
string from byte array c#
c# byte array to string
how add text to element in javascript
kotlin random number
convert string to decimal c#
reload scene unity
ef database update
C# aspnet how to run a migration
ef update database
convert json to list object c#
c# get file extension
c# file exist
c# char to int
c# open file dialog
c# inline if
ModuleNotFoundError: No module named 'requests'
random.range unity
c# check to see if dictionary key exists
c# read all text from a file
unity get distance between two objects
c# datetime current
c# remove spaces from string
random from list c#
c# generate random int in range
c# random number between
c# thread sleep
c# thread# loop through array
c# send email
c# declare empty string array
how to convert a number to 2 decimal places in c#
for loop unity
convert string to array c#
c# list to string comma separated
c# create dynamic object
unity rotate vector around point
unity rotate vector
unity wait for seconds
unity rotate towards
unity c# foreach
c# float to string with 2 decimals
c# display float with 2 decimal places
if get key down unity
idenitfy if you press a key in unity
what is a protected int c#
how to move towards an object unity
get current computer ipv4 C#
how to get ip address in c#
how to get your ipv4 address in C#
c# get pc ip address
c# input integer
unity check if key pressed
remove first character in a string c#
convert timestamp to datetime c# code
c# convert Unix time in seconds to datetime
get time from datetime c#
datetime to hh:mm c#
decode base64 string c#
convert to base64 c#
how do i convert to base64 c#
how to pause your game unity
check if gameobject is active
How to read a XML on C#
how to disable a gameObject unity c#
new color unity
unity new Color()
parse json C#
C# Cast double to float
textmesh pro text unity
c# get today's date
find gameobject with tag
unity textmesh pro
get component text mesh pro
unity get textmesh pro component
unity create gameobject from prefab in script
how to remove a component from an object in unity
how t remove a component in unity
c# filter non alphanumeric characters
How do I remove all non alphanumeric characters from a string?
c# list remove duplicate items
delay in unity
c# convert list to string
c# regex match
percentage in c#
how to detect collision in unity
unity how to get fps
how to detect a mouse click in unity
c# length 2d array
c# post get request
c# read from file
convert string array to int C#
c sharp check if key in dictionary
convert int to double c#
unity delete all children
asp.net list all files in folder
c# list all files in a directory and subdirectory
center an image horizontally and vertically
resize image c#
loop through an enum c#
how to check a list is null or empty in c#
exceptions in c#
c# try catch
c# exception handling
exceptions c#
There is already an open DataReader associated with this Command which must be closed first c#
unity how to move an object
install sticky notes in ubuntu
c# encrypt decrypt string
c# filter list
c# string to byte[]
add row to datagridview c#
unity reset scene
c# wait seconds
c# bytes to string
system command in c#
hide cmd window c#
c# check if array is empty
c# reverse a string
string to list c#
format double to 2 decimal places in c#
c# to binary
c# how to convert string to int
check if string is email c#
c# cvalidate email
create char array c#
c# void
print content of array c#
c# change colour of console
covert char[] to string C#
move towards target unity
unity movetowards 2d
enum loop
c# foreach enum
Loop through enum C#
get last element of array c#
perlin noise unity
unity check if gameobject is active
c# format string with 2 decimals
unity load scene
c# rename file
c# check if a directory exists
how to convert string to guid c#
how to sort string array alphabetically in c#
unity change text color
c# write variable in string
unity add component
c# loop through datatable
setactive unity
c# loop datatable rows
c# random generator
change sprite of gameobject unity
c# enum parse from string
c# get month number from name
c# reading months as int
base64 string to byte array c#
c# tryparse int
base64decode C#
how to lock and hide a cursor unity
c# messagebox yes no
messagebox yes-no
c# prompt user yes no
unity check when clicked on object
get folders in directory c#
remove whitespace between string c#
how to change the position of a gameobject in c# unity
get all files in all subdirectories c#
how to get an child of an gameobject
c# convert object to string
regex for email c#
asp.net core 3.1: cast jObject to dictionary<string,string>
c# write byte[] to stream
c# json to dictionary
change scene unity
unity destroy self
how to destroy an object in unity
how to change image color unity
unity don't destroy on load
dont destroy on load
unity movetowards
C# get size of file
random value in array c#
guid.empty
0 guid
c# how to exit program
how to exit winforms application and shutdown pc in c#
change height of rect transform unity
set width of rect transform unity
c# datetime to timestamp
sum of digits in c#
sum of two numbers in c#
unity textmeshpro
c# get ip address
round to float unity
get working directory c#
unity 2d jump
base64 to image c#
c# generate random number
unity set mouse cursor lock
find the max number in an array c#
unity mouse lock
lockstate untiy
c sharp split by newline
wait in unity
remove last character from string c#
c# remove last value from list
c# class to byte array
c# run file
c# start file
c# open file
get text component unity
c# exit
c# quit
c# stop
c# exit application
unity how to add force
c# append to file
load scene unity
unity access child
.net loop through dictionary
if string contains number c#
c# read all files in a directory
c sharp stream to byte array
read folder c#
c# get class name by type
unity enable gameobject
C# insert into database
fdifference between two date in hours c#
c# find duplicates in list of strings
c# string to sha256
clone gameobject unity c#
duplicate item in c# unity
c# serialize to xml
c# combobox selectedvalue
c# absolute value
#region in c#
how to exit application c# console
how to reference a child object unity
Group by linq multiple columns C#
using serial port in c#
getname of month from date c#
new Color from hex in unity
c# hello world
C# How to write Hello World
c# afficher texte
hello world c#
C# Output
how to find a gameobject in unity
c# print list
disable script in unity
c# datagridview clear all rows
c# randomize a list
unity clamp rotation
how to convert int to string unity c#
if in dictionary c#
how to change rotate with script unity
vs code explorer font size
c# delay
C# Thread Sleep vs Task Delay
c# tostring mmm dd yyyy
c# find largest number in list
find largest number in array c#
how to instantiate as child unity
C# .net core convert string to enum
c# get all class properties
hello world program in c#
c# exit console
c# print hello world
remove first object from list c#
how to make a hello world program in c#
reference to another script unity
how to make a singleton in unity
unity set text value
get directory of file c#
get directory name of path c#
c# random number between 1 and 100
Get Index position of an element in a list in c#
how to cjeck if a string has a word c#
c# textboxaccept only numbers
bitmap to byte array c#
c# how do you check if a string contains only digits
c# rename file add
get application path c#
c# save bytes array to file
unity create a child object
check if number is even or odd c#
round double c#
C# delete folder with all contents
c# separate string by comma
c# print
unity to integer
c# foreach dictionary
ping with c#
dictionary c# iterate
check ping c sharp
c# dictionary loop key value
c# string equals ignore case
how to make rb.addforce 2d
c# datetime remove time
unity mouse click position
convert bytes to string and back c#
C# int to hex
c# decimal to hex
c# string to char
unity instantiate empty gameobject
unity c# get bool from another script
how to check if textbox is empty in c#
c# ascii to char
if cluse in class in vue
unity get layer of gameobject
unity look at target
how consider the first caracter in Split c#
unity dictionary check if key exists
c# append array
get path revit link unloaded
binary search tree c# stackoverflow
bold caption latex
hacker typer.com
how to make a 3d object do something when clicked on
how to use K2 games Games parallax background
List of 2 different iherent classes c#'
get text component unity
hash table in c#
how to make c# program run cmd commands
audioSource unity
C# Cast double to float
unity find gameobject by name
renaming table name entity framework code first fluent api
unity lerp position
c# exit foreach
muovere un elemento in c#
foot in cm c#
Get Index position of an element in a list in c#
write string multiple times c#
run dll file
replace index in string c#
Transpose Matrix CSharp
ArgumentOutOfRangeException when sorting a DataGridView using a custom IComparer
c# datagridview double click on cell
date format full month name c# selenium
how set format persian data picker to en
check if list contains any empty element in c#
print in c#
convert int to short c#
unity get mouse position
how to use distinct in linq query in c#
c# array to list
mouse click unity raycast unity
c# get executable path
c# sort int array
convert bytes to string and back c#
unity event trigger
what is napalm made of
lambda not null c#
c# find longest string in a list
move file from one folder to another c#
Triangle Calculator
irrrtate throught an matrix c#
change object position
how to convert from hexadecimal to binary in c#
Named Entity Extraction C#
upcasting and downcasting in c#
unity textmeshpro
C# float
c# unit test exception using try catch
structure in c sharp with example
c# show list in richtextbox
c# get innermost exception
c# datetime now timestamp
how to take user input in string in c#
unity spawn object at position
how to add skybox in unity
c# excel fix first row
Unity asset storre download forlder
thread c#
C# get all child classes of a class
c# ipaddress to integer
c# check if value in dictionary are unique
unity create random string
Get Mouse World Position
c# system.drawing.color to system.windows.media.color
new list/array with values c#
get execution directory c#
c# use list as a paramter
run file windows forms
mvc get base url
c# half hour dropdown list
Get Last Access Time Of Directory C#
Rotate Object/Camera by Mouse
c# call main method
get text after word C#
conevrt list to pipe separated string c#
delete file from FTP c#
C# IEnumerable access element at index
socket would block error c#
unity create a child object
Selecting item from listview in C#
Team Fortress
Show private fields in Unity Inspector
binding command to event wpf
EF Save changes
unpacking c # tuple
convert generic to type c#
.net mvc foreach with index
unity rotatoin angle
loop for x amount of seconds c#
c# transparent label
unity image button
transformquestionmarks=OCR
asp.net stop page jumping to top on click
c# string to memorystream
c# how to open file explorer
how to know what object player touches unity 2D
htmlgenericcontrol class c#
list sort c#
array declaration in c#
function on animation end unity
c# list audio devices
c# sort array string by length
c# copy each property
linked list follow what in c#
how to check the tag of a collider in unity
how to download somthing from one drive unity
Reading a date from xlsx using open xml sdk
codegrepper
unity textmesh pro
c# open explorer and select file
instantiate unity 2d in parent
c# function return
get connection string from web.config in c#
c# builder pattern fluent example
contains duplicate
c# ienumerable to list
how to play video in ui unity
c# socket listen on port
c# object add property
c# extract after what is
how disable the back off a panel C#
unity audio manager
SendFileAsync discord
JToken to string c#
hash sign c sharp
disable quickedit c#
autoit console write
spawning object around in a circle of an gameobject unity'
c# executing assembly path
c# declare an int list
serach a keyword in whole database
how to split list by date c#
Transparent UserControl
Prime number Upto n
c# performance timer
c# UserControl make background transparent
esc exit winform
multiplication of long number
C# cycle through directory
hovercraft in Unity
c# messagebox yes no "wpf"
unity pick random number
c# remove exit icon
c# string contains
C# how to use if and else
variable size in memory c#
C# unary operator
youtube
unity vector3 initialization
styles does not exisit in current context
get file extension in c# file upload
project camera view to texture
skrivetænking
c# if debug
get last element in a list vb.net
c# array.join
how to remove all whitespace from a string in c#
loop through an enum c#
Xamarin Forms iOS Picker done
abstract
hello world
c# yes or no dialog
c# create tasks and wait all
Declare a Delegate
unity get layermask
c# @ before string
unity pickup and drop objects
exit programm c#
c# how to terminate console application
2d rotation unity
get quaternion from vector unity
subtract days c#
c# create array of number from number
int to binary string with 4 characters
huidige timestamp c#
unity c# cos inverse
how to return array in function c#
c# if a new program is started
c# multiply string
vb.net array search
c# get list of all class fields
autoclicker for yes/no in c# indicator
edit pdf itextsharip
wpf mvvm crud example
make wpf run in fullscreen but above windows taskbar
system command in c#
how to convert date to Complete ISO-8601 date in c#
unity nested list
c# To Pascal Case
c# csv read write
insert keys automatically dictionary in c#
minimize window form c#
c# winforms datagridview bind to list
.net
c# serialize to xml
. | https://www.codegrepper.com/code-examples/csharp/how+to+mock+http+client+c%23 | CC-MAIN-2022-27 | refinedweb | 8,087 | 51.48 |
#include <db.h>
int DB->set_bt_minkey(DB *db, u_int32_t bt_minkey);
Set the minimum number of key/data pairs intended to be stored on any single Btree leaf page.
This value is used to determine if key or data items will be stored on overflow pages instead of Btree leaf pages. For more information on the specific algorithm used, see Minimum keys per page. The bt_minkey value specified must be at least 2; if bt_minkey is not explicitly set, a value of 2 is used.
The DB->set_bt_minkey interface may be used only to configure Berkeley DB before the DB->open interface is called.
The DB->set_bt_minkey function returns a non-zero error value on failure and 0 on success.
The DB->set_bt_minkey function may fail and return a non-zero error for the following conditions:
Called after DB->open was called.
The DB->set_bt_minkey function may fail and return a non-zero error for errors specified for other Berkeley DB and C library or system functions. If a catastrophic error has occurred, the DB->set_bt_minkey function may fail and return DB_RUNRECOVERY, in which case all subsequent Berkeley DB calls will fail in the same way. | http://pybsddb.sourceforge.net/api_c/db_set_bt_minkey.html | crawl-001 | refinedweb | 195 | 59.53 |
Autonomous vehicles still need a driver
Ruben is currently working on his Ph.D. at the Institute Of Marine Research in Norway, focusing on autonomous and stationary remote sensing of marine resources. He can be contacted at ruben.patelimr.no.
A common way of collecting scientific data involves the use of electronic sampling equipment. Typical scenarios for collecting biological data include long-time surveillance, surveillance near specific biomasses, and surveillance using autonomous platforms. In this article, I describe how I communicate with an EK60 SIMRAD echo sounder embedded in the High-precision Underwater Geosurvey and Inspection System (HUGIN) Autonomous Underwater Vehicle (AUV). Although this autonomous vehicle was originally designed for seabed mapping, its software can accommodate any sensor that can connect to the AUV.
As it turns out, the Institute of Marine Research in Norway uses scientific echo sounders for biomass measurements. While the echo sounders work well for remote sensing, they are unfortunately attached to a very large mother ship, which fish tend to react to because of engine and propeller noise. Consequently, the behavior of the fish is altered, introducing bias into the measurements. However, due to its low noise level, the AUV can get closer to schools of fish without introducing fish reaction. Because of this, we decided to embed our sensor in the AUV, thereby letting us move sensors closer to the biomass and collect detailed information and less biased data.
AUV Operation and Communication
The AUV has the ability to run in autonomous or controlled mode.
- In autonomous mode, the AUV conducts a preprogrammed survey with no communication with the mother vessel. This lets us use the mother ship for other activities. When the AUV survey is finished, it is recovered at a predefined time and location.
- In controlled mode, the AUV is remotely controlled from the mother ship using acoustic communication links. The pilot controls the trajectory of the AUV using a 55 bps link. Data from the AUV and its onboard sensors is transmitted over a data link running at 2000 bps. Critical data from the AUV is prioritized and occupy 1000 bps, meaning there is 1000 bps remaining to share among all the payload sensors. Since the acoustic communication links have a limited range of 2000 meters vertical, the mother ship has to follow the AUV to maintain communication.
The High Precision Acoustic Positioning system (HiPAP) tracks the position of the AUV. When running the AUV in the beam of the mother ship's echo sounder, we get detailed information of the biomass location relative to the AUV. This helps us steer the AUV close to the biomass of interest. Figure 1 shows the trajectory of the AUV while approaching and penetrating an enormous school of herring. This biological aggregation is common in some of the fjords in Norway during the herring's wintering phase. Since no cables are attached between the AUV and mother ship, the AUV can maintain a speed of 4 knots at its maximum depth of 2000 meters. In Figure 1, data was collected by running the mother ship directly above the AUV. The sea bottom is the thick red line and the herring school the biggest red aggregation. Two smaller schools of fish can be seen in the beginning of the image, and one small school directly above the biggest. The AUV trajectory can bee seen as a red line enhanced by blue. Dispersed fish (blue dots) can be seen distributed in the image. The image is contaminated due to acoustic interference form the AUVs sensor and communication system. The depth range is 550 meters and the distance from the start of the image to the end is around 3 kilometers. Initially, the stepwise AUV trajectory was to approach the school gradually. This was not successful as the school turned downward and disappeared. Still, this is an excellent performance compared to towed bodies.
The communication protocol between the sensor in the AUV and the control program on the mother vessel is complex. Figure 2 is an overview of the top side and bottom side of the HUGIN system. The horizontal dashed line indicates physical separation of the top side and bottom side. The vertical dashed line is the network connection when the AUV is connected directly to the topside system, this is done only when the AUV is onboard the mother ship. All commands and data sent to or received from the AUV go through the HUGIN Operator Station (HUGIN OS). This computer is also used for navigation, mission planning, and monitoring AUV performance. Sensors are controlled from Payload Operator Stations (POS); if a POS wants to send a command to its corresponding sensor, it has to first send it to the HUGIN OS. In turn, the command is sent over the acoustic data link to be received by the control processor. The control processor sends the command to the payload processor, which addresses it to the correct sensor plugin. All sensor plugins rely on the payload processor and are implemented as Dynamic Link Libraries (DLLs). From this point on, it is up to the programmer of the DLL to forward the message to its sensor. In our case, we send the command using TCP/IP to a bridge program. This design abstracts much of the complexity of the infrastructure in the AUV, and sensors can be added in a systematic manner.
Controlling the Application
The Windows-based applications we run for these studies remotely control the EK60 sensor in the AUV from the mother ship. You have several options when remotely controlling Windows applications. Commercial software packages that let you do this include PcAnywhere and Citrix. While these products give total control over the PC, they don't meet the AUV's communication speed and protocol needs. Consequently, I developed an alternative approach that, as a side benefit, can be used over any protocol.
The basic idea behind the approach I present here is to send events from one application to another using interprocess communication (IPC) based on Windows messages. This lets me send commands to applications from programs on the same machine for opening dialog boxes, pressing buttons, and reading and setting the states of different controls. In other words, I can send commands to applications just as if I were using a keyboard and mouse. This concept opens the possibility to remotely controlling many Windows applications. You can implement complex timers for sampling data at different hours. Sensors can be connected to other sensors and programs. In our case, we wrote a bridge program that translates messages between two communication protocols, letting us communicate with the sensor from different machines.
Figure 3 shows the three abstraction layers of the remote-control system. The first layer defines the fundamental functions for finding Windows handlers and performing simple commands on controls (Listing One). The next layer is a generic dialog box class, which encapsulates some of the fundamental functions (Listing Two). The last classes are dialog box classes that reflect the dialog boxes in our application. In this example, we need to access the BI500 Dialog and Surface Range Dialog dialog boxes (see Listings Three and Four, respectively).
Spying on Applications
Before writing the bridge program, I had to decide what commands to send to the application and what data to retrieve. Typical steps for executing a command are to open the correct dialog box, alter one or more of the controls in it, then press the OK button on the opened dialog boxes. This means that I have to map all the necessary events that are generated during the command execution. Since the control of the application lies in different windows, I have to map the events to open the corresponding dialog boxes, then I have to identify events for executing different commands, and finally the event for pressing the OK button. I did this using Microsoft's Spy++ program to spy on the message loop in the application we want to remotely control while executing the commands manually.
Remote Dialog Boxes
The Set Surface Range command controls the vertical depth range across the echogram. All the other commands are implemented in a similar manner. To set the surface range to 200 meters, for instance, I have to:
- Open the BI500 dialog box.
- Press the Surface Range button to open the Surface Range Dialog Box.
- Enter the number 200 into the Range text box.
- Press OK in the Surface Range Dialog Box.
- Press OK in the BI500 dialog box.
Using Spy++, I map the events that have to be sent to the application to perform each of the steps mentioned. The events are collected in a header file in Listing Five.
Using the defined classes, I can set the range to 200 meters using Listing Six. Line 3 starts the application if it is not started. We then control the range value to see if it is within the valid range using the macro in line 1. A new instance of the Surface Range Dialog box is created in lines 8 and 9. The parent and child window names are set. These names are used to find the windows handler in the window tree. In line 10, the command for setting the range is executed; see Listing Four. Line 41 shows the start of the method for setting the range. This method calls the SetText method in line 33. In line 35 the BI500 dialog is first opened, then the Surface Range Dialog box is opened by pressing the Surface Range button in the BI500 dialog box. Line 36 inserts the range value and closes the dialog boxes by pressing the OK button in each of them. As you see from the code, the PostMessage and SendMessage functions are the core of the communication. These functions send specified messages to a window and call the window procedure of the specified window. SendMessage does not return until the window procedure has processed its message. In contrast, PostMessage returns immediately without waiting for the window procedure to process the message.
Error Handling
The example works only if no errors are cast by the application. If an error is thrown, a dialog box appears, notifying users of the error. In most cases, the error box blocks the application for further input. We use two methods of dealing with this. Before any command is executed, we search for error or warning boxes and close them. The other method to avoid errors is by checking the commands that are sent to the application. One problem I had with our sensor was that our application sometimes lost connection to the general-purpose transceiver (GPT). This is the piece of hardware that does the actual sampling and signal processing of the raw data collected from the transducer. This caused an error box to appear. After pressing Retry three or four times, it worked fine and data was collected. I solved this problem by sending events to press the Retry button as long as the error dialog box was open; see Example 1.
Controls in dialog boxes often have a range limit and, if you try to set some value out of range, an error box appears. I avoided these types of errors by testing the range of each control and checking the range of the value before it was sent to the control, as in Listing Six, line 4.
The Bridge
The bridge program was made for running in two modes. For testing purposes, a command-line interface gives me the ability to send commands to the application. In remote mode, the bridge programs listen on a TCP/IP port. Received messages are translated to events and sent to the application. Example 2 is pseudocode for the bridge program.
Between every command translation, I test for potential GPT error boxes. These rarely occur, but would halt the application for further input if not closed. I then test if we are in test or remote mode. These modes receive commands differently and, therefore, we have two different functions for each mode. If a valid command is received, the nBytes variable contains the number of bytes the command occupies. If the command contains a valid command number of bytes, it is translated to events and sent to the application. If the client has lost connection with the bridge, we wait for the client to reconnect.
Conclusion
You need to be careful when remotely controlling applications. It is important to map all the potential errors that can appear during application use. One unknown error can halt the whole communication. Dialog boxes can use some time before they appear or close. It is therefore important to halt any commands before we are sure that the dialog box is open or closed. In my case, I poll the window tree to see if we can find the dialog box. Some programs are unstable and occasionally shut down or halt. A good rule is to check whether the sensor program is running before sending any commands. If it is not running, then start it before the command is sent. It was necessary to implement commands for stopping the sensor, restarting the computer, and shutting down the computer. I needed to stop the sensor and shutdown the computer before the AUV was launched and recovered. This was to reduce the risk for damaging the transducer and hard disk. There is always the danger of getting a total machine halt, like the blue screen in Windows. To recover from this, the control processor can recycle power on all the sensors at command from the HUGIN OS.
I tested the system during a cruise period over two weeks. My experience during this cruise is that this way of remote controlling and reading data from an application can indeed be used for remote sensors. The method is easy to implement and can be used in many ways. If the application behavior is well investigated a robust communication protocol can be developed.
DDJ
1 // Header 2 #ifndef __GLOBAL_HH__ 3 #define __GLOBAL_HH__ 4 #include \windows.h 5 6 typedef struct 7 { 8 HWND hwnd; 9 const char *title; 10 } FindWnd; 11 12 CALLBACK CheckWindowTitle( HWND hwnd, LPARAM lParam ); 13 HWND FindWinTitle(const char *title); 14 HWND FindWndByTitle(const char *parent,const char *child); 15 HWND WaitForDialogToOpen(char *parent,int timeout); 16 HWND WaitForDialogToClose(char *parent); 17 HWND OnShotOpenDialog(char *parent); 18 HWND LeftClickInAt(const char *parent,const char *child,int x,int y); 19 20 #endif 1 // Cpp file 2 #include "Global.h" 3 4 // Se if the specified window has a specified title 5 CALLBACK CheckWindowTitle( HWND hwnd, LPARAM lParam ) 6 { 7 char buffer[MAX_PATH]; 8 // Get the window title form window 9 GetWindowText( hwnd, buffer, sizeof( buffer ) ); 10 FindWnd * fw = (FindWnd *)lParam; 11 // Compare window tile with title to be checked. 12 if(strcmp( buffer, fw-title ) == 0 ) 13 { 14 fw-hwnd = hwnd; 15 return FALSE; 16 } 17 return TRUE; 18 } 19 // Find a parent window by it window title 20 HWND FindWinTitle(const char *title) 21 { 22 FindWnd fw; 23 fw.hwnd = 0; 24 fw.title = title; 25 EnumWindows( (WNDENUMPROC) CheckWindowTitle, (LPARAM) &fw ); 26 return fw.hwnd; 27 } 28 // Find a child window by it window title 29 HWND FindWndByTitle(const char *parent,const char *child) 30 { 31 FindWnd fw; 32 fw.hwnd = 0; 33 fw.title = child; 34 HWND hWnd = FindWinTitle(parent); 35 if(child==NULL) return hWnd; 36 else 27 { 28 ::EnumChildWindows(hWnd, (WNDENUMPROC) CheckWindowTitle, (LPARAM) &fw); 29 return fw.hwnd; 40 } 41 42 } 43 // Halt until a dialog is opened 44 HWND WaitForDialogToOpen(char *dlgName,int timeout) 45 { 46 HWND hWndDlg; 47 hWndDlg = NULL; 48 // Loop until the window is opened 49 do 50 { 51 hWndDlg= FindWndByTitle(dlgName,NULL); 52 } while(!hWndDlg); 53 return hWndDlg; 54 } 55 // Halt until a dialog is closed 56 HWND WaitForDialogToClose(char *dlgName) 57 { 58 HWND hWndDlg; 59 hWndDlg = NULL; 60 // Loop until the window is opened 61 do 62 { 63 hWndDlg= FindWndByTitle(dlgName,NULL); 64 } while(hWndDlg); 65 return hWndDlg; 66 } 67 // Open dialog 68 HWND OnShotOpenDialog(char *dlgName) 69 { 70 HWND hWndDlg; 71 hWndDlg = NULL; 72 // Get the handler 73 hWndDlg= FindWndByTitle(dlgName,NULL); 74 return hWndDlg; 75 } 76 // Left click in a child window at position x,y 77 HWND LeftClickInAt(const char *parent,const char *child,int x,int y) 78 { 79 // Get window handler 80 HWND hWnd = FindWndByTitle(parent,child); 81 WPARAM wParam = MK_RBUTTON; 82 LPARAM lParam = MAKELPARAM(x,y); 83 // simulating left mouse click in window 84 if(!::PostMessage(hWnd, WM_RBUTTONDOWN ,wParam,lParam)) 85 return NULL; 86 return hWnd; 87 }Back to article
Listing Two
1 // RDialog.h: interface for the CRDialog class. 2 #ifndef __CRDialog_H 3 #define __CRDialog_H 4 5 #include \windows.h 6 7 class CRDialog 8 { 9 public: 10 CRDialog(char *parent,char *child); 11 ~CRDialog(); 12 13 HWND IsDialogOpen(char *dlgName); // Check if the dialog // with name in dlgName is open 14 long SetText(int nIDDlgItem,char *text); // Set text in a control 15 DWORD SetCheck(int nIDDlgItem,BOOL checked); // Check or // uncheck a check box 16 HWND CloseDialog(void); // Close this dialog box 17 BOOL PressButton(int nIDDlgItem); // Press a button 18 19 char *m_sParent; // String to parent window 20 char *m_sChild; // String to this dialog box 21 22 }; 23 #endif 1 // CRDialog class implementation 2 #include \stdio.h 3 #include "CRDialog.h" 4 #include "Global.h" 5 #include "EK60MK1ID.h" 6 7 // Set string of parent and child window 8 CRDialog::CRDialog(char *parent,char *child) 9 { 10 int len1=strlen(parent)+1; 11 int len2=strlen(child)+1; 12 m_sParent = new char[len1]; 13 m_sChild = new char[len2]; 14 sprintf(m_sParent,"%s",parent); 15 sprintf(m_sChild,"%s",child); 16 } 17 CRDialog::~CRDialog() 18 { 19 delete[] m_sParent; 20 delete[] m_sChild; 21 } 22 // Close dialog box 23 HWND CRDialog::CloseDialog(void) 24 { 25 // Find handler of dialog box form string 26 HWND hWndDlg = FindWinTitle(m_sChild); 27 // Close dialog by pressing the OK button 28 ::SendDlgItemMessage(hWndDlg,RIDC_BUTTON_OK,BM_CLICK,0,0); 29 // wait for dialog to close 30 return WaitForDialogToClose(m_sChild); 31 } 32 // Return handler of dialog specified by window name 33 HWND CRDialog::IsDialogOpen(char *dlgName) 34 { 35 return FindWndByTitle(dlgName,NULL); 36 } 27 // Set text in control in dialog box 28 long CRDialog::SetText(int nIDDlgItem,char *text) 29 { 40 return::SendDlgItemMessage(FindWndByTitle(m_sChild,NULL), nIDDlgItem,WM_SETTEXT,0,(LPARAM)text); 41 } 42 // Check or uncheck a check control 43 DWORD CRDialog::SetCheck(int nIDDlgItem,BOOL checked) 44 { 45 // manipulate control in dialog 46 DWORD wParam ; 47 // Check it 48 wParam = (WPARAM) (checked)?(BST_CHECKED):(BST_UNCHECKED); 49 ::SendDlgItemMessage(FindWndByTitle(m_sChild,NULL),nIDDlgItem, BM_SETCHECK,wParam,0); 50 // Check if success 51 return::SendDlgItemMessage(FindWndByTitle(m_sChild,NULL), nIDDlgItem,BM_GETSTATE,0,0); 52 } 53 // Press a button 54 BOOL CRDialog::PressButton(int nIDDlgItem) 55 { 56 HWND hWndDlg; 57 // Check if the dialog is open 58 hWndDlg = IsDialogOpen(m_sChild); 59 // get handler of button to press 60 HWND hWndCont = ::GetDlgItem(hWndDlg,nIDDlgItem); 61 // Press it 62 ::PostMessage(hWndCont,BM_CLICK,0,0); 63 return TRUE; 64 }Back to article
Listing Three
1 // BI500RemoteDlg.h: interface for the BI500RemoteDlg class. 2 #ifndef __BI500RemoteDialog_H 3 #define __BI500RemoteDialog_H 4 5 #include "EK60MK1ID.h" 6 #include "CRDialog.h" 7 8 class CBI500RemoteDlg:public CRDialog 9 { 10 public: 11 CBI500RemoteDlg(char *parent,char *child); 12 virtual ~CBI500RemoteDlg(); 13 14 BOOL PressButtonSurfaceRange(); 15 BOOL PressButtonOK(); 16 private: 17 HWND OpenDialog(void); 18 BOOL SetText(int nIDDlgItem,char *text); 19 BOOL PressButton(int nIDDlgItem); 20 21 }; 22 23 #endif 1 // BI500RemoteDlg.cpp: implementation of the BI500RemoteDlg class. 2 3 #include "CBI500RemoteDlg.h" 4 #include "global.h" 5 6 7 CBI500RemoteDlg::CBI500RemoteDlg(char *parent,char *child) 8 :CRDialog(parent,child) 9 {} 10 CBI500RemoteDlg::~CBI500RemoteDlg() 11 {} 12 HWND CBI500RemoteDlg::OpenDialog(void) 13 { 14 HWND hWndDlg; 15 // Check if dialog is already open 16 hWndDlg = IsDialogOpen(m_sChild); 17 if(hWndDlg) return hWndDlg; 18 // Open the dialog 19 if(!::PostMessage(FindWinTitle(m_sParent), WM_COMMAND, RID_INSTALL_BI500,0 )) return NULL; 20 // get dialog handler 21 hWndDlg = WaitForDialogToOpen(m_sChild,1000); 22 return hWndDlg; 23 } 24 BOOL CBI500RemoteDlg::SetText(int nIDDlgItem,char *text) 25 { 26 OpenDialog(); 27 CRDialog::SetText(nIDDlgItem,text); 28 CloseDialog(); 29 return TRUE; 30 } 31 BOOL CBI500RemoteDlg::SetSurfVals(char *Surf) 32 { 33 SetText(RIDC_LIST_NOSURFVALS,Surf); 34 return TRUE; 35 } 36 37 38 BOOL CBI500RemoteDlg::PressButton(int nIDDlgItem) 39 { 40 HWND hWndDlg; 41 hWndDlg = IsDialogOpen(m_sChild); 42 if(!hWndDlg) hWndDlg=OpenDialog(); 43 HWND hWndCont = ::GetDlgItem(hWndDlg,nIDDlgItem); 44 ::PostMessage(hWndCont,BM_CLICK,0,0); 45 return TRUE; 46 } 47 48 BOOL CBI500RemoteDlg::PressButtonSurfaceRange() 49 { 50 return PressButton(RIDC_BUTTON_SURFRANGE); 51 } 52 BOOL CBI500RemoteDlg::PressButtonOK() 53 { 54 return PressButton(RIDC_BUTTON_OK); 55 }Back to article
Listing Four
1 // CSurfRangeRemoteDlg: interface. 2 #ifndef _SURFRANGEREMOTEDLG_H 3 #define _SURFRANGEREMOTEDLG_H 4 5 #include "EK60MK1ID.h" 6 #include "CRDialog.h" 7 #include "CBI500RemoteDlg.h" 8 #include "Global.h" 9 10 class CSurfRangeRemoteDlg :public CRDialog 11 { 12 public: 13 CSurfRangeRemoteDlg(char *parent,char *child); 14 virtual ~CSurfRangeRemoteDlg(); 15 16 BOOL SetRange(char *range); 17 BOOL SetStart(char *start); 18 19 private: 20 HWND OpenDialog(void); 21 HWND CloseDialog(void); 22 BOOL SetText(int nIDDlgItem,char *text); 23 }; 24 25 #endif 1 // CSurfRangeRemoteDlg: implementation. 2 #include "SurfRangeRemoteDlg.h" 3 4 CSurfRangeRemoteDlg::CSurfRangeRemoteDlg(char *parent,char *child) 5 :CRDialog(parent,child) 6 {} 7 CSurfRangeRemoteDlg::~CSurfRangeRemoteDlg() 8 {} 9 HWND CSurfRangeRemoteDlg::OpenDialog(void) 10 { 11 HWND hWndDlg; 12 // Open BI500 dialog 13 CBI500RemoteDlg BI500RDlg(m_sParent,"BI500 Dialog"); 14 // Press the Surface Range button in the BI500 dialog 15 BI500RDlg.PressButtonSurfaceRange(); 16 hWndDlg = WaitForDialogToOpen(m_sChild,1000); 17 return hWndDlg; 18 } 19 HWND CSurfRangeRemoteDlg::CloseDialog(void) 20 { 21 HWND hWndDlg = FindWinTitle(m_sChild); 22 // Close dialog 23 ::SendDlgItemMessage(hWndDlg,RIDC_BUTTON_OK,BM_CLICK,0,0); 24 // wait for dialog to close 25 WaitForDialogToClose(m_sChild); 26 //CRDialog::CloseDialog(); 27 CBI500RemoteDlg BI500RDlg(m_sParent,"BI500 Dialog"); 28 BI500RDlg.PressButtonOK(); 29 return NULL; 30 } 31 32 33 BOOL CSurfRangeRemoteDlg::SetText(int nIDDlgItem,char *text) 34 { 35 OpenDialog(); 36 CRDialog::SetText(nIDDlgItem,text); 37 CloseDialog(); 38 return TRUE; 39 } 40 41 BOOL CSurfRangeRemoteDlg::SetRange(char *range) 42 { 43 SetText(RIDC_LIST_SRANGE,range) ; 44 return TRUE; 45 } 46 47 BOOL CSurfRangeRemoteDlg::SetStart(char *start) 48 { 49 SetText(RIDC_LIST_STARTSURF,start); 50 return TRUE; 51 };Back to article
Listing Five
1 #define RID_INSTALL_BI500 32878 // ID to activate BI500 dialog 2 #define RIDC_BUTTON_SURFRANGE 0x510 // Button to push for activating // Surface Range Dialog box. 3 #define RIDC_LIST_SRANGE 0x3ec // ID for surface range text box 4 #define RIDC_BUTTON_OK 0x01 // Ok button idBack to article
Listing Six
1 #define IsInRange(val,min,max) if(val=min && val\=max) 2 nRang=200; 3 startEK60MK1App();// Start sensor program if not started 4 IsInRange(nRange,0,15000) // Check range 5 { 6 char val[5]; 7 itoa(nRange,val,10); 8 CsurfRangeRemoteDlg *surfRangeDlg 9 = new CSurfRangeRemoteDlg("SIMRADEK60","SurfaceRange Dialog"); 10 surfRangeDlg-SetRange(val); // Set range 11 delete surfRangeDlg; 12 }Back to article | http://www.drdobbs.com/windows/remotely-controlling-windows-application/184405678 | CC-MAIN-2017-43 | refinedweb | 3,784 | 51.58 |
Good tutorial!
Makes things very much clearer.
Another question.
I'm writing some code to process images. The images are stored as a 2D array of pixels.
When i run the code, i get segmentation violation. This usually occurs when trying to access values that are out side of the array your using.
The problem is I'm pretty sure that the my values are all withing the array. Is there any other cause of segmentation violations?
The other problem i have, when i compile i get the following warning:
Image_lib.c:43: warning: return from incompatible pointer type
from the code below
The declaration of the above function was provided by instructor.The declaration of the above function was provided by instructor.Code:int (*image_invert(int width, int height, int image_data[EP100_LIB_MAX_X][EP100_LIB_MAX_Y]))[] { //(body of code) return (int **)new_image_data; }
it should be returning a 2D array or reference to one (not sure which).
Any suggestions? | http://cboard.cprogramming.com/c-programming/94764-image-processing-need-help-new-c.html | CC-MAIN-2015-14 | refinedweb | 156 | 57.98 |
Issues and known bugs - glitchfur/NeosVR-Headless-API Wiki
Issues and known bugsIssues and known bugs
This is a log/braindump of stuff that needs fixed or gotchas to be aware of.
Windows supportWindows support
At the moment this library will only work on Linux, due to specifically calling
mono. I also don't know how system calls like SIGTERM or SIGKILL are handled on Windows. If you remove the
mono line and try it, stability may be different compared to on Linux.
Text formatting in world namesText formatting in world names
NeosVR-Headless-API looks for the
> character in the console's prompt to determine when a command has finished executing. Consequently, world names that end with any kind of XML-like text formatting (such as
<color></color> or
<size></size>) will trip up the prompt detection and break the library, specifically when calling the
.status() method. These tags are not parsed in the headless client's console and are printed literally. Unfortunately, I have not found a way around this that doesn't break "end of command" detection at this time. Time-based alternatives where the library waits some seconds after issuing a command isn't acceptable and can't realistically work.
Text formatting can still be used if it's done at the beginning or middle of the world name, just as long as the entire world name does not end with a
> character. Perhaps simply adding a space to the end of the world name is enough to prevent this issue from happening, as long as Neos does not truncate trailing whitespace. I have not tested. A period or other symbol could also work.
No worldsNo worlds
Library behavior when there is no world focused/when no worlds are running is untested.
Unimplemented commandsUnimplemented commands
Some commands aren't implemented in the API yet. They are the following:
saveConfig
friendRequests
acceptFriendRequest
startWorldURL
startWorldTemplate
import
importMinecraft
dynamicImpulse
dynamicImpulseString
dynamicImpulseInt
dynamicImpulseFloat
spawn | https://github-wiki-see.page/m/glitchfur/NeosVR-Headless-API/wiki/Issues-and-known-bugs | CC-MAIN-2022-27 | refinedweb | 324 | 52.09 |
So i’m trying to interface twitter with my app by using collecting tweets from a timeline with the api using json. I’m trying to get images from but it’s not working. Most of the tweets on the page have images but only 6 actually showed they had images using the API and looking at the “media_url” in entities. How am i supposed to get all of the images? I am using tweepy with python.
Twitter API Images
Here is the code I am using. The tweepy media call only shows that six of the photos have images even though when I go directly on twitter most of the tweets do have photos.
import tweepy
import json
from ftplib import FTP
import io
#allows access to the account
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(key, secret)
newAPI = tweepy.API(auth)
#gets 50 of the superfan timeline tweets
superFanTimeline = newAPI.user_timeline(id=“UMsuperfans”, count=50,include_rts=True)
#creates a blank array that the superfan json will go into
superFanJSONTimeline = [ ]
media = [ ]
for item in superFanTimeline:
#should get all media items which would be photos in the tweet but doesn’t return as many as it should
media.append(item.entities.get(‘media’, [ ] ))
superFanJSONTimeline.append(item._json)
print(media)
#pretty prints the json call and adds it into a file
finalJson = json.dumps(superFanJSONTimeline,indent=4)
with open(‘finalJson.json’,‘w’) as f:
f.write(finalJson)
include_rts=True includes retweets too, so those don’t have media entities in the Retweet - you need to first select the
retweeted_status and then look inside that for media
I did and it still doesn’t show any media inside.
Nevermind, I was able to fix it!
What was the solution? the retweet thing or something else like extended tweets or something?
I had to use extended tweets in my api call. So the line of code that i needed to have was
api.user_timeline(id=“UMsuperfan”, count=50, include_rts=True, tweet_mode=“extended”).
But thanks for your help I really appreciate it! I wouldn’t have known that it worked if i didn’t look inside the retweeted_status for media like you suggested. | https://twittercommunity.com/t/twitter-api-images/121894 | CC-MAIN-2019-13 | refinedweb | 359 | 58.18 |
In this article, we will review the process of using JavaScript, from an MVC-based perspective, to manipulate the DOM. More specifically, we'll engineer our JavaScript objects, their properties and methods, and their instantiations parallel to the intended behavior of our Views (what the user sees).
Consider Your Views As Objects, Not As Pages
At any point in the development of a web page, we are using a language that naturally promotes either class-based development or object-based development. In strongly-typed languages like Java and C#, we are usually writing our views in classes - giving them state, scope, and context. When we are working with languages like PHP or newer view engines, like Razor for ASP.NET, our views may simply be markup (HTML/CSS) mixed with templating. However, this does not mean we have to change our perception on how the view behaves as its own stateful entity.
Within Views, we are primarily working with HTML, which consists of nested elements; these elements have attributes which describe what their semantic purpose is or how they appear when rendered. These elements then have children or parent elements that inherit/provide cascading (through CSS) and block/inline behaviors. These elements can naturally be viewed from an OOP (Object-Oriented Programming) perspective. Consider, for example, the following markup:
div.container { border: 1px solid #333; padding: 5px; color: red; }
<div class="container"> <h2>About Our Company</h2> </div>
Result :
As you can see above, the header inherited its font color property from its parent container though the CSS behavior of cascading. This behavior is quite similar to the concept of inheritance in OOP. We can also see that the header is a child of the container, inheriting certain properties, based on the behavior of the element. When we see our elements from this perspective, we have a better definition of what we intend to do with our view elements and can encapsulate styles and functionality better.
Inside a view, we will have markup. However, this markup may have nested partial views like sidebars, a header, a footer, a right (or left) rail, and one or more content sections. All of these partial views should be viewed as their own entity, capable of having their own state, context, and scope.
"When you conceive your views and partial views as objects, it makes writing your client-side code much easier."
Translating This Concept Into Your Styles and Scripts
Many developers tend to write JavaScript from a procedural or functional point of view, and often neglect to consider the natural tendencies offered in view-based development approaches and parallel instantiation (creating a new instance of the view as we create a new instance of a JavaScript object corresponding to that view) when working in MVC Frameworks. It's often the case that I run into JavaScript files that are just one method after another. Though this behavior works, and is common, it is not very efficient for code maintenance, debugging, or extension of current or future code when you are working extensively with views.
To get away from this habit and begin writing better behavioral code, when you begin to lay out your View's scripting and styles, follow these general rules:
Golden Rules of View-based JavaScript Development
- Every view that is rendered from an action on a controller should have its own JavaScript object.
- Every Partial View that is loaded inside a View should have its own JavaScript object.
- Name your objects the same as your views (or partial views). This will make more sense for you and everyone else that touches your code.
- Use Pascal case for all objects (i.e. About, Sidebar, etc.). Your views should already, so why not do the same for your JavaScript objects?
- All constants of these objects should be stored in the constructor. This means if your view has properties that will be used in multiple methods, these methods can all access these properties.
- All methods that will be called on a view (or partial view) should be bound to the prototype of the object that corresponds to that view.
- All event bindings for the view (or partial view) should be contained within their own event binding's method, which is placed on the prototype.
Consider the following diagram:
I generally create view-specific scripts and styles and then grab what I need from the main stylesheets and script libraries I've created that would be used on many views. This also reduces the amount of code that is used.
Creating View-based Objects
In this article, we will be laying out the structure for the About Us page on an MVC-based site. To start, we will create the structure as shown above in the previous diagram. From there, we will create an About object, and begin adding methods to the prototype. First, consider the following visual layout:
This is a very logical and commonly used layout for a webpage. We can segment our page into seperate visual objects. For each of these views, we can create a logical object that will correspond to it. I generally omit the repetitive information in the filename or classname that is used by MVC to determine the URI from the route and instead stick with something that is easy to keep consistent.
For page views, I generally call my JavaScript objects by the name of the view. Here is an example of my AboutView Object:
// View Filename: AboutView.cs (.NET MVC 1.0), About.cshtml (.NET MVC 3.0), or AboutView.php (PHP) var About = function(pageTitle) { this.pageTitle = pageTitle; // binding events as soon as the object is instantiated this.bindEvents(); };
In the above example, we created a JavaScript object in the function format, giving it the capacity to serve as an Object constructor for all methods called for the about view. By choosing this format, we can instantiate a new instance of this, just as we do with our view Server-Side (by saying
new AboutView();). From here, we can assign properties and methods to this object. In order to assign methods to this object, we will need access to the object's prototype.
JavaScript's Prototype is your Friend
Developers are often thwarted by the elusiveness (and ambiguity) of JavaScript's Object Prototype.
Developers are often thwarted by the elusiveness (and ambiguity) of JavaScript's Object Prototype. For many, it can be confusing to use and understand and adds another dimension to coding. As JavaScript becomes more event-driven with HTML5, AJAX, and web 2.0 concepts, JavaScript tends to lean naturally to procedural development that is easy to develop but hard to maintain, scale, and replicate.
Think of the word Prototype as a misnomer for now. When I think Prototype, I think of a "rough draft" or a base for inheritance, but this isn't exactly the case.
" In reality, the better perspective for Prototype would be the Object's Pointer in memory."
When we create an object, we then instantiate a new instance of it. When we do that, we create a place in memory that the object can be referenced (remember, Objects in JavaScript are reference types, not primitive types; creating another variable equal to that object and then changing its values will actually change the original object in the pointer). When we create an object, instantiate a new instance of it, and then modify its "Pointer," or Prototype, we add fields and methods to that object in memory directly (obviously we want to add all of these things before instantiation).
Here's an example of creating methods on the
About object's prototype:
var About = function(pageTitle) { this.pageTitle = pageTitle; // binding events as soon as the object is instantiated this.bindEvents(); }; var About.prototype.bindEvents = function() { // Current context: 'this' is the About object // Place all your event bindings in one place and call them out // in their own methods as needed. $('ul.menu').on('click', 'li.search', $.proxy(this.toggleSearch, this)); }; var About.prototype.toggleSearch = function(e) { //Toggle the search feature on the page };
As you can see above, we have contained the properties of the About object within the constructor, have created a single point of reference for binding events (in this case we are using jQuery to create the event bindings, but you can use any framework or JavaScript itself), and have placed the toggleSearch method on the prototype of the About object to contain that method to that object. We have also called the
bindEvents() method in the object so that it is called on instantiation.
Now, consider the following code for the Sidebar Partial View:
var pSidebar = function(pageTitle) { this.pageTitle = pageTitle; // call the bindEvents method on instantiation of the pSidebar object. // this will bind the events to the object this.bindEvents(); }; var pSidebar.prototype.bindEvents = function() { //current context: 'this' is the Sidebar object $('ul.menu').on('click', 'li.has-submenu', $.proxy(this.toggleSubMenu, this)); $('input#search').on('click', $.proxy(this.openSearch, this)); }; var pSidebar.prototype.toggleSubMenu = function(e) { // toggle the submenus // current context: 'this' is the pSidebar obj };
NOTE: I called the object
pSidebar because this is a partial view, not a full view. This is my preference to distinguish between the two, but makes things clearer.
The beauty of using this approach is - we can use the same method names we used in the About object and we will have no conflicts. This is because these methods are bound to the object's prototype itself, not the global namespace. This simplifies our code and allows for a sort of "templating" for future scripting.
Instantiate Only as Needed
Once you have created your objects, calling them is simple. No longer do you need to depend on your framework to fire events when your document is loaded or ready. Now, you can simply instantiate your object and its events will be bound and executed as needed. So, let's instantiate our
About object:
Inside your view where you would call your view specific scripts (dependent upon your templating language), simply call a new instance of your object and include the file as follows:
<script src="/path/to/scripts/views/about.js"></script> <script> new About("About Us"); </script>
As you can see, I passed in the page title for the view (which can be any argument for any need - even Model Data. This gives you excellent context over your model data and allows you to manipulate that data in JavaScript very easily.
Just like your
About Object, calling your partial views is just as easy. I would highly recommend calling new instances of your partial view JavaScript objects within the object's constructor - this ensures that you are only calling these as needed and that they are collectively in one place.
var About = function(pageTitle) { this.pageTitle = pageTitle; //assigning a new instance of the Sidebar Partial View to be referenced later this.sidebar = new pSidebar(pageTitle); //NOTE: If you don't need to reference a partial view after the fact, //you can simply instantiate an instance of it without assigning it within the object's constructor, as so: new pSidebar(pageTitle); //doing the same for the Partial Footer View this.footer = new pFooter(); // binding events as soon as the object is instantiated this.bindEvents(); };
As you can see, by referencing the Sidebar object as a local property of the About object, we now bind that instance, which is a very natural behavior - this instance is now the About Page's Sidebar.
If you don't need to reference a partial view after the fact, you can simply instantiate an instance of it without assigning it within the object's constructor, as so:
var About = function(pageTitle) { this.pageTitle = pageTitle; new pSidebar(pageTitle); // binding events as soon as the object is instantiated this.bindEvents(); };
From here, all we need to do is add another script to our scripts called in our view:
<script src="/path/to/scripts/views/about.js"></script> <script src="/path/to/scripts/partials/sidebar.js"></script> <script> new About("About Us"); </script>
Why This Technique is Beneficial
Once this structure is in place, we can then tailor our JavaScript object to match our view and apply the needed methods to that object to maintain scope. By creating a view-parallel object and working off that object's prototype, we see the following benefits:
- The nomenclature makes it easier to navigate through code
- We naturally namespace our objects, reducing the need for long method names and too much use of anonymous closure.
- Little to no conflict in other code because our methods are on the prototype of the object, not on the global level
- When instantiating our partial views within our View's object constructor and assigning them to a local variable reference, we effectively create a locally bound copy of that Partial View's object.
- We have a firm definition of context and are able to use the keyword 'this' without worry.
- Debugging becomes clear because all methods shown in the stack are bound in one place.
Conclusion
As the MVC Design Pattern continues to become more popular in the design world, the development of JavaScript Objects to accompany DOM Element manipulation will change to be more tailored towards view-specific and event-specific manipulation. By tailoring our JavaScript objects to instantiate in parallel with our Views, we can have a hand-in-hand stateful relationship between the two - one that is symantically in good taste, easy to step through, simple to maintain, and perfect for expansion as the view grows or changes, creating a permeable and expandable relationship between markup and scripting.
By utilizing an Object's Prototype, we are able to maintain a precise context on our View's scripting object and expand that object with a repetitive development frame-of-mind. We can then replicate this format through our partial views, saving us time, brain power, and risk of bugs and unexpected behavior. | http://esolution-inc.com/blog/using-javascripts-prototype-with-mvc--net-23977.html | CC-MAIN-2019-51 | refinedweb | 2,323 | 59.53 |
Introduction
In this article we are going to explore the controls inside Windows Phone 7 who are named NumericTextBox control. Later we will create a class library, which means we have to take a separate Windows Phone class library for which we can made that numeric TextBox. In this we have to learn how to make a user or custom control from Windows Phone 7. Those are controls in which we can add any type of functionality that we want and later you can use it as a control as well toolbox. Here we are making the numeric TextBox for which means whatever we enter inside the TextBox will be in numeric form, it will not have inserted a character value inside the TextBox. Further, whatever library we have made it's reference such as the .dll file will be added inside the other Windows Phone application at which we want to use that control and you should have to add a library project inside the Windows Phone application project. Now it's time to proceed learning something new so have a look on the steps given below and which will be helpful for such a type of implementation.
Step 1 : In this step we have to create a Windows Phone library so let's see from where you have to add it which is given in the figure.
Step 2 : In this step we will see the code for the Windows Phone library so let's have a look on the code given below.
Code : This code will be written inside the NumericTextBox.cs fileusing System;using System.Windows.Controls;using System.Windows.Input;namespace WPControls{ public class NumTxtBox: TextBox { }; public NumTxtBox() { this.InputScope = new InputScope(); this.InputScope.Names.Add(new InputScopeName() { NameValue = InputScopeNameValue.TelephoneLocalNumber }); } protected override void OnKeyDown(KeyEventArgs e) { if(Array.IndexOf(num,e.Key) == -1) { e.Handled = true; } base.OnKeyDown(e); } }}
Step 3 : In this step you have to build the class library for which you have to click on the build project; it will be built succesfully as well.
Step 4 : Now you have to take another application which is a Windows Phone application.
Step 5 : In this step you will have to add the reference of the phone class library which was created; let us see from where you have to add this which is shown in the figure.
Add the reference of the dll file which will be created and see how it will added which is shown in the figure given below.
Step 6 : In this step we have to add the complete phone library project to the Windows Phone application project; let us see how you will add it.
Add the existing project on click to add it shows which project select existing project.
Select the WPControls.cs file; let us see how it will added which is shown in the figure.
Step 7 : In this step you will see that the project has been added to your Windows Phone application project which you can see in the figure given below:
Step 8 : In this step you will just see that the control named numeric textbox has been added to the toolbox which you can see in the figure given below you can drag and drop that control to use it.
Step 9 : In this step you just see the code for the MainPage.xaml.cs file which is given below.Code :
using System;using System.Windows.Input;using Microsoft.Phone.Controls;namespace WPNumericTextBox{ public partial class MainPage : PhoneApplicationPage { // Constructor public MainPage() { InitializeComponent(); } // allowed keys }; private void STxtbox_KeyDown(object sender, KeyEventArgs e) { if (Array.IndexOf(num, e.Key) == -1) { e.Handled = true; } } private void Button2_Click(object sender, System.Windows.RoutedEventArgs e) { txtbres.Text = string.Format("Numeric textbox 1 value is : {1}{0}Numeric textbox 2 value is : {2}{0}", Environment.NewLine,STxtbox.Text,NumTxtboxUC.Text); } private void Button2_Click(object sender, System.Windows.RoutedEventArgs e) { txtbres.Text = STxtbox.Text = NumTxtboxUC.Text = string.Empty; } }}Step 10 : In this step you will see the code for the MainPage.xaml file which is given below:
Code:<phone:PhoneApplicationPage xmlns: <TextBlock x: </StackPanel> <!--ContentPanel - place additional content here--> <Grid x: <Grid.RowDefinitions> <RowDefinition Height="100"/> <RowDefinition Height="100"/> <RowDefinition Height="100"/> <RowDefinition Height="100"/> <RowDefinition Height="200"/> </Grid.RowDefinitions> <StackPanel> <TextBlock Foreground="#FF23FFCB" Text="Enter Numeric value" FontFamily="Comic Sans MS" FontSize="26"></TextBlock> <TextBox Name="STxtbox" InputScope="TelephoneNumber" KeyDown="STxtbox_KeyDown" FontFamily="Comic Sans MS" FontSize="26" BorderBrush="#BF7B0AFF" /> </StackPanel> <StackPanel Grid. <TextBlock Foreground="#FF1CA9FF" Text="My Numeric control" FontFamily="Comic Sans MS" FontSize="28"></TextBlock> <my:NumericTextBoxUserControl x: </StackPanel> <StackPanel Grid. <StackPanel Orientation="Horizontal" HorizontalAlignment="Center"> <Button Name="Button1" Content="Show Data" Click="Button1_Click" FontFamily="Comic Sans MS" FontSize="28" Foreground="#FF30D8C3" /> <Button Name="Button2" Content="Clear Data" Click="Button2_Click" FontFamily="Comic Sans MS" FontSize="28" Foreground="#FFF5F300" /> </StackPanel> <TextBlock Name="txtbres"/> </StackPanel> </Grid> </Grid></phone:PhoneApplicationPage>
Step 11 : In this step you will see the design of the MainPage.xaml file let see the figure given below.
Step 12 : Now it's time to run the application by pressing F5 let see the output figure which is given below.
Output 1 : Whenever we run the application then by default we will see the figure given below.
Output 2 : Now click on the textbox first and second then you can enter only the Numeric value rather than alphabetic.
Output 3 : In this output after click on the button show values then you can see the values which were written inside both textboxes and you can clear these values on click on the second button named clear values.
Here are some other resources which may help you
Calculator in Windows PhoneNumeric Textbox-Custom Control
Create an alpha-numeric textbox using jQuery
View All | http://www.c-sharpcorner.com/UploadFile/74f20d/create-a-simple-numeric-textbox-control-in-windows-phone-7/ | CC-MAIN-2017-09 | refinedweb | 957 | 54.32 |
#include <CCTableView.h>
override functions
Reimplemented from CCScrollView.
Returns an existing cell at a given index.
Returns nil if a cell is nonexistent at the moment of query.
An intialized table view object.
An initialized table view object.
Dequeues a free cell if available.
nil if not.
data source
delegate
Inserts a new cell at a given index.
reloads data from data source.
the view will be refreshed.
Removes a cell at a given index.
determines how cell is ordered and filled in the view.
Updates the content of the cell at a given index.
vertical direction of cell filling
free list of cells
cells that are currently in the table
weak link to the data source object
index set to query the indexes of the cells used.
weak link to the delegate object
vector with all cell positions | http://www.cocos2d-x.org/reference/native-cpp/V2.2.2/d8/d28/classcocos2d_1_1extension_1_1_c_c_table_view.html | CC-MAIN-2016-44 | refinedweb | 139 | 70.6 |
Query explained: merge two dictionaries in a single expression? Answer #1:
For dictionaries
x and
y,
z becomes a shallowly-merged dictionary with values from
y replacing those from
x.
- In Python 3.9.0 or greater (released 17 October 2020): PEP-584, discussed here, was implemented and provides the simplest method:
z = x | y # NOTE: 3.9+ ONLY
- In Python 3.5 or greater:
z = {**x, **y}
- In Python 2, (or 3.4 or lower) write a function:
def merge_two_dicts(x, y): z = x.copy() # start with keys and values of x z.update(y) # modifies z with keys and values of y return zand now:
z = merge_two_dicts(x, y)
Explanation
Say you have two dictionaries and you want to merge them into a new dictionary the What’s New in Python 3.5 document.
However, since many organizations are still on Python 2, you may wish to do this in a backward‘s values, thus
b will point to
3 in our final result.
Not yet on Python 3.5, but want a single expression
If you are not yet on Python 3.5 or need to write backward-compatible code, and you want this in a single expression, the most performant while the arbitrary.
Critiques of Other Answers "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'
and you would have to explicitly create them as lists, e.g.
z = dict(list(x.items()) + list(y.items())). This is a waste of resources and computation power.
Similarly, taking the union of
items() in Python 3 (
viewitems() in Python 2.7) will also fail when values are unhashable objects (like lists, for example). Even if your values are hashable, since sets are semantically unordered, the behavior is undefined in regards to precedence. So don’t do this:
>>> c = dict(a.items() | b.items())
This example demonstrates what happens when values are unhashable:
>>> x = {'a': []} >>> y = {'b': []} >>> dict(x.items() | y.items()) Traceback (most recent call last): File " "<stdin>", line 1, in <module> TypeError: keyword arguments must be strings
From the mailing list, Guido van Rossum, the creator of the language, wrote:
I am fine with declaring dict({}, **{1:3}) illegal, since after all it is abuse of the ** mechanism.
and
Apparently dict(x, **y) is going around as “cool hack” for “call x.update(y) and return x”. Personally, I find it more despicable than cool.
It is my understanding (as well as the understanding of the creator of the language) that the intended usage for
dict(**y) is for creating dictionaries for readability purposes, e.g.:
dict(a=1, b=10, c=11)
instead of
{'a': 1, 'b': 10, 'c': 11}
Response to comments
Despite what Guido says,
dict(x, **y)is in line with the dict specification, which btw. works for both Python 2 and 3. The fact that this only works for string keys is a direct consequence of how keyword parameters work and not a short-coming of dict. Nor is using the ** operator in this place an abuse of the mechanism, in fact, ** was designed precisely to pass dictionaries as keywords.
Again, it doesn’t work for 3 when keys are not strings. The implicit calling contract is that namespaces take ordinary dictionaries, while users must only pass keyword arguments that are strings. All other callables enforced it.
dict broke this consistency in Python 2:
>>> foo(**{('a', 'b'): None}) Traceback (most recent call last): File "<stdin>", line 1, in <module>:
dict(x.items() + y.items())is still the most readable solution for Python 2. Readability counts.
My response:
merge_two_dicts(x, y) actually seems much clearer to me, if we’re actually concerned about readability. And it is not forward compatible, as Python 2 is increasingly deprecated.
{**x, **y}does not seem to handle nested dictionaries. the contents of nested keys are simply overwritten, not merged […] I ended up being burnt by these answers that do not merge recursively and I was surprised no one mentioned it. In my interpretation of the word “merging” these answers describe “updating one dict with another”, and not merging.
Yes. I must refer you back to the question, which is asking for a shallow merge of two dictionaries, with the first’s values being overwritten by the second’s – in a single expression.
Assuming two dictionaries: {}}}
Less Performant But Correct Ad-hocs
Performance Analysis
How to get the union of two dictionaries in Python? Answer }
Answer #3:
An alternative:
z = x.copy() z.update(y)
Answer .
Answer .
Answer #6:
In a follow-up answer, you asked about the relative performance of these two alternatives:
z1 = dict(x.items() + y.items()) z2 = dict(x, **y)
On my machine, at least (a fairly ordinary x86_64 running Python 2.5.2), alternative
z2 is not only shorter and simpler but also significantly faster. You can verify this for yourself using the
timeit module that comes with Python.
Example 1: identical dictionaries mapping 20 consecutive integers to themselves:
% python -m timeit -s 'x=y=dict((i,i) for i in range(20))' 'z1=dict(x.items() + y.items())' 100000 loops, best of 3: 5.67 usec per loop % python -m timeit -s 'x=y=dict((i,i) for i in range(20))' 'z2=dict(x, **y)' 100000 loops, best of 3: 1.53 usec per loop
z2 wins by a factor of 3.5 or so. Different dictionaries seem to yield quite different results, but
z2 always seems to come out ahead. (If you get inconsistent results for the same test, try passing in
-r with a number larger than the default 3.)
Example 2: non-overlapping dictionaries mapping 252 short strings to integers and vice versa:
% python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z1=dict(x.items() + y.items())' 1000 loops, best of 3: 260 usec per loop % python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z2=dict(x, **y)' 10000 loops, best of 3: 26.9 usec per loop
z2 wins by about a factor of 10. That’s a pretty big win in my book!
After comparing those two, I wondered if
z1‘s poor performance could be attributed to the overhead of constructing the two item lists, which in turn led me to wonder if this variation might work better:
from itertools import chain z3 = dict(chain(x.iteritems(), y.iteritems()))
A few quick tests, e.g.
% python -m timeit -s 'from itertools import chain; from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z3=dict(chain(x.iteritems(), y.iteritems()))' 10000 loops, best of 3: 66 usec per loop
lead me to conclude that
z3 is somewhat faster than
z1, but not nearly as fast as
z2. Definitely not worth all the extra typing.
This discussion is still missing something important, which is a performance comparison of these alternatives with the “obvious” way of merging two lists: using the
update method. To try to keep things on an equal footing with the expressions, none of which modify x or y, I’m going to make a copy of x instead of modifying it in-place, as follows:
z0 = dict(x) z0.update(y)
A typical result:
% python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z0=dict(x); z0.update(y)' 10000 loops, best of 3: 26.9 usec per loop
In other words,
z0 and
z2 seem to have essentially identical performance. Do you think this might be a coincidence? I don’t….
In fact, I’d go so far as to claim that it’s impossible for pure Python code to do any better than this. And if you can do significantly better in a C extension module, I imagine the Python folks might well be interested in incorporating your code (or a variation on your approach) into the Python core. Python uses
dict in lots of places; optimizing its operations is a big deal.
You could also write this as
z0 = x.copy() z0.update(y)
as Tony does, but (not surprisingly) the difference in notation turns out not to have any measurable effect on performance. Use whichever looks right to you. Of course, he’s absolutely correct to point out that the two-statement version is much easier to understand.
Answer #7:
In Python 3.0 and later, you can use
collections.ChainMap which groups multiple dicts or other mappings together to create a single, updateable view:
>>> from collections import ChainMap >>> x = {'a':1, 'b': 2} >>> y = {'b':10, 'c': 11} >>> z = dict(ChainMap({}, y, x)) >>> for k, v in z.items(): print(k, '-->', v) a --> 1 b --> 10 c --> 11
Update for Python 3.5 and later: You can use PEP 448 extended dictionary packing and unpacking. This is fast and easy:
>>> x = {'a':1, 'b': 2} >>> y = {'b':10, 'c': 11} >>> {**x, **y} {'a': 1, 'b': 10, 'c': 11}
Update for Python 3.9 and later: You can use the PEP 584 union operator:
>>> x = {'a':1, 'b': 2} >>> y = {'b':10, 'c': 11} >>> x | y {'a': 1, 'b': 10, 'c': 11}
Hope you learned something from this post.
Follow Programming Articles for more! | https://programming-articles.com/how-to-merge-two-dictionaries-in-a-single-expression-taking-union-of-dictionaries-answered/ | CC-MAIN-2022-40 | refinedweb | 1,533 | 62.88 |
Episode 29 · October 23, 2014
Learn how to send email notifications to users with Rails 4.2 ActionMailer, deliver_later, and email previews
Now over the course of the last few episodes, we've been building a forum, and we've created forum threads and forum posts and all the interactions that you typically see with that, however, we now need to start adding things like email notifications. So in this episode we're going to talk about adding email notifications any time you submit a new comment and then how to send this in the background as a background job as well as how to preview these from inside of Rails itself without sending any actual emails. So let's dive in.
Looking at the Rails guides for Action Mailer we can find the deliver_later method, and we can see that inside the Rails guides, it recommends using deliver_later, but it also has this deliver_now method. So there's two different ways that we can be sending emails now in Rails 4.2, and previously we just had the .deliver on an email, so when you had an email it would automatically send it immediately. Now we have two separate commands for this, we have deliver_later and deliver_now. And deliver_now will send immediately of course, and then deliver_later will also send immediately unless you've configured Active Job to use something other than the inline background worker. So if you install Sidekiq, you install Resque or Sucker Punch, you'll be able to send jobs to Active Job that will send the emails later. So by default it will send them immediately and you just have your application ready to go when you want to roll out background workers. So that's really cool, and we're going to be using deliver_later because there's no reason to use deliver_now unless you absolutely need to send it immediately.
After we create a forum post inside the forum post controller, we want to actually send that email notification. We can add a method immediately after save
forum_posts_controller.rb
def create @forum_post = @forum_thread.forum_posts.new forum_post_params @forum_post.user = current_user if @forum_post.save @forum_post.send_notifications! redirect_to forum_thread_path(@forum_thread, anchor: "forum_post_#{@forum_post.id}") else redirect_to @forum_thread, alert: "Unable to save your post" end end
We'll make this send_notifications method on the forum post so it can be the one that contains the logic for this. So we'll have this send_notifications method and it needs to get all the unique users in this thread, and then it also needs to send an email to each of those users. So we're going to have to do two things, the first thing will be to gather up all the users inside the thread that the forum post is in, and then we're going to have to send an email to all of those.
So first thing's first, we can star building this one (gathering all the unique users), and that one (Sending emails) is pretty simple. So we have the forum thread, through our association, so we'll be able to do that, and then we'll be able to say, if we go to the forum thread, you can see that we have a belongs_to, but we can also add a
has_many :users, through: :forum_posts. So this will be a list of all the users who have ever chatted inside of the forum thread, and this (user) will be the owner of the forum thread. We don't really need to interact with this, we're just saving it, just in case that we want to allow them later to be able to edit just the forum thread subject or something. So they're a little bit special because they're the person that created them, and we could give them a different name,
belongs_to :owner, class_name: "User", or something like that so that it separates the two out, so I'm going to leave that for now. so we'll add this association, and then that gives us the ability to save
forum_thread.users, and then we can take all of the unique users in that list, but can remove the current user from this forum post.
This(
belongs_to :user) association, whoever made the post, we want to remove from there, because if you create a comment in a thread, then you don't need to get an email notification because you submitted it, so we're going to remove you from that array, and then we'll save this too, we'll just say users variable.
At this point, the models look a bit like this:
app/models/forum_thread.rb
class ForumThread < ActiveRecord::Base belongs_to :user has_many :forum_posts has_many :users, through: :forum_posts accepts_nested_attributes_for :forum_posts validates :subject, presence: true validates_associated :forum_posts end
app/models/forum_post.rb
class ForumPost< ActiveRecord::Base belongs_to :forum_thread belongs_to :user validates :body, presence: true def send_notifications! users = forum_thread.users.uniq - [user] #TODO Send an email to each of these name users end end
This will allow us to take all the users in the thread, remove you, and then we can send the email out to. So to create our mailer, to do that next step is the app/mailers folder and inside here we can create a new mailer. I'm actually going to se the
rails g mailer NotificationMailer
Rails will generate this for you if you want, it also generates this preview (test/mailers/previews/notification_mailer_preview.rb) which we're going to take a look at just a little bit later.
So now we're going back to MacVim, and we can open up the mailers/notification_mailer.rb, and it's very simple, it's a class, it inherits from ActionMailer::Base, and then there are some defaults that you can set, such as the email it comes from.
app/mailers/notification_mailer.rb
class NotificationMailer < ActionMailer::Base default from: "[email protected]" end
So we can change "[email protected]" to "[email protected]", but then we actually need to create the methods for the actual emails that are sent.
This one will be a forum_post_notification, and we're going to take the user that we want to send it to, and the forum post. What we'll do is we'll go through here, and to send this out, we're going to say:
app/models/forum_post.rb
def send_notifications! users = forum_thread.users.uniq - [user] users.each do |user| NotificationMailer.forum_post_notification(user, self).deliver_later end end
This will take advantage of te background workers if you have them and if we don't have them it will send them immediately.
Inside the notification_mailer.rb, we can cache these variables, so that we have them, and we'll have the forum_post as a variable, we can also have the user, so that we can use these in the views, and this works very similarly to how controllers do. You need to have the instance variables, here the orange ones so that you can use them in your views.
Here we need to send a mail to the user, and we want to send it to their email address. We don't need to specify from inside here (because it's specified in the default), but we can set this subject as
subject: "[GoRails] New post in #{forum_post.forum_thread.title}".
Now when there's a notification, you will see that there was a new post inside of that thread. Now we can open up the app/views/notification_mailer folder and see there's nothing in it, but we can create our templates in there now. And you might have noticed the similarities between controllers and mailers.
You've got the folder name that matches the name of the class, and rather than inheriting from application controller, you inherit from ActionMailer::Base, but each of these method names matches a template inside your views in the same folder, so they work very very similarly which is another benefit of Rails, because you know exactly where these files are going to be. So we edit the app/views/notification_mailer/forum_post_notification.erb Here we can add just any message
<h1>New Post in <%= @forum_post.forum_thread.subject %></h1> <p><%= link_to "Reply to this comment", forum_thread_url(@forum_post.forum_thread, anchor: dom_id(@forum_post)) %></p>
Coming back to our forum thread, we can write a test post, create the forum post and we'll see that it posted correctly, and if we come back to our Rails logs, we should be able to scroll up and see that the ActionMailer sent the email out.
The forum notification sent this email, "From: [email protected]" to me, and then it had the content as well, and you can see notes around this, that are notes from ActiveJob when it got the job from the delivered_later method that we sent. This is pretty neat, and we can see that it's making all these comments and it was processed form the inline thing which is why I executed it immediately and all of this has happened through the global id gem that allows us to do something like we did here where we pass in the user and the forum posts and normally you would take and pass in the user_id and this would look up the user here instead.
The global id gem basically creates a way to serialize your objects because when this happens later, you can't pass in the object immediately because that user might not exist, the forum_post might not exist, you have to look them up later, so there's a lot more to think about with the background workers, but rails is providing these things to handle this for you.
You want to make sure you're on the latest version of 4.2.0 which is beta 2 so that this all works, because you might run into problems with global id otherwise, but it adds a lot of magic in there that you can pass in objects and not have to worry about background workers actually working a little bit differently and we want to save just ID numbers so we can look them up later.
Imagine you sent an email, or created a new post, as test user, and it sends us an email in the background. Imagine that Chris Oliver was changing his email address at the exact same time and that finished first. Sending this email would be going to the wrong email address, unless you sent over the ID where we could look up Chris Oliver's email and then find out that it just changed so we can send it to the right one, rather than sending one to the old address. So there are small subtle things that you have to think about when you're using background workers, but Rails tries to help you quite a bit.
Because Rails is so helpful, they’ve even gone as far as integrating email previews into Rails itself now. So you might have used a gem like a letter opener before. So when you send these emails out, you don't actually have to actually check your email constantly and wait for it to go through the server, and that's a lot of time consuming stuff and it's definitely not testable either. So what Rails has introduced recently it seems to be a very unknown feature is that in the test directory, that file that it created before is in the mailers/previews/notification_mailer_preview.rb allows us to build a method here that we can view in the Rails application. This is only in development, but if we do a
def forum_post_notification just like we had before in our mailer. So if we get the app/mailer/notification_mailer.rb up again, let's just grab
(user, forum_post), we don't need to accept parameters this time because we're going to define those, and we're actually going to call this method. So we're going to have
NotificationMailer.forum_post_notification(User.first, ForumPost.first).deliver_now and this will actually send the email and then Rails will call this method when you visit this URL.
Let's grab the mailers here and open that up in the browser, and you can see that this view is build into Rails, it enumerates all of the mailer that you've set up previews for, so every one of those previews files, it will go through it, look at the mailer preview class name, it will show it here for you, and then all of the methods that you've created, so you can make them named accordingly, so I try to keep them matching, and then when you click on this you can get of course the view of just that mailer so you can drill down a little bit better, but when you click on the individual email, you'll be able to see that email that we saw in the terminal but in your browser. So we don't actually have any CSS in here but you can test the CSS out inside your browser and your Rails application and make sure that's just looking properly, so you don't have to send yourself an email or do any of that hard work, that's very time-consuming. You can put it here and then test this out with actual real users, you can go change
user.first to anyone that you want, you can load specific users, you could generate random users, you can do whatever you want and preview those emails just right there in your browser.
This is probably one of the most underrated and most useful features when using emails and Rails, and I highly recommend that you practice using these email previews because it will save you a crazy amount of time.
We wouldn't actually be finished without integrating a background worker thing into our application, so I'm going to open up the Gemfile and I'm going to add the gem of Sucker Punch in here, and Sucker Punch is one of the many background jobs gems out there so there's Resque, sidekiq, sucker punch. This one is very lightweight and doesn't require running a separate Rails or Ruby application to run those jobs, so it's very very easy to set up, and this is all you have to do actually.
And then we can go into config/environments/production.rb and we'll add
config.active_job.queue_adapter = :sucker_punch
The reason that we're going to do this in production only is because we actually want them to run in the background in production, but in development we don't care, we don't need to be running them in the background, it might be good to run sucker punch in the background to make sure it's working, but aside from that, you don't really need it in development because you can send those emails immediately and test them out because it's probably what you're wanting to do.
In production when you have hundreds of users on your forum sending emails and posting and interacting with different things, you want to tell active_job to change the queue adapter from inline to sucker punch or sidekiq, and that way the emails using deliver_later will send them in the background and then this (send_notifications! in the forum_post model) will execute really quickly as opposed to when we do deliver_now or regular deliver. Thoser are very slow because it actually sends out a bunch of emails.
Imagine your forum thread users list is 100 users. Well if you have to send 100 users 100 emails, that is a ton of work, and when you click "Submit Forum Post", that is going to take a very long time, and you don't want your user to be waiting around and worrying, and then if they worried when they clicked the button to create their post, and it took five seconds, they might submit it again, and then you've got to set another set of a hundred emails, and then people get duplicates and all of that.
Rails has been spending a lot of time building the Active Job API and building things like deliver_later so that by default we have lots of functionality that's easy for us to use.
I hope this was helpful explaining a bunch of the different Active Job things and we're going to come and build an Active Job notification thing, just like deliver_later, but we'll build our own from scratch in the next episode.
Transcript written by Miguel.
The only real time you need to use "self" in the model methods is when you want to assign an attribute. Not using self will create local variables. If you're just working with the values and not changing them, you don't have to use "self".
Yep, I believe so. Python makes it always explicit, but it can be a little confusing in Ruby since it isn't required to access but it is require to set attributes.
Yeah they are. Check out the Mandrill episode to see how I set that up....
Login or create an account to join the conversation. | https://gorails.com/episodes/forum-notification-emails-and-previews | CC-MAIN-2018-43 | refinedweb | 2,888 | 61.8 |
Hi,
i would like to ask about the flow direction of the tabbed pages tab bar...
i want to start the app with the tab at the far right side showing first
so i tried the following:
1. changing the Flowdirection property to Right to left
witch resulted in the title of the page changing directions but not the tab bar
2. changing the CurrentPage property at the start of the app
witch resulted in selecting the wanted tab while its not visible
in other words it selected the tab and scrolled to the far left of the tab bar...
If you want a scrollable tabbar you must define a custom renderer for achieving this. Then we could scroll the tabbar there:
[assembly: ExportRenderer(typeof(MyTabbedPage), typeof(ScrollableTabbedPageRenderer))] namespace App.Droid { public class ScrollableTabbedPageRenderer : TabbedPageRenderer { public ScrollableTabbedPageRenderer(Context context) : base(context) { } public override void OnViewAdded(Android.Views.View child) { base.OnViewAdded(child); var tabLayout = child as TabLayout; if (tabLayout != null) { tabLayout.TabMode = TabLayout.ModeScrollable; tabLayout.Post(() => { tabLayout.SetScrollPosition(tabLayout.TabCount - 1, 0, true); }); } } } }
Answers
If you only want to set the start page to the last tab, you could try the code below:
If you want to change the gesture direction we need to disable the default effect of the tabbed page on Android:
Then implement your own gestures to achieve the custom swipe.
i do but the thing is:
the app is starting, the wanted page is selected, but the tabbar is scrolled way to the other side so you don't even see the selected tab & you have to scroll to the right side again so you can see the selected tab...
Note: my tabbar is scrollable if i didn't make it clear
If you want a scrollable tabbar you must define a custom renderer for achieving this. Then we could scroll the tabbar there:
thanks for your respond,
i think this will do the trick for me but is there a non custom render solution ?
because the tabbar have the scrollable attribute in the Tabbar.axml file
so i thought there would be a way to simply scroll through it.
No, we can't.
We still need to add some code to programmatically scroll it due to your real tab items.
Tabbar.axml is only an appearance template for your Forms. We could configure the tint color, item size or other appearance properties there. | https://forums.xamarin.com/discussion/176644/flow-direction | CC-MAIN-2020-05 | refinedweb | 398 | 68.3 |
Hello,
The wixCrm.notifications.notify api function isn't currently working
It's generating:
TypeError: undefined is not an object (evaluating '_wixCrmBackend2.default.notifications')
I have literally copy and paste the code from the Corvid Reference Doc to run a test.
export function notifyOwnerOnDashboard() { wixCrm.notifications.notify( "Notification body", ["Dashboard"], { "title": "Notification Title", "actionTitle": "Click this!", "actionTarget": {"url": ""}, "recipients": {"role": "Owner"} } ); }
Just thought I should flag it!
Thanks
Chris
If you've just literally copied and pasted to test then you are missing the import wixCrm call and the onReady call at the beginning of your code.
Plus you need to have changed the url line to a url from your website, otherwise you will always get the undefined error!
"actionTarget": {"url": ""}, - this needs to be your website page.
hey,
Sorry I hadn't mentioned it that I had included it as its a default thing I always do first of all. Just gave it a go with these settings below and still comes up with
The error message is associated with line 5 of the code which is
The code that I added was as follows
In addition I've noticed that when you type wixCrm to call its functions, it's not recognised
Hey Chris,
I just noticed this too. Looks like its down or something. When you go to type in 'import' at the top, it doesn't even give the option for 'import wixCrm from 'wix-crm-backend' the only backend option it has it is 'import wixCrmBackend from 'wix-crm-backend'. It looks like we are just going to have to wait until this gets taken care of!
-Morgan
Hey Morgan,
The import function part is not producing as per the reference api, but if you copy and paste it, it still recognises
In terms of the actual API code this needs to go into the backend code structure!
And you simply call it from page code.
When I get to my office, I can show you what you need to do. To make it work.
WIX CORVID team - would be great if you could reflect the api reference for this that it should go backend and not in the page code.
Thanks
Chris
Good work Chris and thanks for pasting up the working code example below too, let's hope that the Wix team can get this changed asap as it does seem a bit odd that there is no reference to it being placed in the backend in the api section.
I hope this helps to anyone that wants to know!
To make Notifications works please follow these steps:
Create a Backend Code page call it Notifications
Place following code in Backend/Notifications
Go to desire page to insert Front end Code.
For full details on how to decide where it notify's and who it is sent to please visit
Thank you!
Hello gents,
I had implemented Chris' code and it had been working beautifully for a few weeks, but it just stopped working about 3 days ago quite inexplicably, which leads me to believe something may have changed on wix side.
Does anyone have any insights on this perhaps - I get the following errors on the developer console when I test the notification function.
@Heath H-M Thanks Heath, but which page exactly can it not access - the URL associated to notification function definitely does exist and is accessible.
I think it may be an issue with the following:
@bradosner Can you share a link to your site.
Have a look at the API Reference for the notify function itself as if you are sending to the site owner's dashboard, it looks like it has been changed slightly.
Hence why you are getting this error received back....
So from this....
Place following code in Backend/Notifications
To this instead with the "Notification body" in it instead.
I'm still getting the same error - did you get it working yourself?
I looked at the API Reference I don't think its changed from before.
@bradosner
Have you actually just tried changing your code to suit the API Reference?
Also, just try deleting the options in the brackets too of title, action, site and role, so you just simply have the () as the code below.
Plus, add in the other two channels for notification of Browser and Mobile again too.
The code has changed from the original posted in this forum post.
You need to replace the title, line with the "Notification body", line instead.
ORIGINAL
NEWER
Like I've said previously, that would explain why you are getting the error with the title and the 403 Forbidden etc.
@givemeawhisky
Are you putting this in the backend - if so how do call the function with different arguments?
I've tried it exactly as you've put it - I'm still getting the same error
Just as @bradosner , I am getting the same 403 error after altering my code based on @givemeawhisky
FrontEnd:
import {notifyOwnerOnDashboard} from 'backend/notifications.jsw'; $w.onReady(function () { notifyOwnerOnDashboard(); });
BackEnd (based on the example provided by @givemeawhisky :
import wixCrm from 'wix-crm-backend';
export function notifyOwnerOnDashboard() { wixCrm.notifications.notify( "Notification body", ["Dashboard"], { "title": "Notification Title", "actionTitle": "Click this!", "actionTarget": {"url": ""}, "recipients": {"role": "Owner"} } ); }
You don't need the file type at the end of your backend import.
Plus, you should be putting the notifications in the backend in a js file.
@givemeawhisky Removing the file type at the end of the backend import didn't help.
Changing the file type to .js caused this error:
Access to backend script 'backend/notifications.js' denied! Client-side scripts can only import web-modules (.jsw) from backend code context.
@givemeawhisky Did you manage to actually get the notifications api to work at all?
I haven't been able to get any of them to work. I have tried every possible way, i think that the notification system is broken due to the new Module Web Permissions option, or there has been a change interanally on the Wix side.
Could one of the Corvid Dev team please let us know, as this is causing major issues for various clients not being informed or certain changes on thier site.
#corvidissue
Thanks all
Chris Silvester
@Chris Silvester Hi. Thank you for letting us know. I will check this error on our side.
Regards, Alex
Looks like an issue on our end. I've reported it to our development team and update here once it is resolved.
Sorry for the inconvenience.
Regards, Alex
@Aleksander Denga This post comment took me about 2 days to find. This comment about a known issue on Wix's end should not be hidden away in a thread. It should be a pinned post where everyone can see it easily.
It would be ideal if the Corvid Forum created an actual category specifically FOR known issues.
This way we do not spend hours, days or even weeks trying to debug a code that cannot be fixed until Wix fixes it.
Because out of the entire Corvid Forum reported issues / bugs / Wix errors there is a lot more than 1 at the moment, and right now the Help Center is clearly not up to date with any of these Known Issues. I USED to go here FIRST to see if there are any known issues, but i STOPPED going here because it is clearly not reliable in anyway.
This is making it a lot harder to convince our clients that there is clear communication between Wix and the Experts / Partners.
At this point it feels like there continuous and consistent communication between Wix and the Experts / Partners when it comes to getting feedback FROM the Experts / Partners for 'new' and 'upcoming' features.
But when we actually DO post the feedback about existing features / codes it feels like all communication is lost in endless threads that MAY or MAY NOT be read by Wix.
We call regular Wix Support KNOWING they will not have any Corvid answer. Wix Support directs us to the Forum. We search through the forum hoping to find a needle in a haystack in between all the Questions by New Users, Questions by Power Users (aka Corvid Ninjas), and Spam.
Do you know how disappointing it is to find out that Wix ALREADY knew there was a problem but did NOT make the effort to make it KNOWN to us that Wix is 'on it'? Do you know that we spend more effort in reporting a problem that was ALREADY reported, yet we did not know so now we spent our time (and clients money) on something that could have taken MINUTES to find if we had a proper Category or Location to find these known issues?
Hi Aleksander, That's amazing news that I'm not going crazy! Thanks for following this up ! Thanks Chris
@Chris Silvester The issue should be fixed now. Could you please check?
@Code Queen Nayeli I can feel your frustration. Couldn't promise a quick solution here, but I'll raise this question once again to see what can be done.
Regards, Alex
It works!! | https://www.wix.com/corvid/forum/community-discussion/resolved-wixcrm-notifications-notify-not-functioning | CC-MAIN-2019-47 | refinedweb | 1,522 | 70.13 |
Advertisement
Jdbc Mysql Connection Help
I found your Jdbc Mysql Connection String tutorial very useful. I am using NetBeans IDE 6.1 and am trying to connect to mysql database. I have provided all the connection parameters correctly, but when I run the program, I get ClassNotFoundException
database query
How to sort data in MySQl if data are very large and in the sequience of ...........
1,12,2,4,13,18,16,23,3,31...
if i m using order by ASC data are coming like this 1,12,13,16,18,2,23,3,31......
give me solution for this how to sort in ascendung
JDBC Connectivity
"jdbc:mysql://localhost:3306/komal"
can anyone tell me if i created a database name Employee how can i set the path in url wat i have to write
"jdbc:mysql://localhost:3306/Employee"
pls suggest me
jdbc connection
");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://127.0.0.1...) DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/location", "root", "root...jdbc connection How to Submit data????
<%--
view
JDBC connection
JDBC connection ![alt text][1]I got exception in Connecting to a MySQL Database in Java.
The exception is ClassNotFoundException:com.mysql.jdbc.Driver
wat is the problem
JDBC
!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db... the connection between java and mysql using JDBC and saves the data into the database...JDBC code to save a data in the database I need a code to save
JDBC
con = null;
String url = "jdbc:mysql://localhost:3306/";
String db... in the database can anyone help?
The given code set up the connection between java and mysql using JDBC and saves the data into the database.
import
connection - JDBC
connection how to connect server pages to mysql Hi Friend,
To learn how to connect MySql to JSP, please visit the following link:
Thanks-Connection Pool - JDBC
{ public static void main(String[] args){ Connection con = null; String url = "jdbc:mysql://localhost:3306/"; String db = "register"...Java-Connection Pool How can I create a connection pool. My database
Jdbc Mysql Connection Url
JDBC Mysql
Connection. In this program, the code explain the JDBC url and string...
JDBC Mysql Connection Url
...; "jdbc:mysql://localhost:3306/komal" +
"?user
jdbc mysql - JDBC
=DriverManager.getConnection("jdbc:mysql://localhost:3306/ram","root","root...(String[] args) {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://192.168.10.211:3306/";
String dbName = "amar";
String userName | http://roseindia.net/tutorialhelp/allcomments/155533 | CC-MAIN-2015-22 | refinedweb | 408 | 50.43 |
C# and Code Organization: C# Language Accessories
Command Line Options
In Lesson
1, we saw that, to see the result of an application, you must execute it. To
make this possible,, Microsoft Visual C# ships with an internal program. In our lessons, Microsoft .NET Framework is a program.
In this book, we will create our program using Microsoft Visual C# 2005 Express Edition or Professional
but if you didn't have it, you would still be
able to create and execute applications. To do this, at the Command Prompt, you
would type csc, followed by the name
of the file that contains the code with its extension. An example would be:
csc Filename.cs
When you do this, an executable with the same name as the
file is created. If you want, you can ask the
compiler to produce an executable using the name of your choice. To do this, you
would compile the project using the following formula:
csc /out:NameOfExecutate.exe Filename.cs
The NameOfExecutate factor in our formula represents
the name you want the executable to have. If the name you want is in one word,
you can just type it. If you want a name made of various words, you can include
those words in double-quotes
The FileName factor is one we
are familiar with.
Unsafe Code
When C# was invented, one of its biggest goals was to avoid
some of the difficulties of C/C++. Among them was the use of pointers. C/C++ uses pointers to refer to the area in memory
where a value is located. C# highly avoids pointers and takes over memory
management as opposed to letting the programmer take care of that aspect of an
application. You can still use pointers in C# in extreme cases when. Here is an example:
using System;
class Exercise
{
unsafe static void Main()
{
int Length = 224;
int *Len = &Length;
Console.Write("Length ");
Console.WriteLine(Length);
Console.Write("Length ");
Console.WriteLine(*Len);
Console.WriteLine();
Length = 804;
Console.Write("Length ");
Console.WriteLine(Length);
Console.Write("Length ");
Console.WriteLine(*Len);
}
}
To compile the
application, you must indicate that you are using unsafe code. To do that, use
the /unsafe modifier. Here is an example:
csc /unsafe Exercise.cs
To apply this option in Microsoft Visual C# 2005 Express Edition or Professional, on the main menu, you can click Project -> Project
Properties... In the Build section, click the Allow Unsafe Code check box:
Code Editor Region Delimiter
Microsoft Visual C# provides various to
assist you with code writing and management., methods, etc.
Besides, or instead of, the sections of code created by the
Code Editor, if you want, you can create your own sections. To do
this, start the section with
#region Whatever
and end it with
#endregion Whatever
When and where you start, the #region
expression is required. On the right side of this expression, you can type
anything you want on the line. To end the section, type #endregion,
followed by anything you want. Consider the following example:
using System;
class House
{
void Create()
{
}
}
#region These are classes used for Student Registration
class Car
{
void Build()
{
}
}
class Student
{
void Register()
{
}
}
#endregion We can just stop it here
class Program
{
static void Main()
{
}
}
You don't have to type anything on the right side of #endregion. After creating the region, the Code Editor would display a -
button to the left side of #region with a line from there to the
left of #endregion:
This then allows you to expand and collapse that section at
will:
We mentioned that you didn't have to type anything on the
right side of #endregion and you could leave it empty. In our
example, notice that there is a rectangle with gray lines around the string that
follows #region. This rectangle doesn't cover the string that
follows #endregion. This means that if you don't type anything on
the right side of #endregion, that section on the right side the #region line would not show. | http://www.functionx.com/csharp2/fundamentals/Lesson04b.htm | CC-MAIN-2017-30 | refinedweb | 666 | 60.95 |
By prateek Joshi
Compile | Flin
Source: analyticsvidhya
summary
- Are you excited about the idea of smart city? If so, you’ll love this tutorial on building your own vehicle detection system
- Before we go into the implementation part, we will first learn how to detect moving objects in the video
- We will use opencv and python to build an automatic vehicle detector
introduce
I like the idea of smart city. Automatic intelligent energy system, power grid, the idea of one button access port and so on. This is a fascinating concept! To be honest, it’s a data scientist’s dream, and I’m glad that many cities around the world are moving towards smarter things.
One of the core components of intelligent city is automatic traffic management. This makes me think – can I use my scientific knowledge of data to build a vehicle detection model and play a role in intelligent transportation management?
Think about it. If you can integrate a vehicle detection system into a traffic light camera, you can easily track many useful things at the same time:
- How many cars are there at the intersection during the day?
- When is the traffic jam?
- What kind of intersection are heavy vehicles passing through?
- Is there any way to optimize traffic and distribute it through different streets?
There are many other examples that will not be listed one by one. Applications are endless!
We humans can easily detect and recognize objects from complex scenes in a flash. However, it is necessary for us to learn to use computer vision algorithm to detect objects.
Therefore, in this paper, we will establish an automatic vehicle detector and counter model. Here’s what you can look forward to:
Note: do not understand the new concepts of deep learning and computer vision? Here are two popular courses to start your deep learning journey:
- Foundation of deep learning(… )
- Computer vision using deep learning(… )
catalog
- The idea of moving object detection in video
- Real world use cases of object detection in video
Basic concepts of video target detection
- Frame difference
- Image threshold
- Detection profile
- Image expansion
- Construction of vehicle detection system based on OpenCV
The idea of moving object detection in video
Object detection is an attractive field in computer vision. When we deal with video data, it reaches a whole new level of complexity, but it pays off!
We can use target detection algorithms to perform super useful high-value tasks, such as surveillance, traffic management, fighting crime and so on. The following GIF diagram illustrates this idea:
In target detection, we can perform many subtasks, such as calculating the number of targets, finding the relative size of targets or finding the relative distance between targets. They help solve some of the most difficult tasks.
If you want to learn target detection from scratch, I suggest you use the following tutorial:
- The basic target detection algorithm is introduced step by step(… )
- Real time target detection using slimyolov3(… )
- Other target detection items and resources(… )
Let’s look at some exciting real-world target detection use cases.
Real world use cases of object detection in video
Nowadays, video object detection is widely used in various industries. Use cases range from video surveillance to sports broadcasting to robot navigation.
The good news is that in future video object detection and tracking use cases, the possibilities are endless. Here I list some interesting applications:
- Crowd count(… )
- License plate detection and recognition
- Ball tracking in motion(… )
- Robotics
- Traffic management (we’ll see this idea in this article)
Basic concepts of video target detection
Before you start building a video detection system, you should know some key concepts. Once you are familiar with these basic concepts, you can build your own inspection system for any use case you choose.
So, how do you want to detect moving objects in the video?
Our goal is to capture the coordinates of a moving object and highlight it in the video. Consider this frame in the following video:
We hope our model can detect moving objects in the video, as shown in the figure above. A moving car is detected and a bounding box is created around the car.
There are many ways to solve this problem. You can train a deep learning model for target detection, or you can choose a pre trained model and fine tune it according to your data. However, these methods are supervised learning methods, which need labeled data to train the target detection model.
In this article, we willThis paper focuses on unsupervised target detection in video, that is, target detection without any label data。 We will useFrame difference technology。 Let’s see how it works!
Frame difference
A video is a set of frames stacked together in the correct order. So, when we see an object moving in the video, it means that the object is in a different position on each successive frame.
If we assume that no object moves in a pair of consecutive frames other than the target, then the pixel difference between the first frame and the second frame highlights the pixel of the moving target. Now, we get the pixels and coordinates of the moving object. This is how frame difference works.
for instance. Consider the following two frames in the video:
Can you see the difference between the two frames?
The position of the hand holding the pen changes from frame 1 to frame 2. The rest of the objects did not move at all. So, as I mentioned earlier, in order to locate the moving target, we will perform frame difference. The results were as follows:
You can see the highlight or white area, which is where the hand first appears. In addition, the edge of Notepad will also be highlighted. This may be because the movement of the hand changes the light. It is suggested that unnecessary detection of stationary objects should not be carried out. Therefore, we need to perform some image preprocessing steps on the frame.
Image threshold
In this method, the pixel value of the gray image is specified as one of the two values representing the black and white color according to the threshold value. Therefore, if the value of a pixel is greater than a threshold, it is given a value, otherwise it is assigned another value.
In this example, we will apply an image threshold to the output image of the frame difference in the previous step:
As you can see, most of the unwanted highlights have disappeared. The highlighted Notepad edge is no longer visible. The composite image can also be called a binary image because there are only two colors in it. In the next step, we’ll see how to capture these highlights.
Detection profile
Contours are used to identify the shape of areas in an image that have the same color or intensity. The contour is the boundary around the target area. Therefore, if we apply contour detection to the image after the threshold step, we will get the following results:
The white area is surrounded by light gray boundaries, which are the contours. We can easily get the coordinates of these contours. This means that we can get the location of the highlight.
Notice that there are multiple highlighted areas, each surrounded by a profile. In our example, the contour with the largest area is the area we expect. Therefore, it is best to have as few contours as possible.
In the image above, there are still some unnecessary fragments of white areas. There is still room for improvement. The idea is to merge nearby white areas to get less contours, so we can use another technique called image blotting.
Image expansion
This is the convolution operation of the image, in which the core (matrix) is transferred to the whole image. For your intuition, the image on the right is an enlarged version of the image on the left:
So, let’s inflate our image, and then we’ll find the contour again:
Many fragmented regions have proved to be integrated. Now we can find the outline again in this image:
Here, we have only four candidate profiles, from which we can choose one with the largest area. You can also draw them on the original frame to see how the contours revolve around the moving target:
Building vehicle detection system with OpenCV and python
We are going to build our vehicle detection system! In this implementation, we will use the computer vision library opencv (version 4.0.0)(… 。 Let’s first import the required libraries and modules.
Import library
import os import re import cv2 # opencv library import numpy as np from os.path import isfile, join import matplotlib.pyplot as plt
Import video frames
Please download the frames of the original video from this link.…
Save the frame in a folder called frames in your working directory. From this folder, we will import frames and save them in the list:
# get file names of the frames col_frames = os.listdir('frames/') # sort file names col_frames.sort(key=lambda f: int(re.sub('\D', '', f))) # empty list to store the frames col_images=[] for i in col_frames: # read the frames img = cv2.imread('frames/'+i) # append the frames to the list col_images.append(img)
Data exploration
Let’s show two consecutive frames:
# plot 13th frame i = 13 for frame in [i, i+1]: plt.imshow(cv2.cvtColor(col_images[frame], cv2.COLOR_BGR2RGB)) plt.title("frame: "+str(frame)) plt.show()
It’s hard to find a difference between the two frameworks, isn’t it? As mentioned earlier, obtaining the difference between the pixel values of two consecutive frames will help us to observe the moving target. So let’s use this technique in the two frames above:
# convert the frames to grayscale grayA = cv2.cvtColor(col_images[i], cv2.COLOR_BGR2GRAY) grayB = cv2.cvtColor(col_images[i+1], cv2.COLOR_BGR2GRAY) # plot the image after frame differencing plt.imshow(cv2.absdiff(grayB, grayA), cmap = 'gray') plt.show()
Now we can clearly see the moving target in frames 13 and 14. Everything else that doesn’t move is subtracted.
Image preprocessing
Let’s see what happens when thresholds are applied to the above image:
diff_image = cv2.absdiff(grayB, grayA) # perform image thresholding ret, thresh = cv2.threshold(diff_image, 30, 255, cv2.THRESH_BINARY) # plot image after thresholding plt.imshow(thresh, cmap = 'gray') plt.show()
Now, moving objects (vehicles) look more like what we expect, and most of the noise (unwanted white areas) are gone. However, the highlighted areas are a bit fragmented. Therefore, we can apply image dilation to the image:
# apply image dilation kernel = np.ones((3,3),np.uint8) dilated = cv2.dilate(thresh,kernel,iterations = 1) # plot dilated image plt.imshow(dilated, cmap = 'gray') plt.show()
Moving objects have more solid highlights. You want no more than 3 contours per target in the frame.
However, we will not use the entire framework to detect moving vehicles. We will first select an area, if the vehicle enters the area, only that area is detected.
So let me show you the areas we’re going to use:
# plot vehicle detection zone plt.imshow(dilated) cv2.line(dilated, (0, 80),(256,80),(100, 0, 0)) plt.show()
The area below the horizontal line y = 80 is our vehicle detection area. We will only detect any movement in this area. You can also create your own detection area.
Now let’s find the contour in the detection area of the above frame:
# find contours contours, hierarchy = cv2.findContours(thresh.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
The above code looks up all the contours in the entire image and saves them in the variable “contours.”. Since we only need to find the contour existing in the detection area, we will check the detected contour twice.
The first check is whether the Y coordinate of the upper left corner of the contour should be greater than or equal to 80 (I include another check here, the X coordinate is less than or equal to 200). Another check is that the area of the contour should be greater than or equal to 25. With the help of the CV2. Courtoarea() function, you can find the contour area.
valid_cntrs = [] for i,cntr in enumerate(contours): x,y,w,h = cv2.boundingRect(cntr) if (x <= 200) & (y >= 80) & (cv2.contourArea(cntr) >= 25): valid_cntrs.append(cntr) # count of discovered contours len(valid_cntrs)
Next, let’s draw the outline and the original frame:
dmy = col_images[13].copy() cv2.drawContours(dmy, valid_cntrs, -1, (127,200,0), 2) cv2.line(dmy, (0, 80),(256,80),(100, 255, 255)) plt.imshow(dmy) plt.show()
That’s cool! Only the contour of the vehicle within the detection area is visible. This is how we detect the vehicle in the whole picture
Vehicle detection in video
It’s time to apply the same image transformation and preprocessing to all frames and find the desired contour. Again, we will follow these steps:
- Apply frame difference to each pair of consecutive frames
- Apply the image threshold to the output image of the previous step
- Enlarge the output image of the previous step
- Find the contour in the output image of the previous step
- Detection of candidate contours in the region
- Save frame and final outline
# kernel for image dilation kernel = np.ones((4,4),np.uint8) # font style font = cv2.FONT_HERSHEY_SIMPLEX # directory to save the ouput frames pathIn = "contour_frames_3/" for i in range(len(col_images)-1): # frame differencing grayA = cv2.cvtColor(col_images[i], cv2.COLOR_BGR2GRAY) grayB = cv2.cvtColor(col_images[i+1], cv2.COLOR_BGR2GRAY) diff_image = cv2.absdiff(grayB, grayA) # image thresholding ret, thresh = cv2.threshold(diff_image, 30, 255, cv2.THRESH_BINARY) # image dilation dilated = cv2.dilate(thresh,kernel,iterations = 1) # find contours contours, hierarchy = cv2.findContours(dilated.copy(), cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) # shortlist contours appearing in the detection zone valid_cntrs = [] for cntr in contours: x,y,w,h = cv2.boundingRect(cntr) if (x <= 200) & (y >= 80) & (cv2.contourArea(cntr) >= 25): if (y >= 90) & (cv2.contourArea(cntr) < 40): break valid_cntrs.append(cntr) # add contours to original frames dmy = col_images[i].copy() cv2.drawContours(dmy, valid_cntrs, -1, (127,200,0), 2) cv2.putText(dmy, "vehicles detected: " + str(len(valid_cntrs)), (55, 15), font, 0.6, (0, 180, 0), 2) cv2.line(dmy, (0, 80),(256,80),(100, 255, 255)) cv2.imwrite(pathIn+str(i)+'.png',dmy)
Prepare the video
Here, we add contours for all moving vehicles in all frames. Now it’s time to stack frames and create videos:
# specify video name pathOut = 'vehicle_detection_v3.mp4' # specify frames per second fps = 14.0
Next, we’ll read the last frame in the list:
frame_array = [] files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))] files.sort(key=lambda f: int(re.sub('\D', '', f)))
for i in range(len(files)): filename=pathIn + files[i] #read frames img = cv2.imread(filename) height, width, layers = img.shape size = (width,height) #inserting the frames into an image array frame_array.append(img)
Finally, we will use the following code to create a target detection video:
out = cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*'DIVX'), fps, size) for i in range(len(frame_array)): # writing to a image array out.write(frame_array[i]) out.release()
Congratulations on learning vehicle target detection!
Endnote
In this tutorial, we learned how to use frame difference technology to perform moving object detection in video. We also discuss some concepts of target detection and image processing. Then we use OpenCV to build our own moving object detection system.
I am sure that using the techniques and methods learned in this article, you will build your own version of the target detection system.
Link to the original text:…
Welcome to visit pan Chuang AI blog station:
Sklearn machine learning Chinese official document:
Welcome to pay attention to pan Chuang blog resource collection station: | https://developpaper.com/using-opencv-and-python-to-build-our-own-vehicle-detection-model/ | CC-MAIN-2021-43 | refinedweb | 2,634 | 56.55 |
22 June 2011 11:45 [Source: ICIS news]
LONDON (ICIS)--Bayer MaterialScience (BMS) has broken ground on the third phase of expanding its polymer research & development (R&D) centre in ?xml:namespace>
The centre is scheduled to be operational by the second half of 2012, BMS added.
The project is part of Bayer Group’s €1bn ($1.45bn) investment plan – announced in December 2010 – to expand its facilities in Shanghai with an eye on generating about €5bn in total sales from the Greater China region by 2015.
“
He added that
“This expansion of our R&D facility is an important part of our large and continuous investment here in
Following the expansion, the number of employees at the polymer R&D centre is planned to almost double to about 260 workers.
( | http://www.icis.com/Articles/2011/06/22/9471597/bayer-begins-further-expansion-of-polymer-rd-centre-in.html | CC-MAIN-2014-42 | refinedweb | 131 | 54.97 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.