text stringlengths 20 1.01M | url stringlengths 14 1.25k | dump stringlengths 9 15 ⌀ | lang stringclasses 4
values | source stringclasses 4
values |
|---|---|---|---|---|
Blender 3D: Noob to Pro/Advanced Tutorials/Blender Scripting/A User Interface For Your Addon
StartEdit .
Your First PanelEdit
A panel is defined by subclassing the bpy.types.Panel class. You set the value of various attributes (bl_space_type, bl_region_type, bl_category and bl_context) to determine the context in which the panel will appear, and also give a title to the panel (bl_label):
class TetrahedronMakerPanel(bpy.types.Panel): bl_space_type = "VIEW_3D" bl_region_type = "TOOLS" bl_context = "objectmode" bl_category = "Create" bl_label = "Add Tetrahedron"
Those first three attributes cause the panel to appear in the Tool Shelf, but only while the 3D View is in Object mode.The bl_category line determines the toolbar tab the addon is placed in, and only applies to the toolbars with tabs (added 2.7). Specify any existing tab, or define a new one. SupportEdit TogetherEdit
Here is the complete script for the addon as it stands now:
import math import bpy import mathutils class TetrahedronMakerPanel(bpy.types.Panel): bl_space_type = "VIEW_3D" bl_region_type = "TOOLS" bl_context = "objectmode" bl_category = "Create""}, 2,); in the tab you have specified,. | https://en.m.wikibooks.org/wiki/Blender_3D:_Noob_to_Pro/Advanced_Tutorials/Python_Scripting/Addon_User_Interface | CC-MAIN-2022-40 | en | refinedweb |
table of contents
NAME¶
ng_car — Committed
Access Rate netgraph node type
SYNOPSIS¶
#include
<netgraph/ng_car.h>
DESCRIPTION¶
The
car node type limits traffic flowing
through it using:
- Single rate three color marker as described in RFC 2697,
- Two rate three color marker as described in RFC 2698,
- RED-like rate limit algorithm used by Cisco,
- Traffic shaping with RED.
HOOKS¶
This node type supports the following hooks:
- upper
- Hook leading to upper layer protocols.
- lower
- Hook leading to lower layer protocols.
Traffic flowing from upper to lower is considered downstream traffic. Traffic flowing from lower to upper is considered upstream traffic.
MODES OF OPERATION¶¶ { uint64_t cbs; /* Committed burst size (bytes) */ uint64_t ebs; /* Exceeded/Peak burst size (bytes) */ uint64_t cir; /* Committed */ }; /* possible actions (..._action) */ enum { NG_CAR_ACTION_FORWARD = 1, NG_CAR_ACTION_DROP }; /* operation modes (mode) */ enum { NG_CAR_SINGLE_RATE = 0, NG_CAR_DOUBLE_RATE, NG_CAR_RED, NG_CAR_SHAPE }; /* mode options (opt) */ #define NG_CAR_COUNT_PACKETS 2 struct ng_car_bulkconf { struct ng_car_hookconf upstream; struct ng_car_hookconf downstream; };
NGM_CAR_GET_STATS(
getstats)
- Return node statistics as struct ng_car_bulkstats
struct ng_car_hookstats { uint64_t passed_pkts; /* Counter for passed packets */ uint64_t droped_pkts; /* Counter for dropped packets */ uint64_t green_pkts; /* Counter for green packets */ uint64_t yellow_pkts; /* Counter for yellow packets */ uint64_t red_pkts; /* Counter for red packets */ uint64_t errors; /* Counter for operation errors */ }; struct ng_car_bulkstats { struct ng_car_hookstats upstream; struct ng_car_hookstats downstream; };
NGM_CAR_CLR_STATS(
clrstats)
- Clear node statistics.
NGM_CAR_GETCLR_STATS(
getclrstats)
- Atomically return and clear node statistics.
SHUTDOWN¶
This node shuts down upon receipt of a
NGM_SHUTDOWN control message, or when all hooks have
been disconnected.
EXAMPLES¶
Limit outgoing data rate over fxp0 Ethernet interface to 20Mbit/s and incoming packet rate to 5000pps.
/usr/sbin/ngctl -f- <<-SEQ mkpeer fxp0: car lower lower name fxp0:lower fxp0_car connect fxp0: fxp0_car: upper upper msg fxp0_car: setconf { downstream={ cir=20000000 cbs=2500000 ebs=2500000 greenAction=1 yellowAction=1 redAction=2 mode=2 } upstream={ cir=5000 cbs=100 ebs=100 greenAction=1 yellowAction=1 redAction=2 mode=2 opt=2 } } SEQ
SEE ALSO¶
J. Heinanen, A Single Rate Three Color Marker, RFC 2697.
J. Heinanen, A Two Rate Three Color Marker, RFC 2698.
AUTHORS¶
Nuno Antunes
<nuno.antunes@gmail.com>
Alexander Motin <mav@FreeBSD.org>
BUGS¶
At this moment only DROP and FORWARD actions are implemented. | https://manpages.debian.org/bullseye/freebsd-manpages/ng_car.4freebsd.en.html | CC-MAIN-2022-40 | en | refinedweb |
Each Answer to this Q is separated by one/two green lines.
I use Jupyter Notebook to make analysis of datasets. There are a lot of plots in the notebook, and some of them are 3d plots.
I’m wondering if it is possible to make the 3d plot interactive, so I can later play with it in more details?
Maybe we can add a button on it? Clicking it can pop out a 3d plot and people can zoom, pan, rotate etc.
My thougths:
1. matplotlib, %qt
This does not fit my case, because I need to continue plot after the 3d plot.
%qt will interfere with later plots.
2. mpld3
mpld3 is almost ideal in my case, no need to rewrite anything, compatible with matplotlib. However, it only support 2D plot. And I didn’t see any plan working on 3D ().
3. bokeh + visjs
Didn’t find any actualy example of 3d plot in
bokeh gallery. I only find, which uses
visjs.
4. Javascript 3D plot?
Since what I need is just line and surce, is it possible to pass the data to js plot using js in the browser to make it interacive? (Then we may need to add 3d axis as well.) This may be similar to
visjs, and
mpld3.
try:
%matplotlib notebook
EDIT for JupyterLab users:
Follow the instructions to install jupyter-matplotlib
Then the magic command above is no longer needed, as in the example:
# Enabling the `widget` backend. # This requires jupyter-matplotlib a.k.a. ipympl. # ipympl can be install via pip or conda. %matplotlib widget # aka import ipympl import matplotlib.pyplot as plt plt.plot([0, 1, 2, 2]) plt.show()
Finally, note Maarten Breddels’ reply; IMHO ipyvolume is indeed very impressive (and useful!).
There is a new library called ipyvolume that may do what you want, the documentation shows live demos. The current version doesn’t do meshes and lines, but master from the git repo does (as will version 0.4). (Disclaimer: I’m the author)
You may go with Plotly library. It can render interactive 3D plots directly in Jupyter Notebooks.
To do so you first need to install Plotly by running:
pip install plotly
You might also want to upgrade the library by running:
pip install plotly --upgrade
After that in you Jupyter Notebook you may write something like:
# Import dependencies import plotly import plotly.graph_objs as go # Configure Plotly to be rendered inline in the notebook. plotly.offline.init_notebook_mode() # Configure the trace. trace = go.Scatter3d( x=[1, 2, 3], # <-- Put your data instead y=[4, 5, 6], # <-- Put your data instead z=[7, 8, 9], # <-- Put your data instead mode="markers", marker={ 'size': 10, 'opacity': 0.8, } ) # Configure the layout. layout = go.Layout( margin={'l': 0, 'r': 0, 'b': 0, 't': 0} ) data = [trace] plot_figure = go.Figure(data=data, layout=layout) # Render the plot. plotly.offline.iplot(plot_figure)
As a result the following chart will be plotted for you in Jupyter Notebook and you’ll be able to interact with it. Of course you will need to provide your specific data instead of suggeseted one.
A solution I came up with is to use a vis.js instance in an iframe. This shows an interactive 3D plot inside a notebook, which still works in nbviewer. The visjs code is borrowed from the example code on the 3D graph page
A small notebook to illustrate this: demo
The code itself:
from IPython.core.display import display, HTML import json def plot3D(X, Y, Z, height=600, <script src=""></script> <div id="pos" style="top:0px;left:0px;position:absolute;"></div> <div id="visualization"></div> <script type="text/javascript"> var data = new vis.DataSet(); data.add(""" + json.dumps(data) + """); var </iframe>" display(HTML(htmlCode))
For 3-D visualization pythreejs is the best way to go probably in the notebook. It leverages the interactive widget infrastructure of the notebook, so connection between the JS and python is seamless.
A more advanced library is bqplot which is a d3-based interactive viz library for the iPython notebook, but it only does 2D
| https://techstalking.com/programming/python/python-matplotlib-make-3d-plot-interactive-in-jupyter-notebook/ | CC-MAIN-2022-40 | en | refinedweb |
Each Answer to this Q is separated by one/two green lines.
I’m working on an app that to do some facial recognition from a webcam stream. I get base64 encoded data uri’s of the canvas and want to use it to do something like this:
cv2.imshow('image',img)
The data URI looks something like this:
snippet" data-
<img src=">
The official doc says, that
imread accepts a file path as the argument. From this SO answer, if I do something like:
import base64 imgdata = base64.b64decode(imgstring) #I use imgdata as this variable itself in references below filename="some_image.jpg" with open(filename, 'wb') as f: f.write(imgdata)
The above code snippet works and the image file gets generated properly. However I don’t think so many File IO operations are feasible considering I’d be doing this for every frame of the stream. I want to be able to read the image into the memory directly creating the
img object.
I have tried two solutions that seem to be working for some people.
pilImage = Image.open(StringIO(imgdata)) npImage = np.array(pilImage) matImage = cv.fromarray(npImage)
I get
cvnot defined as I have openCV3 installed which is available to me as
cv2module. I tried
img = cv2.imdecode(npImage,0), this returns nothing.
Getting the bytes from decoded string and converting it into an numpy array of sorts
file_bytes = numpy.asarray(bytearray(imgdata), dtype=numpy.uint8) img = cv2.imdecode(file_bytes, 0) #Here as well I get returned nothing
The documentation doesn’t really mention what the
imdecode function returns. However, from the errors that I encountered, I guess it is expecting a
numpy array or a
scalar as the first argument. How do I get a handle on that image in memory so that I can do
cv2.imshow('image',img) and all kinds of cool stuff thereafter.
I hope I was able to make myself clear.
This worked for me on python 2, and doesn’t require PIL/pillow or any other dependencies (except cv2):
Edit: for python3 use
base64.b64decode(encoded_data) to decode instead.
import cv2 import numpy as np def data_uri_to_cv2_img(uri): encoded_data = uri.split(',')[1] nparr = np.fromstring(encoded_data.decode('base64'), np.uint8) img = cv2.imdecode(nparr, cv2.IMREAD_COLOR) return img data_uri = " img = data_uri_to_cv2_img(data_uri) cv2.imshow(img)
This is my solution for python 3.7 and without using PIL
import base64 def readb64(uri): encoded_data = uri.split(',')[1] nparr = np.fromstring(base64.b64decode(encoded_data), np.uint8) img = cv2.imdecode(nparr, cv2.IMREAD_COLOR) return img
i hope that this solutions works for all
You can just use both cv2 and pillow like this:
import base64 from PIL import Image import cv2 from StringIO import StringIO import numpy as np def readb64(base64_string): sbuf = StringIO() sbuf.write(base64.b64decode(base64_string)) pimg = Image.open(sbuf) return cv2.cvtColor(np.array(pimg), cv2.COLOR_RGB2BGR) cvimg = readb') cv2.imshow(cvimg)
I found this simple solution.
import cv2 import numpy as np import base64 image = "" # raw data with base64 encoding decoded_data = base64.b64decode(image) np_data = np.fromstring(decoded_data,np.uint8) img = cv2.imdecode(np_data,cv2.IMREAD_UNCHANGED) cv2.imshow("test", img) cv2.waitKey(0)
Source :
| https://techstalking.com/programming/python/read-a-base-64-encoded-image-from-memory-using-opencv-python-library/ | CC-MAIN-2022-40 | en | refinedweb |
Write a Program to find the Python String Length. The python programming language provides a building-in standard function called len. It can help you to find the length of a string or any other object type.
In this program, we declared an empty string. Next, we find the length of a string in Python using the len function. Next, we find the total characters in the tutorial gateway and learn programming.
Remember, this len function counts empty space as 1. It means the total number of characters in ‘he ll’ is 5.
str1 = '' print("\nstr1 = ", str1) print(len(str1)) str2 = 'Tutorial Gateway' print("\nstr2 = ", str2) print(len(str2)) str3 = 'Learn Programming' print("\nstr3 = ", str3) print(len(str3))
str1 = 0 Tutorial Gateway 16 str3 = Learn Programming 17
This program is the same as the first example. However, we allow the users to enter their own words and then find the character count of a user given one.
str1 = input("Please enter the sentence you want : ") print("\n Original str1 = ", str1) print("The length of a Given sentence = ", len(str1))
Please enter the sentence you want : Py Programming Language Original str1 = Py Programming Language The length of a Given sentence = 23
Let me try with different sentences.
Python String Length Example
In all the above-specified examples, we used the built-in function len. However, you can also find the length without using any built-in function. In interviews, this can test your coding skills.
In this program, we are using For Loop to iterate each character in a user-given sentence. Inside the Loop, we increment the val to count the characters. Next, outside the loop, we are printing the final output.
Please refer to Strings, For Loop, and len articles in Python.
str1 = input("Please enter the text you want : ") val = 0 print("\n str1 = ", str1) for i in str1: val = val + 1 print("Total = ", val)
Please enter the text you want : Tutorial Gateway str1 = Tutorial Gateway Total = 16
In this example, we are using Functions to separate the logic to find the length. Next, we are calling that function to find the characters in the user-entered sentence.
def stringLength(string): length = 0 for i in string: length = length + 1 return length str1 = input("Please enter the text you want : ") print("\n str1 = ", str1) strlength = stringLength(str1) print("Characters = ", strlength)
Please enter the text you want : hello str1 = hello Characters = 5
Let me re-run the len program and enter a new word. It can help you understand it in more detail.
Please enter the text you want : Hello Guys str1 = Hello Guys Characters = 10 | https://www.tutorialgateway.org/python-string-length/ | CC-MAIN-2022-40 | en | refinedweb |
Post-nonlinear causal models
Algorithm Introduction
Causal discovery based on the post-nonlinear (PNL 1) causal models. If you would like to apply the method to more than two variables, we suggest you first apply the PC algorithm and then use pair-wise analysis in this implementation to find the causal directions that cannot be determined by PC.
(Note: there are some potential issues in the current implementation of PNL. We are working on them and will update as soon as possible.)
Usage
from causallearn.search.FCMBased.PNL.PNL import PNL pnl = PNL() p_value_foward, p_value_backward = pnl.cause_or_effect(data_x, data_y)
Parameters
data_x: input data (n, 1), n is the sample size.
data_y: output data (n, 1), n is the sample size.
Returns
pval_forward: p value in the x->y direction.
pval_backward: p value in the y->x direction. | https://causal-learn.readthedocs.io/en/latest/search_methods_index/Causal%20discovery%20methods%20based%20on%20constrained%20functional%20causal%20models/pnl.html | CC-MAIN-2022-40 | en | refinedweb |
Calling strategy from strategy leads to maximum recursion depth error
Hi, i am currently struggling with a problem I can't find the solution too.
The basic idea is the following:
I have a BaseStrategy which inherits from backtrader.Strategy
I have a PivotStrategy class which inherits from BaseStrategy
I have a LevelStrategy class which inherits from BaseStrategy
The LevelStrategy contains code to analyse some candlestick patterns around key levels
Now, in PivotStrategy I want to call an analysis method of LevelStrategy if the current price is around a pivot level to see if the price action gives any indication of breakout or reversal.
If I use the following code I get the error message shown below:
class BaseStrategy(backtrader.Strategy): @abstractmethod def analyse_ticker(self): pass
from trader.executor import BaseStrategy from trader.strategies.LevelStrategy import LevelsStrategy class PivotStrategy(BaseStrategy): def __init__(self, alert_only: bool = False): super().__init__() def analyse_ticker(self): # Do stuff ls = LevelsStrategy() return_value = ls.apply_strategy() return return_value def next(self): self.analyse_ticker()
from trader.executor import BaseStrategy class LevelsStrategy(BaseStrategy): def analyse_ticker(self): return 0.0
import backtrader as bt from trader.strategies.PivotStrategy import PivotStrategy if __name__ == "__main__": cerebro = bt.Cerebro() data = bt.feeds.GenericCSVData(dataname='data.csv', headers=True, dtformat=('%Y-%m-%dT%H:%M:%S%z'), timeframe=bt.TimeFrame.Minutes, datetime=1, open=2, high=3, low=4, close=5, volume=6, tz=pytz.timezone('UTC')) cerebro.adddata(data) cerebro.addstrategy(PivotStrategy) cerebro.addsizer(bt.sizers.SizerFix, stake=3) cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='mysharpe') cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="mytrades") start_portfolio_value = cerebro.broker.getvalue() thestrats = cerebro.run()
The stacktrace:
Traceback (most recent call last): File ".../pycharm/plugins/python/helpers/pydev/_pydevd_bundle/pydevd_trace_dispatch_regular.py", line 422, in __call__ if not is_stepping and frame_cache_key in cache_skips: RecursionError: maximum recursion depth exceeded in comparison Fatal Python error: Cannot recover from stack overflow. Python runtime state: initialized Thread 0x00007feba7b38640 (most recent call first): File "/usr/lib/python3.8/threading.py", line 306 in wait File "/usr/lib/python3.8/threading.py", line 558 in wait File ".../pycharm/plugins/python/helpers/pydev/pydevd.py", line 150 in _on_run File ".../pycharm/plugins/python/helpers/pydev/_pydevd_bundle/pydevd_comm.py", line 218 in run File "/usr/lib/python3.8/threading.py", line 932 in _bootstrap_inner File "/usr/lib/python3.8/threading.py", line 890 in _bootstrap Current thread 0x00007febc7a67740 (most recent call first): File ".../pycharm/plugins/python/helpers/pydev/_pydevd_bundle/pydevd_trace_dispatch_regular.py", line 422 in __call__ File ".../venv/lib/python3.8/site-packages/backtrader/lineroot.py", line 304 in _stage1 File ".../venv/lib/python3.8/site-packages/backtrader/lineiterator.py", line 189 in _stage1 File ".../venv/lib/python3.8/site-packages/backtrader/lineiterator.py", line 196 in _stage1 ....
I have already identified that the problem is the code 'ls = LevelsStrategy()'. If I remove that line and the following one, the execution runs through.
However, currently I can't think of a solution.
Any ideas on how to implement this?
Thank you.
- Carlus Remod last edited by
Cupcake made at home are a lot more than just a delicious dessert. They can be an interesting and fun activity that you and your family can enjoy together to make Cupcake Delivery Sydney. Cupcakes make great party favors, teach children about kitchen hygiene, help with math skills, and much more! | https://community.backtrader.com/topic/5456/calling-strategy-from-strategy-leads-to-maximum-recursion-depth-error/? | CC-MAIN-2022-40 | en | refinedweb |
Each Answer to this Q is separated by one/two green lines.
Python decorators are fun to use, but I appear to have hit a wall due to the way arguments are passed to decorators. Here I have a decorator defined as part of a base class (the decorator will access class members hence it will require the self parameter).
class SubSystem(object): def UpdateGUI(self, fun): #function decorator def wrapper(*args): self.updateGUIField(*args) return fun(*args) return wrapper ...
I’ve omitted the rest of the implementation. Now this class is a base class for various SubSystems that will inherit from it – some of the inherited classes will need to use the UpdateGUI decorator.
class DO(SubSystem): def getport(self, port): """Returns the value of Digital Output port "port".""" pass @SubSystem.UpdateGUI def setport(self, port, value): """Sets the value of Digital Output port "port".""" pass
Once again I have omitted the function implementations as they are not relevant.
In short the problem is that while I can access the decorator defined in the base class from the inherited class by specifiying it as SubSystem.UpdateGUI, I ultimately get this TypeError when trying to use it:
unbound method UpdateGUI() must be called with SubSystem instance as first argument (got function instance instead)
This is because I have no immediately identifiable way of passing the
self parameter to the decorator!
Is there a way to do this? Or have I reached the limits of the current decorator implementation in Python?
You need to make
UpdateGUI a
@classmethod, and make your
wrapper aware of
self. A working example:
class X(object): @classmethod def foo(cls, fun): def wrapper(self, *args, **kwargs): self.write(*args, **kwargs) return fun(self, *args, **kwargs) return wrapper def write(self, *args, **kwargs): print(args, kwargs) class Y(X): @X.foo def bar(self, x): print("x:", x) Y().bar(3) # prints: # (3,) {} # x: 3
It might be easier to just pull the decorator out of the
SubSytem class:
(Note that I’m assuming that the
self that calls
setport is the same
self that you wish to use to call
updateGUIField.)
def UpdateGUI(fun): #function decorator def wrapper(self,*args): self.updateGUIField(*args) return fun(self,*args) return wrapper class SubSystem(object): print(name,value) class DO(SubSystem): @UpdateGUI def setport(self, port, value): """Sets the value of Digital Output port "port".""" pass do=DO() do.setport('p','v') # ('p', 'v')
You’ve sort of answered the question in asking it: what argument would you expect to get as
self if you call
SubSystem.UpdateGUI? There isn’t an obvious instance that should be passed to the decorator.
There are several things you could do to get around this. Maybe you already have a
subSystem that you’ve instantiated somewhere else? Then you could use its decorator:
subSystem = SubSystem() subSystem.UpdateGUI(...)
But maybe you didn’t need the instance in the first place, just the class
SubSystem? In that case, use the
classmethod decorator to tell Python that this function should receive its class as the first argument instead of an instance:
@classmethod def UpdateGUI(cls,...): ...
Finally, maybe you don’t need access to either the instance or the class! In that case, use
staticmethod:
@staticmethod def UpdateGUI(...): ...
Oh, by the way, Python convention is to reserve CamelCase names for classes and to use mixedCase or under_scored names for methods on that class.
You need to use an instance of
SubSystem to do your decorating or use a
classmethod as kenny suggests.
subsys = SubSystem() class DO(SubSystem): def getport(self, port): """Returns the value of Digital Output port "port".""" pass @subsys.UpdateGUI def setport(self, port, value): """Sets the value of Digital Output port "port".""" pass
You decide which to do by deciding if you want all subclass instances to share the same GUI interface or if you want to be able to let distinct ones have distinct interfaces.
If they all share the same GUI interface, use a class method and make everything that the decorator accesses a class instance.
If they can have distinct interfaces, you need to decide if you want to represent the distinctness with inheritance (in which case you would also use
classmethod and call the decorator on the subclasses of
SubSystem) or if it is better represented as distinct instances. In that case make one instance for each interface and call the decorator on that instance.
| https://techstalking.com/programming/python/python-decorators-that-are-part-of-a-base-class-cannot-be-used-to-decorate-member-functions-in-inherited-classes/ | CC-MAIN-2022-40 | en | refinedweb |
The things I’ve googled haven’t worked, so I’m turning to experts!
I have some text in a tab-delimited text file that has some sort of carriage return in it (when I open it in Notepad++ and use “show all characters”, I see [CR][LF] at the end of the line). I need to remove this carriage return (or whatever it is), but I can’t seem to figure it out. Here’s a snippet of the text file showing a line with the carriage return:
firstcolumn secondcolumn third fourth fifth sixth seventh moreoftheseventh 8th 9th 10th 11th 12th 13th
Here’s the code I’m trying to use to replace it, but it’s not finding the return:
with open(infile, "r") as f: for line in f: if "n" in line: line = line.replace("n", " ")
My script just doesn’t find the carriage return. Am I doing something wrong or making an incorrect assumption about this carriage return? I could just remove it manually in a text editor, but there are about 5000 records in the text file that may also contain this issue.
Further information:
The goal here is select two columns from the text file, so I split on t characters and refer to the values as parts of an array. It works on any line without the returns, but fails on the lines with the returns because, for example, there is no element 9 in those lines.
vals = line.split("t") print(vals[0] + " " + vals[9])
So, for the line of text above, this code fails because there is no index 9 in that particular array. For lines of text that don’t have the [CR][LF], it works as expected.
Solution #1:
Technically, there is an answer!
with open(filetoread, "rb") as inf: with open(filetowrite, "w") as fixed: for line in inf: fixed.write(line)
The b in
open(filetoread, "rb") apparently opens the file in such a way that I can access those line breaks and remove them. This answer actually came from Stack Overflow user Kenneth Reitz off the site.
Thanks everyone!
Solution #2:
Here’s how to remove carriage returns without using a temporary file:
with open(file_name, 'r') as file: content = file.read() with open(file_name, 'w', newline='n') as file: file.write(content)
Solution #3:
Depending on the type of file (and the OS it comes from, etc), your carriage return might be
'r',
'n', or
'r'n'. The best way to get rid of them regardless of which one they are is to use
line.rstrip().
with open(infile, "r") as f: for line in f: line = line.rstrip() # strip out all tailing whitespace
If you want to get rid of ONLY the carriage returns and not any extra whitespaces that might be at the end, you can supply the optional argument to
rstrip:
with open(infile, "r") as f: for line in f: line = line.rstrip('rn') # strip out all tailing whitespace
Hope this helps
Solution #4:
Python opens files in so-called
universal newline mode, so newlines are always
n.
Python is usually built with universal newlines support; supplying ‘U’
opens the file as a text file, but lines may be terminated by any of
the following: the Unix end-of-line convention ‘n’, the Macintosh
convention ‘r’, or the Windows convention ‘rn’. All of these
external representations are seen as ‘n’ by the Python program.
You iterate through file line-by-line. And you are replacing
n in the lines. But in fact there are no
n because lines are already separated by
n by iterator and each line contains no
n.
You can just read from file
f.read(). And then replace
n in it.
with open(infile, "r") as f: content = f.read() content = content.replace('n', ' ') #do something with content
Solution #5:
I’ve created a code to do it and it works:
end1='C:...file1.txt' end2='C:...file2.txt' with open(end1, "rb") as inf: with open(end2, "w") as fixed: for line in inf: line = line.replace("n", "") line = line.replace("r", "") fixed.write(line)
| https://techstalking.com/programming/question/solved-how-can-i-remove-carriage-return-from-a-text-file-with-python/ | CC-MAIN-2022-40 | en | refinedweb |
15,434,219 members
Forgot your password?
articles
Browse Topics
>
Latest Articles
Top Articles
Posting/Update Guidelines
Article Help Forum
Submit an article or tip
Import GitHub Project
Import your Blog
quick answers
Q&A
Ask a Question
View Unanswered Questions
View All Questions
View C# questions
View Python questions
View C++ questions
View Javascript questions
View Java questions
discussions
forums
CodeProject.AI Server
All Message Boards...
Application Lifecycle
>
Running a Business
Sales / Marketing
Collaboration / Beta Testing
Work Issues
Design and Architecture
Artificial Intelligence
ASP.NET
JavaScript
Internet of Things
C / C++ / MFC
>
ATL / WTL / STL
Managed C++/CLI
C#
Free Tools
Objective-C and Swift
Database
Hardware & Devices
>
System Admin
Hosting and Servers
Java
Linux Programming
.NET (Core and Framework)
Android
iOS
Mobile
WPF
Visual Basic
Web Development
Site Bugs / Suggestions
Spam and Abuse Watch
features
stuff
Competitions
News
The Insider Newsletter
The Daily Build Newsletter
Newsletter archive
Surveys
CodeProject Stuff
community
lounge
Who's Who
Most Valuable Professionals
The Lounge
The CodeProject Blog
Where I Am: Member Photos
The Insider News
The Weird & The Wonderful
?
What is 'CodeProject'?
General FAQ
Ask a Question
Bugs and Suggestions
Article Help Forum
Search within:
Articles
Quick Answers
Messages
Everything / .NET
Artificial Intelligence
Artificial Intelligence
Neural Networks
Machine Learning
Deep Learning
ML.Net
Big Data
Data Science
Tensorflow
Internet of Things
Internet of Things
Arduino
Edge Device
Raspberry-Pi
Wearables
IoT Edge
Industrial IoT
DevOps
DevOps
Agile
Automation
Continuous Build
Continuous Delivery
Continuous Deployment
Continuous Integration
Deployment
Git
Installation
Integration Testing
Load Testing
Quality Assurance
TFS
Unit Testing
Testing
Containers
Containers
Docker
Kubernetes
Virtual Machine
High Performance Computing
High Performance Computing
GPU
Parallel Processing
Parallelization
Vectorization
Hosted Services
Hosted Services
AWS
Cordova
ExtJS
Google Cloud
Microservices
PhoneGap
Serverless
Storage
Web Hosting
WordPress
Azure
Security
Security
Blockchain
Cryptography
Encryption
Identity
Identity Server
Web Development
Web Development
Blazor
CSS3
Flask
HTML5
Kestrel
LESS
Nginx
Node.js
React
SCSS
Spring
Vue.js
ASP.NET
CSS
Apache
HTML
IIS
XHTML
Mobile Apps
Mobile Apps
Flutter
Ionic
iOS
Nativescript
React Native
Xamarin
Windows Mobile
Android
Desktop Programming
Desktop Programming
Cocoa
Electron
QT
Universal Windows Platform
X11
Windows Forms
ATL
MFC
Swing
Win32
WTL
WPF
XAML
System
Database Development
Database Development
Data Visualization
Elasticsearch
Lucene
MariaDB
MongoDB
NoSQL
PostgreSQL
Redis
MySQL
SQL Server
Productivity Apps and Services
Productivity Apps and Services
LibreOffice
OpenOffice
Sharepoint
Team Communication Tools
Biztalk
Microsoft Office
SAP
Game Development
Game Development
Doom
Kinect
Playstation 4
Playstation 5
Unity
Unreal
XBox
Multimedia
Multimedia
Audio
Image Processing
Video
Audio Video
DirectX
GDI
GDI+
OpenGL
General Programming
General Programming
Algorithms
Compression
Computational Geometry
Emulation
Exceptions
File
Internet
Localization
Memory Management
Optimization
Parser
Performance
Regular Expressions
Sorting
State Machines
Architecture
Design / Graphics
Printing
String
Threads
Usability
Programming Languages
Programming Languages
ASM
Bash
Basic
COBOL
Dart
Go
Haskell
Kotlin
Lua
Pascal
R
Razor
Rust
Scala
Swift
Typescript
Objective C
Visual Basic
VBScript
C++
C#
F#
FORTRAN
Java
Javascript
Perl
Python
Ruby
SQL
PHP
PowerShell
XML
Submit your article
.NET
.NET
Great Reads
Comparator - Data Sources Comparer
by
Alex Pumpet
A simple program for comparing table data from two sources - SQL databases,
Excel,
CSV or XML-files.
CPS1.
NET: A C# Based CPS1 (MAME) Emulator
by
shunninghuang
CPS1 emulator,
ROM hacking
Latest Articles
CodeProject.
AI Server: AI the easy way.
by
CodeProject
Version 1.
6.
0.
0.
Our fast,
free,
self-hosted Artificial Intelligence Server for any platform,
any language
Go Ahead And Cheat! You Know You Want To!
by
David O'Neil
Create drastic life improvements by completing your Wordle puzzle in minutes instead of days!
ftp2? Evolving File Transfer with msgfiles
by
Michael Sydney Balloni
A .
NET client-server application for sending files over a network.
All Articles
Article
Project
Technical Blog
Tip/Trick
Video
Reference
Asset
top
Sort by Score
Title
Updated
Author
Score
.NET
Comparator - Data Sources Comparer
20 Mar 2018 by
Alex Pumpet
A simple program for comparing table data from two sources - SQL databases, Excel, CSV or XML-files
Cryptographic Interoperability: Keys
5 Jun 2008 by
Jeffrey Walton
Import and export Cryptographic Keys in PKCS#8 and X.509 formats, using Crypto++, C#, and Java.
CPS1.NET: A C# Based CPS1 (MAME) Emulator
3 Apr 2021 by
shunninghuang
CPS1 emulator, ROM hacking
Understanding the Insides of the SMTP Mail Protocol: Part 1
9 Dec 2012 by
Higty
This article describes the mail sending process using the SMTP mail protocol.
.NET File Format - Signatures Under the Hood, Part 1 of 2
29 Sep 2009 by
Przemyslaw Celej
A full description of signatures, that are part of the .NET file format
Sequence Classifiers in C# - Part II: Hidden Conditional Random Fields
9 Dec 2014 by
César de Souza
The Hidden Conditional Random Field - or why discriminative learning is also an option
Fluid Geometry - An Animation Library and Configuration Application
9 May 2012 by
Josh Smith
A task-oriented review of an animation library and the application which uses it
Automatic Linguistic Indexing of Pictures (ALIP) By Artificial Neural Network Approach
10 Sep 2009 by
Chesnokov Yuriy
General idea of how the computer may be used to describe the image analyzing its pixel content known as ALIP
Calcium: A Modular Application Toolset Leveraging PRISM – Part 2
23 Nov 2009 by
Daniel Vaughan
Calcium provides much of what one needs to rapidly build a multifaceted and sophisticated modular application. Includes a host of modules and services, and an infrastructure that is ready to use in your next application.
Integration: Mechanics + Hydraulics + Navigation
3 Feb 2011 by
Petr Ivankov
Sample of integration of branches of engineering.
WPF 3D FlipPanel
13 Mar 2012 by
Fredrik Bornander
WPF Implementation of the spinning panel frequently used on the iPhone
24 Jul 2014 by
David Rogers Dev
Learn how to load related entities using the Entity Framework with simple examples
Simple Method of DLL Export without C++/CLI
27 Jun 2009 by
Dark Daskin
Article describes how to build an assembly that exposes functions to unmanaged code without C++/CLI
TCP Socket Off-the-shelf
22 Jan 2014 by
Igor Ladnik
Wrapper to facilitate usage of TCP sockets
WPF: If Carlsberg did MVVM Frameworks: Part 6 of n
4 Sep 2009 by
Sacha Barber
It would probably be like Cinch, an MVVM framework for WPF.
Human-readable Enumeration Meta-data
8 Mar 2017 by
Sergey Alexandrovich Kryukov
Display names and descriptions for enumeration members: a non-intrusive, reliable, localizeable method.
XamlVerifier - Check or Auto Correct Binding Path at Compile and Design Time
9 Jan 2012 by
Nicolas Dorier
Stop wasting time on a stupid typo in binding paths
Understanding Merkle Trees - Why Use Them, Who Uses Them, and How to Use Them
13 Mar 2017 by
Marc Clifton
An interactive demo of how audit and consistency proofs work
Find and Replace Text in a Word Document
14 Jun 2016 by
Mario Z
Pure .NET solution for performing find and replace text on Word documents (DOCX file format)
Using a TypeDescriptionProvider to support dynamic run-time properties
16 Jun 2008 by
Nish Nishant
This articles explains how to implement a TypeDescriptionProvider for a class to support multiple object types using a single class type
Phalanger, PHP for .NET: Introduction for .NET developers
24 Jan 2007 by
Tomas Petricek
Phalanger is a PHP language compiler for the .NET Framework which introduces PHP as a first-class .NET citizen.
DirectShow Virtual Video Capture Source Filter in C#
13 Oct 2012 by
Maxim Kartavenkov
Articles describes how to create virtual video capture source directshow filter in pure C#
Routing Manager for WCF4
29 Apr 2010 by
Roman Kiss
This article describes a design, implementation and usage of the Custom Routing Manager for managing messages via Routing Service built-in .Net 4 Technology.
Entity Framework: Storing Complex Properties as JSON Text in Database
18 Jan 2017 by
Jovan Popovic(MSFT)
Mapping properties in EF model to database columns that contain JSON
SignalR Chat App With ASP.NET WebForm And BootStrap - Part Three
18 Sep 2018 by
Altaf Ansari
SignalR Real-Time ChatApp with Emoji / Smiley and sending file attachment
IFS - an Internet File System implementation based on Web services and peer-to-peer technology
28 Sep 2002 by
Stoyan Damov
Internet File System from scratch - making web services and peer-to-peer technology work together to build a virtual file system
AJAX-enabled Name Selector User Control
24 Aug 2009 by
Steve Krile
Fully AJAX-enabled user control used to select names from a database in a drop-down format.
Advanced Excels With EPPlus
23 May 2018 by
yuvalsol
Create professional-looking Excels (Filters, Charts, Pivot Tables) with EPPlus
A Complete Anti Theft Homemade Surveillance System
10 Mar 2017 by
Miguel Diaz Kusztrich
Be notified in your mobile phone of intruders in your home, and take photos of them
Document Processing Part II: Request Driven OCR
30 Apr 2005 by
Martin Welker
To get qualified access to paper based information, sometimes more than plain OCR is needed. This article shows why, and offers a solution to increase OCR quality by semi-automatic table extraction.
A Project Dependency Graph Utility for Visual Studio 2008
17 Jun 2009 by
Marc Clifton
Review your project dependencies.
How To: Use Office 2007 OCR Using C#
24 Aug 2009 by
Waleed Elkot
Reading text from any image using Microsoft Office 2007 OCR
Demystify http.sys with HttpSysManager
23 Aug 2012 by
Nicolas Dorier
Configure the HTTP traffic on your local machine. A nice alternative for netsh http.
Always run Visual Studio as Administrator with no UAC prompt
30 Jul 2015 by
Tom Chantler
UPDATE: 2015-07-30 - Works correctly in Windows 10 RTM (10.0.10240) with VS2013 and VS2015 - If you're running Windows 7, 8, 8.1 or 10 and you don't want to disable User Account Control (UAC) - which you shouldn't and quite possibly can't in a corporate environment - then you get an annoying prompt
Dependency Injection using Unity: Resolve Dependency of Dependencies
13 Mar 2018 by
Akhil Mittal
A tutorial to learn dependency injection with the help of a simple example
Bring Your Animations to H264/HEVC Video
7 Mar 2022 by
Shao Voon Wong
Bring your animations to H264/HEVC video using C++ and C# with h/w acceleration
SignalR Chat App with ASP.NET WebForm And BootStrap - Part One
20 Dec 2017 by
Altaf Ansari
Integration of SignalR with ASP.NET C# WebForm Application in Real-Time Chat Application
Conceptual Children: A powerful new concept in WPF
6 Apr 2008 by
Dr. WPF
This article describes a new approach by which an element can remove its visual and logical relationships to its children while maintaining a conceptual parental relationship with those children.
Object Tracking: Particle Filter with Ease
27 Apr 2015 by
Darko Jurić
SIR Particle Filter brief tutorial with samples in C#
C#.NET Implementation of K-Means Clustering Algorithm to Produce Recommendations
25 Dec 2016 by
Arthur V. Ratz
In this article we'll demonstrate the implementation of k-means clustering algorithm to produce recommendations.
Using Python Scripts from a C# Client (Including Plots and Images)
26 Aug 2019 by
Thomas Weller
Demonstrates how to run Python scripts from C#
Attaching a Virtual Branch to the Logical Tree in WPF
6 May 2007 by
Josh Smith
Reviews a pattern which enables new possibilities for data binding.
An extensible ExifReader class with customizable tag handlers
29 Mar 2010 by
Nish Nishant
An ExifReader class in C# that supports custom formatting and extraction. StyleCop compliant code, with demos for WPF and Windows Forms.
Many Questions Answered At Once: Interactive Animated Graphics with Forms
22 Mar 2017 by
Sergey Alexandrovich Kryukov
Addresses questions on graphics, threading with UI, form development, printing and more
X86/ARM Emulator
1 May 2014 by
codestarman
X86/ARM emulator written using C++ and assembler for the .NET environment.
Create and Send An Email Reply in C# / VB.NET
15 Jun 2016 by
JosipK, Marko Kozlina
C# and VB.NET console applications that demonstrate how to create and send an email reply with IMAP and SMTP protocols in .NET Framework
WPF Geometries, the Processing Way
15 Aug 2013 by
Nicolas Dorier
Create drawings easily with the Drawing/Drawer space paradigm
Flexible WPF ToggleSwitch Lookless Control in C# & VB
15 Nov 2017 by
Graeme_Grant
A Modern Toggle Switch - From mock concept to a full custom WPF control that you can plug into your own apps
Silverlight DataTrigger is the Answer to View Model / MVVM Issues
6 Nov 2010 by
defwebserver
How using the Silverlight DataTrigger allows you to run a process and then raise another when using View Model (MVVM)
A Look into the Future - Source Code Generation by the Bots
14 Dec 2018 by
Dmitriy Gakh
The perspectives of creating bots that write programs with two simple examples.
Data Debugger Visualizer
30 May 2005 by
dotnetdan
VS 2005 debug visualizers for DataSet, DataTable, DataView, DataRow and DataColumn objects.
.NET File Format - Signatures under the Hood, Part 2 of 2
28 Sep 2009 by
Przemyslaw Celej
Full description of signatures, that are part of .NET file format
Build a Desktop GIS Application Using MapWinGIS and C# - Part 4
20 May 2010 by
Wisam E. Mohammed
The hidden secerts of GIS data creation.
Reflection Studio - Part 2 - User Interface: Themes, Dialogs, Controls, External Libraries
22 Sep 2010 by
Guillaume Waser
Reflection Studio is a "developer" application for assembly, database, performance, and code generation, written in C# under WPF 4.0.
Azure Animal Adoption Agent and Lost & Found
7 Oct 2020 by
roscler
Azure based pet adoption agent that helps pet lovers find the perfect pet while saving the lives of kittens & puppies
Using Roslyn for Compiling Code into Separate Net Modules and Assembling them into a Dynamic Library
16 Jun 2021 by
Nick Polyak
Dynamically compile and assemble code snippets into a dynamic assembly
Music Notation in .NET
15 Jul 2018 by
Ajcek84
Open source library for music engraving in desktop, mobile and web applications
Create An Awesome WPF UI for Your C++/QT Applications
6 Jan 2020 by
The Ænema
This article will teach you how to create an amazing, clean and smooth WPF/Winform UI for your native application without using any complex, unsafe, ActiveXish methods, etc.
Multiplatform Avalonia .NET Framework Programming Basic Concepts in Easy Samples
14 Sep 2021 by
Nick Polyak
This article explains the most important and basic concepts of Avalonia WPF-like multiplatform UI package..
.NET Shell Extensions - Shell Icon Overlay Handlers
14 Sep 2013 by
Dave Kerr
Create Shell Icon Overlay Handlers using .NET!
Deep Dive into OWIN Katana
17 Sep 2020 by
kusnaditjung
Web specification and framework
Binding RadioButtons to an Enum in Silverlight
5 Sep 2011 by
Todd Davis
How to bind an enum to radiobuttons in Silverlight/WPF
PowerJSON - A Powerful and Fast JSON Serializer
2 Feb 2018 by
wmjordan
This is a fork of "fastJSON" with new power to control many aspects in JSON serialization and deserialization, such as, serializing interface instances (polymorphic serialization) and private types, including or excluding members, performing data conversions, conditional serialization, etc.
Understanding the SynchronizationContext in .NET with C#
28 Jul 2020 by
honey the codewitch
Take control of which thread your code gets executed on, and how it does
Self-Hosting Multiple HTTPS Websites in IIS with SNI and LetsEncrypt Certificates
4 Jul 2017 by
Marc Clifton
Ability to self-host multiple HTTPS websites without having to pay for hosting and certificates
BuilderHMI.Lite - Simple Drag-and-Drop WPF Layout
18 Nov 2020 by
Bruce Greene
.NET Core WPF design as quick and intuitive as WinForms! Hear that MICROSOFT?
Outlook style GUI - three-way split form
3 Jul 2002 by
Nish Nishant
Demonstrates the usage of splitters, treeviews, listviews, panels, toolbars
The ALXGrid Control Library.
10 Nov 2002 by
Alexey
The ALXGrid Control Library is a set of classes for management of data as a table.
ImmDoc .NET - a tool for generating HTML documentation
27 Jun 2007 by
Marek Stoj
ImmDoc .NET is a command-line utility for generating HTML documentation from a set of .NET assemblies and XML files created by the compiler.
Introducing Calcium for Xamarin.Forms
15 Sep 2014 by
Daniel Vaughan
Create best-in-breed cross-platform MVVM apps using Calcium for Xamarin.Forms.
HandlEdInput - Powerful and Highly Customizable Input Handler for TextBox, RichTextBox and ComboBox
17 Jul 2019 by
Edwyn Amador
Handles and validates input typing and pressed keys in TextBox, RichTextBox and ComboBox, displaying custom balloon tips messages
fastCSV - A Tiny, Fast, Standard Compliant CSV Reader Writer
6 Dec 2020 by
Mehdi Gholam
With the increased prominence of machine learning and ingesting large datasets with the CSV format for this purpose, I decided to write a CSV parser which met my requirements of being small, fast and easy to use.
A Custom WPF Carousel Control
21 Nov 2019 by
Leif Simon Goodwin
This article presents a simple WPF Carousel Control
Using C Calling Convention Callback Functions in C# and VB - The Easy Way
13 Sep 2005 by
Jecho Jekov
Provides an easy way to use C calling convention callback functions in C# and VB
Manageable Services
30 Apr 2009 by
Roman Kiss
This article describes a design, implementation and tooling of model driven WorkflowServices logically centralized in the Repository and physically decentralized for their runtime projecting.
Genuilder
10 Nov 2009 by
Nicolas Dorier
Enhance Visual Studio and your build process in just two clicks. This tool does its best to be out of your way, while improving your development experience seemlessly.
Build a Desktop GIS Application Using MapWinGIS and C# - Part 3
22 Nov 2009 by
Wisam E. Mohammed
Raster data display and manipulation using MapWinGIS.
Exploring Clip Property of UIelement to Make Animation in WPF
30 Dec 2009 by
Razan Paul (Raju)
Animation technique based on Clip property of UIelement in WPF
Introducing PdfRport
14 Feb 2013 by
Vahid_N
PdfReport is a code-first reporting engine which is built on top of the iTextSharp and EPPlus libraries.
Computer Algebra System for .NET Framework
21 Jun 2013 by
Igor S Medvedev
The article describes a C# library for symbolic computations.
Generating RDLC Dynamically for the Report Viewer Local Report
2 Jan 2014 by
tetsushmz
This article explains how to dynamically create RDLC.
Lightning-Fast Nested User Groups in C#
5 Dec 2015 by
Daniel Miller
This article describes the C# implementation for a high-performance user/role security principal hierarchy.
.NET Core nginx, and Postgres with EF on an rPi
11 Jan 2019 by
Marc Clifton
Implementing an SSL capable server in .NET Core WITHOUT ASP.NET, using nginx, and testing Postgres with EF, all running on an rPi
Virtualizing WrapPanel
25 May 2010 by
Thiago de Arruda
A Virtualizing WrapPanel for WPF.
InternetToolTip
2 Dec 2011 by
Florian Rappl
A better ToolTip for Windows Forms and more.
Mario5 with TypeScript
18 Dec 2014 by
Florian Rappl
Exploring the abilities, benefits and features of TypeScript by extending / rewriting the original Mario5 source.
Driver Loader [DLoad] from Scratch
2 Nov 2009 by
csrss
A tool for loading device drivers
Aspect Oriented Programming using Interceptors within Castle Windsor and ABP Framework
21 Feb 2018 by
Halil ibrahim Kalkan
In this article, I'll show you how to create interceptors to implement AOP techniques. I'll use ASP.NET Boilerplate (ABP) as base application framework and Castle Windsor for the interception library.
Elasticsearch, Kibana and Docker using .NET Standard 2
29 Dec 2018 by
Juan G. Carmona
Advanced logging in modern .NET applications. A Sunday-morning-proof-of-concept.
Vash - A GDI+ Flash-Like Vector Animation Program
27 Apr 2016 by
Clayton Rumley
There are those who think I am crazy, and this just might be the proof.
Using Create-React-App and .NET Core 3.0 to Build a React Client (Global Weather) - Part 1
5 Feb 2020 by
Fred Song (Melbourne)
Global Weather - React App with ASP.NET Core 3.0.
An Introduction to the Silverlight samples in the All-In-One Framework
12 Dec 2009 by
All-In-One Code Framework
This article introduces several Silverlight samples in the All-In-One Framework.
C# WebServer Using Sockets
23 Jan 2014 by
Alberto Biafelli
How to make a simple web server which supports GZIP compression, applications, and sessions.
Threads, Processes, Memory Allocation, and Workstation Mode vs. Server Mode
15 Mar 2015 by
Marc Clifton
What you may not realize about memory allocation and threads, and a little known thing called "Server Mode"
Passing Strings Between Managed and Unmanaged Code
7 Jul 2017 by
Leif Simon Goodwin
How to pass strings between managed and unmanaged code
Reactive Programming for .NET and C# Developers - An Introduction To IEnumerable, IQueryable, IObservable, and IQbservable
1 Sep 2013 by
Anoop Pillai
Exploring Reactive Programming including a detailed look at Interactive and Reactive Extensions for .NET and C# developers.
Notification of Silverlight Applications about Database State Changes
27 Nov 2009 by
Max Paulousky
This article presents the techniques and caveats of building Silverlight applications that can be notified about database state changes via polling duplex. WSHttp binding and CLR triggers are used to implement the solution as well.
Windows-Service for Multithreading with Remote Control GUI
25 Feb 2016 by
J.Starkl
A windows-service which can handle different operations in separate threads and which can be controlled by a small GUI program
Real-Time Gauge with ChartJS and Spike-Engine
23 Jun 2015 by
Kel_
Presents a real-time gauge implementation that can be used for building dashboards
Understanding and Implementing Factory Pattern in C#
9 Feb 2015 by
Rahul Rajat Singh
In this article, we will try to understand what is Factory Pattern, what are the benefits of this pattern and how we can implement this pattern using C#.
CudaPAD
11 Jul 2020 by
Ryan S White
CudaPAD is a PTX/SASS viewer for NVIDIA Cuda kernels and provides an on-the-fly view of your Cuda code.
Introduction to Dependency Injection and Inversion of Control
26 Feb 2016 by
DotNetSteve
A gentle introduction for DI and IOC in the first program most of us have written - Hello World
Hashcash or "Proof of Work"
24 Feb 2017 by
Marc Clifton
Hashcash is a proof-of-work system used to limit email spam and denial-of-service attacks, and more recently has become known for its use in bitcoin (and other cryptocurrencies) as part of the mining algorithm.
Slack Chatting with your rPi
27 Jan 2019 by
Marc Clifton
Talk to your rPi over a Slack channel, getting status, controlling devices, and running shell (bash) commands and viewing the console output posted back to your Slack channel
ANNT : Convolutional neural networks
28 Oct 2018 by
Andrew Kirillov
The article demonstrates usage of ANNT library for creating convolutional ANNs and applying them to image classification tasks.
C++/CLI HowTo : Deriving from a C# disposable class
5 Jul 2008 by
Nish Nishant
This article walks through the implementation of a C++/CLI class from a disposable C# base.
WinForms WebBrowser + HTTP Server
18 Apr 2010 by
Nicholas Butler
A tiny HTTP server wrapped in a WebBrowser control
Creating PDF Documents from XML
16 Aug 2013 by
Marco Merola
Creating PDF documents from XML
WinRT: StyleMVVM Demo 1 of 2
4 Nov 2013 by
Sacha Barber
A look at an excellent WinRT MVVM framework.
WinRT: StyleMVVM Demo 2 of 2
5 Nov 2013 by
Sacha Barber
StyleMVVM Demo App
Decorator Pattern Usage on a Simplified Pacman Game
9 Dec 2013 by
Petar Brkusanin
An example of how Decorator, Dependency Injection, and Composition Root patterns can be used to extend the base game functionality.
WPF Custom Visualization Part 2 of some: Triggers
24 Aug 2016 by
Serge Desmedt
(Yet Another) Investigation of WPF triggers
Introduction to FORTRAN Interoperability with .NET
16 May 2016 by
Christ Akkermans
An introduction to the strange world of mixed language programming with FORTRAN and C# .NET code
Understanding and creating a .NET like List
11 Jul 2016 by
Paulo Zemek
Solution Build Timer for VS 2005/2013/2015/2017/2019
10 Jun 2019 by
Brett Rowbotham
Add-in for VS2005, VS2013/2015 and VS2017/2019 that provides the time taken to build a complete solution
A Case Study of Taking a Simple Algorithm from Prototype to "Production" Quality Code
5 Apr 2017 by
Marc Clifton
A somewhat lightweight article, that covers some issues that we should all be conscious of when reworking prototype code (and deciding whether to rework prototype code!) with a case study.
DX Game Utility Class Library
9 Nov 2003 by
Dan Peverill
A managed DirectX class library that can be used as a foundation for basic 2D games. Demo included.
2D "Nim" Game Development and Animation in C# (Part 2)
16 Aug 2007 by
Volynsky Alex
Part 2 in a series of articles on a two-player mathematical game of strategy
Introduction to Model Driven Development with Sculpture – Part 1
3 Sep 2008 by
Ahmed Negm
This article introduces how to create and manage .NET enterprise applications using your favorite technology (Data Access Application Block, LINQ, NHibernate, ASMX, and WCF) with the Model Driven Development approach by Sculpture.
Export Silverlight DataGrid to Excel XML/CSV
1 Dec 2009 by
raelango
This article explains how to export the contents of a DataGrid to Excel/CSV.
Processing4Net
4 Jun 2012 by
Espen Harlinn
Release the random artist inside you
Smart WPF Login Overlay (Windows 8 Style)
3 Dec 2012 by
DotNetMastermind
Login Overlay for WPF applications with a styling similar to the Windows 8 Login Screen.
Office 2013 Style Splash Screen
5 Aug 2014 by
Magyar András
How to create Office 2013 style splash screen for Windows Forms
Sketcher : Two Of n
14 Aug 2014 by
Sacha Barber
Angular.Js / Azure / ASP MVC / SignalR / Bootstrap demo app
Building a Simple .NET Compiler
26 Jan 2018 by
Jason R. Fruit
Implement a compiling calculator to learn about .NET CIL compilation
Proper List Support in C#
17 Nov 2019 by
honey the codewitch
Implementing full list support over custom data structures in .NET
Flyout - A great way to save space on your webpage
4 Dec 2007 by
Ned Thompson
This article will demo how a free Flyout can help to save space on your webpage.
Protecting .NET 4.+ Application By C++ [Unmanaged]
25 Mar 2018 by
The Ænema
Inject your 4.5 framework .NET application into a C++ unmanaged host application - fast, secure & without any extra tool or library.
CodeProject.AI Server: AI the easy way.
U
22 Sep 2022 by
CodeProject
Version 1.6.0.0. Our fast, free, self-hosted Artificial Intelligence Server for any platform, any language
API-Less INI File Wrapper
5 Nov 2008 by
Tolgahan ALBAYRAK
Read, Write, Save INI files without using Windows APIs.
DirectShow: Examples for Using SampleGrabber for Grabbing a Frame and Building a VU Meter
8 May 2009 by
almere109
DirectX.Capture class examples showing how to grab a frame from video and how to make a VU meter for audio
Binding a ListView to a Data Matrix
15 May 2009 by
Tawani Anyangwe
Binding a WPF ListView to a DataMatrix with columns determined at runtime
Calcoolation: A Math Puzzle Board Game
6 Aug 2009 by
Marcelo Ricardo de Oliveira
Demo for a math puzzle board game
Windows Ribbon for WinForms, Part 0 – Table of Contents
31 Jan 2010 by
Arik Poznanski
Complete Library for using the Windows 7 Ribbon from C#, including 18 samples and 21 blog posts documenting the Ribbon features
WPF: Where to Put Value Converters?
31 Jan 2010 by
Arik Poznanski
The question this posts tries to address is: Where to put value converters?
Windows Phone Crosswords
3 Jul 2012 by
Marcelo Ricardo de Oliveira
Learn how to create a Windows Phone crosswords game taking advantage of online internet resources
SQLoogle - Part 1 of 2
16 May 2013 by
dale.newman
Google your SQL.
Sketcher : Three Of n
14 Aug 2014 by
Sacha Barber
Angular.Js / Azure / ASP MVC / SignalR / Bootstrap demo app
Exploring Computational Number Theory (Part 1)
31 May 2016 by
William Hey
Classical number theories
Build My Own 3D Graphics Engine Step By Step
1 Feb 2017 by
Mr. xieguigang 谢桂纲
How to build my own 3D graphics engine from ZERO step by step
Interoping .NET and C++ through COM
11 Jul 2017 by
Marius Bancila
Create COM visible types in C# and consume them from C++
How to Build a Regex Engine in C#
21 Nov 2019 by
honey the codewitch
Build a feature rich, non-backtracking regular expression engine and code generator in C#
Using DescriptionAttribute for enumerations bound to a WPF ComboBox
27 Jan 2016 by
Clifford Nelson
How to use DescriptionAttribute for enumerations bound to a ComboBox.
Delaunay Triangulation For Fast Mesh Generation
12 Nov 2012 by
HoshiKata
Practical on the fly fast mesh generation from arbitrary points.
.NET Wrapper of FFmpeg Libraries
15 Jul 2022 by
Maxim Kartavenkov
Article describes created .NET wrapper library
Find File in Solution
28 Mar 2010 by
Alex Blekhman
Find any file in solution using incremental search and advanced filtering
Injecting Method Calls to Existing Methods of an Assembly
24 Apr 2012 by
Ana Carolina Zambon
This is a demonstration of how to use the basics of Mono.Cecil by adding method calls to existing assemblies.
TCP Socket Off-the-shelf - Revisited with Async-Await and .NET Core
8 May 2018 by
Igor Ladnik
Handy component for asynchronous TCP connection. With the same code it is available in .NET Core and Desktop versions.
Inference in Belief Networks
6 Dec 2002 by
hzhou
A C# implementation of bucket elimination algorithm for inference in belief networks.
SMTP Client Supporting Implicit SSL Secure Sockets Layer with OAuth2 Open Authorization or Password Authorization (2.0)
20 Jun 2019 by
Uzi Granot
The attached open source C# .NET library is an SMTP client implementing implicit SSL and OAuth2 protocols. The library answers the question: how to send email message using Gmail as a server. Or, how to send email message using email server that implements implicit SSL and port 465.
UniDock - New Multiplatform Docking Framework (Introduction)
29 Aug 2021 by
Nick Polyak
This article describes a new multiplatform Docking framework - UniDock
WebService Probe
19 Oct 2002 by
Roman Kiss
Using the WebService Probe to publish details of the "talking" between the web service and its consumer. Here is its design, implementation and usage in the WebService Analyzer Studio.
Using a NetworkStream with raw serialization, GZipStream, and CryptoStream
26 Mar 2006 by
Marc Clifton
Using a NetworkStream with raw serialization, GZipStream, and CryptoStream.
Implement an Autoplay Handler
18 Sep 2006 by
Tim Almdal
Implementing an Autoplay handler in C#.
Windows Authentication Using Form Authentication
1 Jul 2009 by
Muhammad Akhtar Shiekh
An article on "How to authenticate windows user using form authentication in ASP.NET?"
PSAM WPF Control Library
19 Jul 2018 by
Ajcek84
PSAM Control Library ported over to WPF
Chain Of Responsibility Design Pattern in C#, using Managed Extensibility Framework (MEF)
13 Nov 2011 by
Anoop Pillai
This post is about implementing Chain Of Responsibility design pattern, and few possible extensions to the same using Managed Extensibility Framework or MEF
RSA Library with Private Key Encryption in C#
15 Jul 2012 by
Arpan Jati
RSA encryption library with full OAEP padding and private key encryption support
A GAC Manager Utility and API
30 Jul 2012 by
Dave Kerr
Manage the Global Assembly Cache with this handy tool - or roll your own with the provided API!
WPF Layout to Layout Transitions
27 Nov 2012 by
Yuriy Zanichkovskyy
Layout to layout transitions made easy
Zip Rendering Extension for SQL Server Reporting Services 2005/2008/2012
14 Aug 2013 by
Harmen Brouwer
How to create and deploy a SSRS rendering extension, explained by a functional Zip Rendering extension for SSRS 2005, 2008 (R2) and 2012.
Understanding SelectedValue, SelectedValuePath, SelectedItem & DisplayMemberPath + Demo
21 Oct 2013 by
_Noctis_
Sorting out the confusion about these properties, and providing a demo app for them
Improve SPA Web Page Performance
6 Mar 2016 by
DataBytzAI
Get on top of memory leaks and improve user experience when using JQuery/KnockoutJS in a SPA or SPA based Hybrid Mobile Application
Implementing K-Means Image Segmentation Algorithm
29 Aug 2017 by
Arthur V. Ratz
This article demonstrates the development of code in C# implementing famous k-means clustering algorithm to perform graphical raster image segmentation.
Build Simple AI .NET Library - Part 1 - Basics First
9 Sep 2017 by
Gamil Yassin
Part 1 of a series of articles demonstrating .NET AI library from scratch
ASP.NET Core Web API: Plugin Controllers and Services
3 Jan 2022 by
Marc Clifton
The middle ground between monolithic applications and an explosion of microservices
Hadoop For .Net & AngularJS Developers
29 Dec 2015 by
Bert O Neill
Query Hadoop using Microsoft oriented technologies (C#, SSIS, SQL Server, Excel etc.)
How to Test a Class Which Uses DispatcherTimer
14 Jul 2007 by
Josh Smith
Demonstrates how to create unit tests for a class which uses a DispatcherTimer.
GPS Receivers, Geodesy, and Geocaching: Vincenty’s Formula
9 Jan 2008 by
Mike Gavaghan
Vincenty's Formula is an iterative solution for calculating the distance and direction between two points along the surface of Earth.
Grid Computing Using C# Script and .NET Remoting
10 Apr 2010 by
Ali Aboutalebi
Using the C# script engine inside a network using .NET Remoting.
Flexpressions
10 Oct 2012 by
Andrew Rissing
An intuitive-fluent API for generating Linq Expressions.
Smart Watcher
5 Sep 2013 by
Tammam Koujan
Easy to use directory watching tool.
Interoping .NET and C++ through Registration-free COM
2 Aug 2017 by
Marius Bancila
Using managed COM objects in C++ without registering the server in Windows Registry
Introducing Lightweight WebSocket RPC Library for .NET
14 Jan 2018 by
Darko Jurić
WebSocket RPC library for .NET with auto JavaScript client code generation, supporting ASP.NET Core.
CropBox
21 Aug 2019 by
Johnny J.
Easily add image cropping to your desktop application
Configuring Simple State Machines
6 May 2020 by
George Swan
An attempt to throw some light on how state machines work and what they can be used for
Group Sudoku in AngularJs and SignalR
14 Apr 2021 by
Anurag Gandhi
A group Sudoku game to demonstrate the usage of SignalR in AngularJs application
How to Upload a Document in ASP.NET Core
20 Jan 2020 by
Marc Clifton
The Secret Sauce
ASP.NET Core: Implement a Load Balancer
8 Sep 2017 by
Daniele Fontani
.NET Core showcase: learn basics implementing a toy tool
C# Scripts using DynamicMethod
10 May 2011 by
D. Christian Ohle
C# scripts using DynamicMethod
AngularJS Falling Blocks
27 May 2020 by
Theo Kand
An original AngularJS implementation of the most famous video game ever
C# Lectures - Lecture 10: LINQ introduction, LINQ to 0bjects Part 1
19 Jul 2016 by
Sergey Kizyan
10th article from my series. We will talk about LINQ in general and LINQ to objects deferred operators
PDF417 Barcode Encoder Class Library and Demo App Ver. 2.2
8 Sep 2020 by
Uzi Granot.
How to Make an LL(1) Parser: Lesson 1
14 Nov 2019 by
honey the codewitch
Creating a simple parser in 3 easy lessons
A Simple XML Validator, using VOLE
16 Apr 2007 by
Matt (D) Wilson
A simple command-line utility that validates XML files, implemented using MSXML via the VOLE COM/Automation driver library
Getting Started with Automated White Box Testing (and Pex)
28 Jan 2009 by
Jonathan de Halleux, Nikolai Tillmann
Pex is a new tool that helps in understanding the behavior of .NET code, debugging issues, and in creating a test suite that covers all corner cases -- fully automatically.
Develop a Mono application for the XO laptop
21 Apr 2009 by
Lionel LASKE
Learn how to develop an application for the XO laptop - the OLPC project's machine - using Mono on Sugar OS.
Extending ASP.NET Controls: A Scrollable GridView
7 Sep 2020 by
Herre Kuijpers
Extending the standard ASP.NET GridView control to add a vertical scrollbar in the grid
Using WebSocket in .NET 4.5 (Part 2)
15 Jul 2013 by
Zhuyun Dai
Using WebSocket in traditional ASP.NET and MVC 4
HackerSpray - Block Brute Force and DOS Attacks
18 Jul 2016 by
Omar Al Zabir
A .NET library to defend websites and web APIs against brute force and Denial-of-Service attacks
A Real MVVMLight Example
1 Mar 2017 by
Clifford Nelson
This is a more comprehensive example of how to implement a project with MVVMLight
A Tool for Visualizing 3D Geometry Models (Part 1)
11 Oct 2009 by
Wu Xuesong
An article describing a tool developed using WPF for visualizing 3D geometry models
Multiplatform Avalonia .NET Framework Programming Advanced Concepts in Easy Samples
17 Nov 2021 by
Nick Polyak
This article covers important concepts of Avalonia/WPF needed for programming and software design
Using the Web Service Callbacks in the .NET Application
2 Nov 2001 by
Roman Kiss
This article describes a .NET Application model driven by the Web Services using the Virtual Web Service Proxy (written in C#)
Share the Clipboard Using .NET Remoting
14 Oct 2002 by
Douglas Earl
Use .NET remoting to send the contents of your clipboard to another computer method.
Numbered Bookmarks - Visual Studio Extension VSX 2010
1 Mar 2010 by
The Manoj Kumar
A Visual Studio 2010 extension for creating numbered bookmarks.
Silverlight 4 Drag and Drop File Manager
6 May 2010 by
defwebserver
A Silverlight file manager that allows drag and drop multiple file uploads
Shaped WPF Form
24 Jun 2010 by
Amit Kumar Tiwari
Shaping WPF Form using an Image
Send and receive messages in a LAN with broadcasting
6 Mar 2012 by
Orekaria
Lightweight .Net library for UDP LAN broadcasting.
Dynamic Table Mapping for LINQ-to-SQL
21 May 2012 by
Zimin Max Yang
Dynamic table mapping for LINQ-to-SQL, suitable for data horizontal partitioning (Shard).
Making a Borderless Form Movable
29 Mar 2012 by
Rahul Rajat Singh
This is an alternative for "Making a Borderless Form Movable in C++"
AvalonDock [2.0] Tutorial Part 2 - Adding a Start Page
31 Jan 2014 by
Dirk Bahle
How to create a start page based on AvalonDock [2.0].
Creating a CodeDOM: Modeling the Semantics of Code (Part 2)
9 Nov 2012 by
KenBeckett
Creating a CodeDOM for C#
Property Finder – a Cross-Platform Xamarin MonoTouch Mobile App
3 Jan 2013 by
Colin Eberhardt
A look at how Xamarin MonoTouch allows you to create cross-platform applications, using the native C# / Silverlight for Windows Phone and C#, via Xamarin MonoTouch, for iOS.
PaydayUSA™ Employment Tax Calculator and Payroll Organizer
17 Feb 2015 by
DrABELL
Employment Tax computation and Payroll management app for Windows 8: contest entry
ViewModel 1st Child Container PRISM Navigation
20 Aug 2013 by
Sacha Barber
Shows how to use PRISM navigation API in VM 1st with child container support
Remote Operation Layer
14 Apr 2014 by
Kemeny Attila
Service layer which hides the concrete technology details and doesn’t need to change when a new feature is implemented.
A Lean and Mean Un-opinionated Templating Engine
21 Mar 2016 by
Marc Clifton
Based on Razor template engine syntax, a straightforward, extensible, easy to maintain implementation of a templating engine.
Story of Equality in .NET - Part 4
21 Aug 2017 by
Ehsan Sajjad
This article is the continuation of the previous three articles regarding how Equality works in .NET, the purpose is to give developers a more clear understanding on how .NET handles equality for types.
C# System.Random extensions
29 Jul 2016 by
Igor Krein
A library of simple extension methods that could be useful for data generation tasks
Dependency Injection to The Core
28 Dec 2016 by
Fiyaz Hasan
Learn how dependency injection mechanism has evolved from ASP.NET to ASP.NET Core.
Solving the Brain Teaser Triangle Peg Game
1 Jun 2017 by
Marc Clifton
Three algorithms are presented -- iterative, recursive yield, and recursive step-and-continue, with a real time and interactive UI of the solving process and solution.
Refresh your cached data asynchronously
18 Apr 2013 by
Guirec
A pattern for an always available cache using asynchronous refresh.
Selection of .NET Edition for Your Projects
13 Dec 2016 by
Afzaal Ahmad Zeeshan
Overview of selecting a .NET edition over other, based on services and features provided
Deployment, because WPF desktop applications aren't dead yet
18 Dec 2015 by
Mohamed Kalmoua
This article describes how you can deploy your application using ClickOnce and Windows Installer technology.
Duplex gPRC
27 Nov 2020 by
Sacha Barber
Small demo on creating C# duplex (streaming) gRPC client/server
Defend ASP.NET and WCF from Various Attacks using Nginx
28 Jul 2016 by
Omar Al Zabir
Protect ASP.NET and WCF from various brute force and Denial of Service attacks and speed up response time using nginx.
Application Architecture - Grab Fried Onion Rings And Throw Spear Into Onion Architecture And Domain Driven Design
5 May 2017 by
Habibur Rony
This will cover how to use Domain Driven Design in your application according to the Onion Architecture. There are short descriptions about architecture Category / Style, N-Layer / N-Tier Architecture, Template Method Pattern and Facade Design Pattern.
Visual Studio Extensibility (Day 3): Visual Studio Extension in Visual Studio Isolated Shell
8 Mar 2017 by
Akhil Mittal
Customize basic Visual Studio Isolated shell application and add custom extension to the shell application.
C# Docx to HTML to Docx
22 Dec 2016 by
Ozesh Thapa
Converting Docx To Html to Docx
Creating a Cursor from a Font Symbol in a WPF Application
2 Apr 2018 by
Clifford Nelson
This gives the code to create a cursor from a character in a font.
Setting Screen Brightness in C#
13 Dec 2009 by
Ron Beyer
Tutorial on programmatically setting the screen brightness using C#.
Using WF4 WorkflowInvoker
1 Sep 2009 by
Roman Kiss
This article describes a design, implementation and usage of the custom service operation invoker for invoking a xaml workflow. It is based on the upcoming Microsoft .NET 4 Technology.
ySurf : A Yahoo! Messenger clone built in Silverlight
28 Mar 2010 by
Vinit Yadav
A Yahoo! messenger clone application built with Silverlight and its Duplex Polling WCF service. Explains how to deal with the Yahoo! packet format named YMSG.
MatchKit Library
21 Apr 2014 by
fabio bussu
MatchKit is a .NET Library that provides a set of classes to build patterns to match simple and complex strings
Drawing a Basic 3D Cylinder Chart in WPF
4 Oct 2014 by
Marco Bertschi
A really basic 3D Cylinder chart, drawn on a WPF canvas
Autoshutdown Service in C#
10 Jan 2014 by
Kees van Spelde
This is an alternative for "AutoShut, my first program in C#"
C# CSV File and String Reader Classes
3 Sep 2014 by
Vladimir Nikitenko
CSVFileReader and CSVStringReader are light weighted and fast classes that resemble unidirectional data set
Code39 Barcodes in VB.NET and C#
24 Sep 2015 by
Stefano Castelli
The article will illustrate how to create a Code39 barcode in VB.NET and C#
Cross Cutting Concerns in .NET Applications
27 Nov 2015 by
Christian Vos
How to use Microsoft Unity Interception as a solution for cross cutting concerns in a .NET application
A Particle Swarm Optimizer In C#
6 Sep 2016 by
George Swan
An articial life algorithm that attempts to solve a problem by flying a swarm of entities through a range of possible solutions where each entity is guided by the performance of other members of the swarm
In Search of the Ultimate DataTable Serializer
28 Sep 2016 by
Massimo Fabiano
I know that "returning DataSets from WebServices is the spawn of Satan" but...
Intercommunication Between the FlowSharp Canvas and a FlowSharpCode Application
2 Jan 2017 by
Marc Clifton
Illustrating both HTTP and WebSockets Intercommunication
Class-less Coding - Minimalist C# and Why F# and Function Programming Has Some Advantages
7 Aug 2017 by
Marc Clifton
Not very classy in C#, but pretty classy in F#.
Handwritten Digits Reader UI
8 Jan 2019 by
KristianEkman
A C# object oriented Neural Network, trainer, and Windows Forms user interface for recognitions of hand-written digits.
Database Bot using Oscova
17 Jan 2017 by
DaveMathews
Use Oscova, a bot development framework, to create a Natural Language Interface to an SQL Database
C# Out VS Ref
4 Sep 2015 by
Shivprasad koirala
This blog discusses about C# Out vs Ref keyword.
Adventures in Debugging: Hosting Processes, Windows Subsystems, and Other Magical Things
1 Aug 2021 by
David A. Gray
Though useful and mostly harmless, pitfalls can lead unwary developers astray.
A Tic Tac Toe AI with Neural Networks and Machine Learning
24 Jun 2019 by
Thomas Daniels
This article describes the making of a tic tac toe player that uses neural networks and machine learning..
Virtual Mode ListView
11 Sep 2009 by
yetibrain
A listview running in virtual mode
Build Simple AI .NET Library - Part 5 - Artificial Neural Networks
18 Sep 2017 by
Gamil Yassin
Types of Artificial Neural Networks
Test Driven Development Process with XUnit
30 Jan 2022 by
Nick Polyak
This article explains Test Driven Development using XUnit with a detailed sample.
ASP.NET Core and Web API: A Custom Wrapper for Managing Exceptions and Consistent Responses
4 Jun 2020 by
Vincent Maverick Durano
This article will talk about how to implement a custom wrapper for your ASP.NET Core and Web API applications for managing exceptions, providing meaningful and consistent responses to consumers.
Angular 4 Data Grid with Sorting, Filtering & Export to CSV
10 Jul 2017 by
Yaseer Mumtaz
This article helps to understand the architecture and use of simple data grid developed in Angular 4.
Patterns and Frameworks - What's Wrong?
9 Aug 2022 by
Paulo Zemek
Are you spending most of your time just writing code to "glue" your components together? Let's change that!
Thread Sychronization using monitors
31 Oct 2001 by
Nish Nishant
Introduction to using the Monitor class for accessing shared resources from multiple threads
Bi-directional HTTP Connection
22 Jan 2004 by
Wytek Szymanski
An article about a bi-directional communication using a single open connection.
Interfacing with IBM WebSphere MQ (formally IBM MQSeries) from .NET
4 May 2006 by
Khalid Al-Hadlaq
This article is targeting architects and developers who are looking for a way to integrate .NET applications / Servers with IBM WebSphere MQ (IBM MQSeries).
A Stegano-Framework for .NET Developers
2 Aug 2006 by
Corinna John
From tutorial snippets to open source project.
LINQ To Google Image and Google Groups
8 May 2007 by
Ming.Chen
A LINQ Implementation for Google Images/Groups Search
XML Serialization on a Collection of Multiple Types that are Unknown
22 Jan 2009 by
Sike Mullivan
Shows how to do XML serialization on a collection of multiple types when the types are not known.
ASP.NET AJAX Testing Made Easy using Visual Studio 2008 Web Test
11 Jun 2011 by
Omar Al Zabir
A collection of ExtractionRules, ValidationRules, and Request Plugin that makes ASP.NET and AJAX website testing painless. No need to record tests, write parameterized tests using server-side control names, handle UpdatePanels, simulate clicks on buttons - all from Web Test.
ProcessCommunicator
5 Apr 2010 by
PIEBALDconsult
A class that allows my CommScript class to "'drive' a command line utility".
Export to Excel Functionality in WPF DataGrid
24 Oct 2010 by
Nithyaduruvan, Sathishkumar_P
This article describes about the export functionality of Excel sheet from WPF datagrid.
WPF TextBox With Ellipsis
13 Jan 2012 by
MarkLTX
A subclass of the WPF TextBox control that displays an ellipsis when the text doesn't fit.
Displaying a CodeDOM using WPF (Part 3)
12 Nov 2012 by
KenBeckett
Displaying a CodeDOM graphically using WPF
Emulation of I2C Protocol on C#
26 Feb 2013 by
Nakul Vyas
This article presents code to emulate I2C protocol in C#, this can be useful in applications like data acquisition without microcontrollers.
.NET Shell Extensions - Shell Drop Handlers
19 Jan 2013 by
Dave Kerr
Rapidly create Shell Drop Handler Extensions using .NET
Visual Studio Visualizer: Part 2 - Entity Framework
23 Jun 2013 by
Frederico Regateiro
This project creates a Visual Studio visualizer for entity framework queries, views edit and runs the generated SQL.
WinRT : Simple ScheduleControl
16 Sep 2013 by
Sacha Barber
Introduction to B-trees: Concepts and Applications
15 Aug 2014 by
Ștefan-Mihai MOGA
How to solve real-life problems using B-trees
Evaluation of .NET Testing
19 Aug 2015 by
Ganesan Senthilvel
Stimulating journey on evaluation of .NET Testing over the years
Composite Applications with Prism in WPF - Part 3
5 Dec 2015 by
Snesh Prajapati
In this article we will learn about EventAggregator and IActiveAware interface and its uses in WPF application using Prism. This is continuation of second part of article series having total three parts.
Creating A Facebook Bot Using Microsoft Bot Framework
2 Jul 2016 by
defwebserver
You can easily create a Bot and deploy it on Facebook.
A C# System Tray Application using WPF Forms
17 Mar 2017 by
Leif Simon Goodwin
How to create a basic system tray app in C# and WPF
SOLID Poker - Part 2 - Compare Poker Hands
7 Apr 2017 by
Marco-Hans Van Der Willik
This article continues with the development of the SOLID Poker project, and covers functionality to Compare and Validate Poker Hands.
Contributing to .NET for Dummies
28 Apr 2017 by
Rion Williams
Contributing to .NET for dummies
An Object Explorer Written in a Map/Filter style with C# Partial Application Functions
26 Jun 2017 by
Marc Clifton
Among other things, an exploration into writing C# code in a functional programming style.
Capturing a Pop Up Window using LifeSpanHandler and CefSharp
26 Feb 2021 by
Sheila Pontes
How to capture the event open of a pop up, stop this event and open them wherever you wish
How to Implement Generic Queries by Combining EntityFramework Core and GraphQL.NET?
8 Jan 2018 by
thangchung
This article will show you how to expose the database schema to the APIs, then query from it. No boilerplate code for simple query actions. Go and read it.
Scaffolding Dapper with CatFactory
8 Dec 2019 by
HHerzl
Scaffolding Dapper with CatFactory
Brief Introduction of a Continuous SQL-stream Sending and Processing System (Part 1: SQLite)
1 Jan 2021 by
Yuancai (Charlie) Ye
Application of SocketPro onto various databases for continuous inline request/result batching and real-time stream processing with bi-directional asynchronous data transferring
Construction and Design-Time Support of the RadioGroup User Control
22 Jul 2021 by
Сергій Ярошко
How to create a .NET user control combining several radio buttons with a border and a caption and provide it with handy support of Visual Studio at design time.
Image Filters
30 Sep 2009 by
Fiwel
Different ways to apply image filters.
My Work with LiteDB
14 Jul 2022 by
Ivan Yakimov
My experience with the LiteDB database
Simple SignalR Server and Client Applications Demonstrating Common Usage Scenarios
16 Jul 2019 by
Mustafa Kok
SignalR server and client applications for demonstrating common scenarios like connecting, disconnecting, joining and leaving groups, sending messages to all clients, to specific or group of clients
.NET MSIE OnBeforeNavigate2 Fix
29 Oct 2002 by
Stephane Rodriguez.
Provides a fix to catch otherwise hidden events of MS Internet Explorer
Drag and Drop support for column reordering in DataGrid control
5 Dec 2004 by
Elvin Cheng
Enhance the DataGrid control with drag and drop support for column reordering
NormalMapCompressor - A tool to automatically compress normal maps
4 Jul 2005 by
DeltaEngine
Normal maps are used for realtime 3D rendering (mostly in games) to improve the visual quality, but compressing them makes the 3D content look ugly, this tool helps to fix that problem.
Rendering Textures with Alpha Channels and Color Key Transparency using a MatrixStack in Managed Direct3D
28 Jun 2005 by
Greg Rezansoff
This brief article describes how to use managed Direct3D to render texture bitmaps with alpha channels and transparency key colours onto vertices in C# with the aid of a MatrixStack.
sharpcms.net - CMS framework based on XSLT and XML
29 Nov 2005 by
peterhansen2
CMS for .NET based on XSLT, XML and C#.
Introduction to Creating Dynamic Types with Reflection.Emit: Part 2
1 May 2006 by
jconwell
Part 2 of an introduction to creating dynamic types. This article shows how to actually generate the methods in a dynamic type and how to call them.
Nullable datetime column in .NET DataGrid with DateTimePicker
17 Aug 2009 by
vic_ch2000
A nullable datetime column in .NET DataGrid with DateTimePicker.
Using LINQ for type Conversion
25 Feb 2010 by
dasblinkenlight
Converting between types in .NET
Windows Ribbon for WinForms, Part 13 – DropDownColorPicker
15 Mar 2010 by
Arik Poznanski
In this article, I'll present how to use the ribbon drop down color picker control.
Windows Ribbon for WinForms, Part 20 – QuickAccessToolbar
23 Mar 2010 by
Arik Poznanski
In this article, I'll present how to work with the ribbon quick access toolbar.
EXIF Compare Utility using WPF
12 Apr 2010 by
Nish Nishant
The Exif Compare Utility is a WinDiff equivalent for image files that compares the Exif meta-data and displays the differences and similarities. The application is written using WPF and MVVM.
Excel Add-in for Exporting Data to XML
21 Jan 2015 by
Syed Umar Anis
ExcelXMLExport is a Microsoft Excel 2010 / 2013 Add-in that generates XML data from Excel sheet.
Globalization in WPF using ResourceDictionary
31 Jan 2013 by
Hiren Khirsaria
Multilingual application using ResourceDictionary in WPF.
WPF-Less GDI+.NET Report Component: Star Report
25 Jan 2013 by
FatCatProgrammer
StarReport: WPF-less GDI+.NET report component.
Unexpected Garbage Collection Results Courtesy of Your Compiler
9 Aug 2013 by
Dennis C. Dietrich
Clarifying how the .NET GC identifies objects to collect once and for all... hopefully...
C# Generic List Extensions for Data Output to Formatted String, CSV File, and Excel Worksheet Window
5 Dec 2013 by
Shenwei Liu
Using extension methods to export data from a Generic List to a formatted string, CSV file, or Excel Worksheet window with data field selections
ASP.NET Identity 2.0 Change Primary Key from String to Integer
1 Jun 2014 by
S. M. Quamruzzaman Rahmani
ASP.NET team released Identity framework 2.0. The new release contain some new features like generic primary key. This article explain how to change primary key from string to integer & use it with MVC5..
WuffProjects.CodeGeneration
28 Feb 2016 by
WuffProjects
WuffProject.CodeGeneration is an easy to use, reliable and powerful code generation framework
When Lists and data grow up
21 Sep 2015 by
Thomas Nielsen - getCore
This article will take a dive into one of the reasons why code sometimes sands over.
Tutorial | Quick start-up for .NET core on Windows and Linux
21 Jul 2016 by
Gourav Jain MCTS®
This article will give a kick off start to build an application using .NET core on Linux and Windows
UWP Alien Sokoban - Part 2
18 Oct 2016 by
Daniel Vaughan
A fun UWP implementation of the game Sokoban, demonstrating some new features of XAML and C# 6.0. Part 2
C#.NET: Implementing SVD++ AI Data Mining Algorithm To Produce Recommendations Based On Ratings Prediction
1 Feb 2017 by
Arthur V. Ratz
In this article, we will discuss about the implementation of the SVD++ AI data mining algorithm to produce recommendations based on ratings prediction
Iterated Function Systems and self similar fractals
22 Jan 2017 by
Miguel Diaz Kusztrich
A simple way to build a wide family of fractals
Asp.Net: Monitor performance without using windows performance counters.
15 Feb 2017 by
Sergey Volk
Open source framework for monitoring Asp.Net Web Api 2 and MVC5 applications performance without using windows performance counters, automates performance counters data collection, store and visualization.
Dynamically Querying Entity Framework with ASP.NET
15 May 2017 by
Charles d'Avernas
A ready-to-use solution for dynamically querying an Entity Framework DbContext in ASP.NET
UnitParser
1 Jun 2018 by
Alvaro Carballo Garcia
Comprehensive unit parsing library
The astounding Pickover's biomorphs
27 Nov 2017 by
Miguel Diaz Kusztrich
An infinite set of biological shape fractals in the complex plain
Newt: A Powerful C# Parser Generator in a Small Package
14 May 2019 by
honey the codewitch
An LL(1) pull parser and generator that thinks it's an LL(k) parser - with a rich, simple and beautiful EBNF syntax
Using Multiple Return Values instead of Exceptions
4 Jan 2021 by
Rick Drizin
Discussion about how Exceptions are different from expected errors, and how to return errors in your methods using multiple return values
Form With End Resize
25 Aug 2020 by
Mark Kruger
OnResizeEnd does not supply all triggers you need, this form fixes that.
Midi: A Windows MIDI Library in C#
6 Jul 2020 by
honey the codewitch
Provides a complete managed API for working with MIDI files, sequences and devices
Extract Images and Icons of .NET Resources
17 Nov 2011 by
Timur Eroglu
List and extract .NET resources
Mr. Crossworder - Create Crosswords in Seconds!
6 Jan 2019 by
Mehedi Shams
Crossword creator - with a touch of Unicode Logic!
Build Simple AI .NET Library - Part 3 - Perceptron
16 Sep 2017 by
Gamil Yassin
Perceptron, when to use it and sample code
Singular Values Decomposition (SVD) In C++11 By An Example
30 Dec 2018 by
Arthur V. Ratz
In this article, we will demonstrate how to compute full SVD of a given matrix A and discuss about the code in C++11 implementing the full SVD computation by using simple iteration and Jordan-Gaussian methods.
Microsoft Blazor - Custom Controls for Dynamic Content
17 Oct 2020 by
Ev Uklad
Demonstration of how to create an externally extendable dynamic page, which will support all controls that we can add later in a separate assembly without the recompilation of the dynamic page
MQTT – Message Queue Telemetry Transport Protocol with .NET Core
19 Oct 2020 by
JawadHasan
How to use MQTT Protocol in your .NET Core Applications
Creating a Custom WPF Window
16 Nov 2018 by
nvasilev1
Often, when WPF developers have to write a custom window, they find themselves drowning in countless articles, blog posts, and StackOverflow threads each depicting a different approach to the problem.
SPA^2 using ASP.NET Core 1.1 + Angular 2.4 - Part 5
16 Mar 2017 by
Robert_Dyball
Create a simple data grid that provides list, add, edit and delete and uses a simple 'parent/child' template to provide view, edit or add functionality
Garbage Collection in .NET
17 Jun 2002 by
Chris Maunder
A quick introduction to Garbage collection in .NET using Managed C++
Deadlock Detection in Existing Code
11 Jan 2008 by
eransha
The article briefly discusses deadlocks behavior, and presents an easy way to detect them.
Using Dynamic Proxies for Fault Tolerance and Failover
4 Mar 2009 by
Derek Viljoen
How to leverage LinFu (or any other Dynamic Proxy implementation) for Fault Tolerance and Failover
Introduction to Composite WPF (CAL, Prism): Part 2
19 Jul 2009 by
Jammer
An article showing an extremely simple implementation of CompositeWPF.
Safe WinForms Databinding
5 Aug 2009 by
Cosmin Oprea (aka somalezu)
This article describes a very simple way to make WinForms databindings without the need to refer the datasource property names with magic strings.
Populate TreeView Menu with XML
10 Sep 2009 by
ralph1957
This step-by step article describes how to populate a TreeView control by using XML data.
Adapter Design Pattern
8 Oct 2009 by
Allen _ Wang
This article shows a case study about how we use the Adapter Pattern to Elizabeth's Day Care Center
Silverlight Windows User Identity Name
15 Dec 2009 by
Webplethora
How to get the Windows user identity name in Silverlight.
Windows Ribbon for WinForms, Part 5 - Application Menu with SplitButton and DropButton
6 Mar 2010 by
Arik Poznanski
In this article, I'll present how to use the ribbon application menu with ribbon split button and ribbon drop button controls.
Windows Ribbon for WinForms, Part 8 – ComboBox
9 Mar 2010 by
Arik Poznanski
In this article, I'll present how to use the ribbon combo box control.
Windows Ribbon for WinForms, Part 18 – ContextPopup
22 Mar 2010 by
Arik Poznanski
In this article, I'll present how to work with ribbon context popup.
Balanced Binary Search Tree (BST) (Search, Delete, InOrder, PreOrder, PostOrder,DepthFirst, BreadthFirst, BalanceTree)
9 Jun 2012 by
FatCatProgrammer
Balanced Binary Search Tree (BST) (Search, Delete, PrintInOrder, PrintPreOrder, PrintPostOrder,DepthFirst, BreadthFirst, BalanceTree)
Claim based Authentication- WIF: Part 3
26 Nov 2011 by
Brij
This article discusses some problems with the earlier approach and discusses Identity federation
Learning XNA 2D Engine IceCream With 1945 Demo Project
8 Aug 2012 by
Tyler Forsythe
IceCream1945 is a demonstration of XNA and the IceCream 2D library in a 2D top-down scrolling shooter similar to 1942 for the NES.
Code Generation in Visual Studio From XML Files - A Simpler Approach
21 Feb 2012 by
Anoop Pillai
In this post, we'll explore how to generate code from a simple XML model, with in Visual Studio - For a lot of scenarios
A Beginner's Tutorial for Understanding Templated User Controls
6 Jun 2012 by
Rahul Rajat Singh
Understanding templated web user controls from a beginner's perspective.
Small Paging Control for Windows Presentation Foundation (WPF)
27 Jun 2012 by
freedeveloper
A small control to control paging in Windows Presentation Foundation.
Dynamically adding controls on a hierarchical structure on MVC
6 Aug 2012 by
_DanV_
How to dynamically add controls on a hierarchical structure on MVC.
A C# SMTP server (receiver)
17 Sep 2012 by
ObiWan_MCC
A C# SMTP server (receiver).
Socialize your ASP.NET application with OpenSocial
26 Sep 2012 by
Ilya Builuk
This article briefly describes what is OpenSocial and how to use it in ASP.NET applications by Catpic
Recording Audio to WAV with WASAPI in Windows Store Apps
19 Jan 2013 by
padmore
Getting started recording audio to WAV with WASAPI in Windows Store apps
Azure WebState
9 Jun 2013 by
Florian Rappl
Crawling tons of (individual) web information and creating statistics using Windows Azure.
SOLID Principles: The Liskov Principle -> What, Why and How
11 Nov 2018 by
Christian Vos
SOLID principles: The Liskov Principle, a simple example in C#
Slitastic
13 Aug 2013 by
Florian Rappl
Creating a highly extensible presentation app with multi-user and device integration for tablets.
Weaver
14 Nov 2013 by
Alexander SchuIze, Felix Herbst, Paul Kirsten
Multi-User game for AIO where players build their own spider's web
Working with MongoDB's $lookup Aggregator
21 Jun 2016 by
Marc Clifton
A deep dive into the $lookup aggregator with examples of one-to-one, one-to-many, many-to-many, and nested relational "queries"
A simple WPF LineChart control
29 May 2016 by
Kenneth Haugland
A simple WPF chart control that draws a 2D line chart.
Serialize/Deserialize objects by reference to transfer json between server and client
31 Aug 2016 by
Sheshnath Kumar
This article will find out a solution to serialize/deserialize object by reference at server and client, also will serialize/deserialize objects having circular references.
Create a Dockerized Python Fiddle Web App
10 May 2017 by
Marc Clifton
Using C#, a simple web server, and Docker, I show you how to create a "Fiddle" website to run Python (or other script languages)
Continued code execution after (throwing) an Exception
3 Jan 2018 by
Jasper Lammers
A method to easily toggle the way exceptions are being handled (either being thrown or handled by custom code), while still conserving the stack trace when exceptions are not being thrown.
Orbital Mechanics Introduction
23 Dec 2018 by
charles922
Introduction to Orbital Mechanics - 2 Body Problem
A Fixed Block Memory Allocator in C
24 Dec 2018 by
David Lafreniere
Unique allocator features improve performance and protect against heap fragmentation faults on any C or C++ project.
C# Language Features: Tuples
1 Mar 2019 by
Serge Desmedt
A deep dive into tuples
BusinessRulesEngine for .NET Applications
1 Dec 2019 by
Dan Ionescu (USINESOFT)
Complex cascade defaulting of properties on an object graph triggered by other property changes
SQL Server Governor: The unknown hero
7 Sep 2012 by
Shivprasad koirala
This article will discuss about SQL Server governer.
Action Result in ASP.NET MVC
21 Jun 2018 by
Syed Zain Shah
In this article, you will learn about basic foremost concepts about Action Results in ASP.NET MVC 5. Hope you'll enjoy this. Feel free to give your feedback.
The Oracle Call Interface (OCI) and ODP.Net - Part 1
23 Mar 2021 by
Espen Harlinn
Proven techniques for fast Oracle Database access using .NET 5.0 and native C++
The Product Aggregate in T-SQL Versus the CLR
22 Feb 2013 by
Scott Burkow
An exercise in algorithm analysis and design.
16 Days: A TypeScript Application from Concept to Implementation
3 Nov 2019 by
Marc Clifton
A metadata driven, view defines the model, schema generated on the fly, from concept to prototype application in 16 days
A C# 3D Surface Plot Control
19 Feb 2021 by
Leif Simon Goodwin
A 3D surface plot control in C#
Dynamically Add Access Database Columns at Runtime using VB.NET
21 Apr 2013 by
Rob Culhane
How to dynamically add access database columns at runtime using VB.NET
Azure IoT Hub Tester
20 Feb 2022 by
Roman Kiss
Design and implementation of small tool, tester for exploring Azure IoT Hub with virtual MQTT device
Logging Proxy in C#
9 May 2022 by
Mark Pelf
In this article, we build a practical reusable Logging Proxy in C#
Plotting a Real-time 3D Toolpath with Helix Toolkit
30 May 2018 by
Bruce Greene
A plot control based on the WPF Helix Toolkit for visualizing a real-time stream of 3D locations
Mouse and Keyboard Tracking and Simulator
21 Nov 2014 by
CodeFate
Revision of the Global Mouse and Keyboard Library from Brian Geiman
Using a Smart Card Certificate with .NET Security in C#
5 Oct 2011 by
orouit
How to use smartcard certificates in your .NET application
C# Header control
20 Jun 2004 by
Sergei_VP
.NET wrapper of the system Header control.
IBM WebSphere MQ with C#: GUI application that is both GET REQUEST/ PUT RESPONSE and PUT REQUEST/ GET RESPONSE
9 Nov 2005 by
Koushik Biswas
An article on synchronization of a GET REQUEST/ PUT RESPONSE MQ C# program and a PUT REQUEST/ GET RESPONSE MQ C# program.
DACBuilder – Data Access objects generation tool based on XML and XSL templates transformation
31 Mar 2006 by
Dan Radu
The DACBuilder application provides auto-generation features from multiple database systems in multiple programming languages.
Cat - A Statically Typed Programming Language Interpreter in C#
4 Nov 2006 by
Christopher Diggins
This article contains the public domain implementation of an interpreter for a statically typed stack-based programming language in C# called Cat. The accompanying article is a high-level description of how the various modules work, a brief description of the language, and links to related work.
Data Visualization in WPF with LINQ to SQL and Data Binding
21 Dec 2007 by
Bruno Sonnino
This article will show how to use data binding and styles to show data coming from a Microsoft SQL database using the new object-relational model introduced in Visual Studio 2008, LINQ to SQL, allowing grouping, sorting and filtering of data with almost no code.
Asynchronous T-SQL Execution Without Service Broker
15 Sep 2008 by
Oleg Vorkunov
Set of SQL CLR Stored Procedures to execute T-SQL asynchronously without using a Service Broker.
Vernam encryption/decryption of files
27 Sep 2008 by
Günther M. FOIDL
Class for encrypting/decrypting files using a Vernam chipher.
APNG Viewer
6 May 2009 by
SprinterDave, Huisheng Chen
Parse and extract APNG frames to each PNG file
The Nito.MVVM (WPF) Library: Commands
25 Jul 2009 by
Stephen Cleary
Describes the ViewModel command classes in the Open-Source Nito.MVVM (WPF) library, and provides guidelines on their usage.
Windows Mobile App Development Part 7: Mobile Web Development
30 Oct 2009 by
mstruys, dougturn
Learn to create web based apps for Moble Devices with AJAX support enabled using browser controls.
WCF Service over HTTPS with custom username and password validator in IIS
19 Feb 2010 by
Ondra Spilka
How to host a WCF HTTPS service with a custom username validator, in IIS.
Windows Ribbon for WinForms, Part 6 – Tabs, Groups and HelpButton
7 Mar 2010 by
Arik Poznanski
In this article, I'll present how to use ribbon tabs, groups and the ribbon help button control.
Windows Ribbon for WinForms, Part 15 – Use Ribbon as External DLL
19 Mar 2010 by
Arik Poznanski
In this article, I'll present how to load ribbon resources from external DLLs.
Windows Ribbon for WinForms, Part 16 – ApplicationModes
20 Mar 2010 by
Arik Poznanski
In this article, I'll present how to work with ribbon application modes.
Simple Silverlight 4 Example Using oData and RX Extensions
23 May 2010 by
defwebserver
A simple Silverlight application that uses RX Extensions to communicate with an oData service.
Building a Client-Side Grid Control using SharpKit
19 Dec 2019 by
Dan-el Khen
Sample code on building a client-side Grid control in C# using SharpKit
A WPF Font Picker (with Color)
19 Jan 2013 by
Alessio Saltarin
Unsatisfied by the WPF Font Pickers available, I decided to write one on my own (well, almost...)
Silverlight Pronunciation Test
29 Apr 2012 by
Marcelo Ricardo de Oliveira
How to create a pronunciation test tool using Silverlight and Python
Demystifying concurrent lazy load pattern
5 Aug 2012 by
MVukoje
Shows what are common mistakes in lazy load implementations and how to implement fast concurrent lazy load cache..
Excel Add-in Framework for Validating and Exporting Data
17 Aug 2012 by
Clifford Nelson
A framework for scanning a worksheet for headers, reading and validating data, providing feedback to the user, and displaying the data in a form with the results.
How to Mock Test an Entity Framework Model-First Project
29 Aug 2012 by
linush
Explains how to mock test an EF Model-First project using ADO.NET Entity Data Model template
Inheriting from a Look Less WPF Control
31 Jul 2017 by
Dirk Bahle
This article explains how to take advantage from look-less WPF controls through inheritance
DicomTagSeeker - A DiCOM repository tag searcher
18 Apr 2013 by
tumbledDown2earth
A tool for Seeking, Sorting and Reporting in a morderately large DICOM repository.
C# - Generate and Deliver PDF Files On-Demand from a Template Using iTextSharp
12 Dec 2013 by
John Atten
In this article, we will examine the specifics of this "Just-In-Time" PDF generation.
Controlling a Myo Armband with C#
6 Oct 2014 by
Nick Cosentino
Are you excited to get your Myo armband from Thalmic Labs? If you're a C# developer, then check out this open source library to help you control your Myo! The post appeared first on.
TmStorage, Open-source Storage Engine for .NET
21 Nov 2014 by
Tomaz Koritnik
TmStorage is a structureless virtual file system from which complex storages or databases can be built.
UNITY 3D – Game Programming – Part 9
8 May 2015 by
Vahe Karamian
The ninth article in a series to discuss Unity 3D and how to get started with your own 3D projects.
UNITY 3D – NETWORK GAME PROGRAMMING
26 May 2015 by
Vahe Karamian
This article will cover the basics of network programming using Network View in Unity 3D. We will be creating an Authoritative Server based networking environment showcasing the basics functions of network programming using Unity 3D and C#.
Protect word document using C# and Word Automation
24 Nov 2015 by
koolprasadd
This article explain you How to protect word document using C# and Word automation
Using Reactive Extensions - the basics
29 Feb 2016 by
Kenneth Haugland
How to connect hot observables to Rx
Safe Images from Streams
9 Oct 2016 by
Midi_Mick
Alleviate issues with Image objects created from streams and files.
ASP.NET Web API - Keeping It Simple
25 Nov 2016 by
kannankeril
This article is an attempt at splitting out the controller layer to reduce its complexity and improve quality and maintainability of the resulting code.
WinForms + Sciter: Embeddable HTML/CSS/TIScript Control for Modern UI Development
17 Jan 2019 by
Ramon F. Mendes
A lightweight HTML control for WinForms
Domain Events with Convention-Based Registration and Deferred Execution Support
27 Mar 2017 by
Arthur Minduca
Domain Events registered by conventions with the container and fired only when the transaction is committed
Universal SMTP Code to Send Emails in .NET Apps
8 Aug 2017 by
Afzaal Ahmad Zeeshan, Iqra Ali
Since I wrote an article previously, I had been asked on various occasions to share the code on Yahoo! or Bing, etc. I wanted to write an article, with the code, which covers all of those vendors as well.
Implementing Custom XAML Intellisense VS2017 Extension
22 Nov 2017 by
Nick Polyak
Describes creating a XAML Intellisense Visual Studio 2017 extension
A Highlightable WPF/MVVM TextBlock in C#/VB.Net
22 Jan 2018 by
Dirk Bahle
Implementing text highlighting in a WPF TextBlock control with MVVM
Getting Started with Angular 7 And ASP.NET Core 2.1
27 Jan 2019 by
syed shanu
Getting started with Angular 7 and ASP.NET Core 2.0 using Angular 7 Web Application (.NET Core) Template and ASP.NET Core MVC Application
Getting Started with PouchDB - Part 1
15 Jan 2019 by
Paul D. Sheriff
As more and more users interact with web applications on their mobile devices, it is becoming increasingly important for software developers to allow them to work offline; PouchDB can help.
A Regular Expression Engine in C#
31 Mar 2019 by
honey the codewitch
A Non-Backtracking Regular Expression Engine for .NET (Core)
Windows Experience Score For Windows 10
5 Nov 2019 by
Howard 9448490
A replacement Windows Experience Score tool for Windows 10
Inspired by codewitch's "What is a Coroutine?"
25 Mar 2020 by
Marc Clifton
Abstracting codewitch's article into a cooperative worker implementation
The Atlas Copco Open Protocol Interpreter
18 Aug 2019 by
Henrique Dal Bello
This article describes a DLL made to help the community when communicating with Tightening Controllers via Open Protocol.
Excel Pixelating Image Creator
30 Aug 2017 by
Geek2Simon
Use Excel worksheet's cells as pixels to render real image (for fun and experiment)
Cinchoo ETL - CSV Writer
9 Sep 2021 by
Cinchoo
Simple CSV file writer for .NET
The DARL Language and its Online Fuzzy Logic Expert System Engine
7 Dec 2021 by
AndyEdmonds
A free service makes it possible to use a fuzzy logic expert system online. We'll go through an example of coding in .NET core to access this, and look at some of the features of the engine and the DARL language.
WPF MVVM View Binding to a Singleton and WeakReference
25 Apr 2018 by
Clifford Nelson
Concept to create a Singleton for WPF MVVM Binding, and using Weak reference for the property that is bound to.
Cinchoo ETL - Xml Reader
9 Feb 2022 by
Cinchoo
Simple Xml file reader for .NET
Rendering 3D Graphic in .NET with C# and Igneel.Graphics
20 Jan 2017 by
Ansel Castro
The article shows how to render 3D graphics with C# in .NET using an API Igneel.Graphics.
Why Do We Need MediatR?
15 Nov 2021 by
Ivan Yakimov
This article contains a discussion of MediatR NuGet package.
Sharing a USB Serial Device to Multiple Clients over TCP
23 May 2022 by
DaveAuld
Putting together an application to share a USB Sky Quality Meter to Multiple Clients
Photino: Open Source for Building Cross-Platform Desktop Apps via .NET Core
30 May 2022 by
raddevus
Fully Open Source Library for building Cross-Platform Desktop apps on .NET Core
Running and Debugging Multiplatform .NET (.NET Core, .NET5 and .NET6) GUI and Console Applications on Windows Subsystem for Linux (WSL)
1 May 2022 by
Nick Polyak
This article describes how to test and debug .NET/Avalonia Linux applications using WSL.
Secure Web Services via TCP/IP
30 May 2003 by
Simon Gregory
Describes an approach for delivery of Soap Messages serialised using ASP.NET Web Client Services over TCP/IP
MCMS User Roles
15 Mar 2005 by
Chester Ragel
Finding MCMS user by role.
Crossbrowser SmartNavigation Alternative II
3 Apr 2005 by
ibrahimuludag
An article describing how to create a server control that preserves the scroll position in longer pages.
Lat Lays Flat - Part 3: Creating A Google Maps .NET Control
17 Oct 2005 by
Bill Pierce
Creating an ASP.NET server control wrapper for the Google Maps API.
Slink Framework - Strongly Typed URLs for ASP.NET
4 Sep 2007 by
Brian Chavez
Slink is a code generating Framework that generates type safe URLs for ASP.NET. With Slink URLs, you increase code quality, increase maintainability, and get compile time checking of your URLs in all your ASPX pages (code-behind and non-codebehind).
Automatic Culture Flowing with WCF by using Custom Behaviour
30 Nov 2007 by
Patrick Kalkman
An article to demonstrate culture flow from Windows client to Windows server using WCF.
XSL 2.0 and XQuery 1.0 in .NET
18 Oct 2018 by
Gavin Sinai
Using the open source Saxon library, .NET programmers can benefit from XSL 2.0 and XQuery 1.0..
Build ReST based Web Services in .NET/C#
12 Jul 2009 by
Parag.Gadkari
A ReST based Web Service for C#.
Windows Workflow (WF) as a WCF Service
17 Jul 2009 by
eyedia
Sequential workflow as a WCF service. Create workflow custom activities, invoke child workflow from parent. Configure workflow runtime service using a config file. Basic idea of rules, creating a rule using the rule editor. Applying rules during runtime.
Populating a Silverlight DataGrid with Data from MDB
24 Nov 2009 by
raelango
This is a sample project to access Microsoft Access MDB data in Silverlight via OLEDB and dynamically populate a DataGrid.
Forward/Backward Code Navigation with the Mouse Thumb Buttons Inside Visual Studio 2010 (C++, Visual Basic, F#)
7 Feb 2010 by
Jochen Baier
Addin to navigate in your code using the thumb buttons of your mouse
Voice and Text Conferencing Library
14 Feb 2010 by
Irfan alam
A library for creating a voice and text conferencing application
Windows Ribbon for WinForms, Part 4 - Application Menu with Buttons
4 Mar 2010 by
Arik Poznanski
In this article, I'll present how to use the ribbon application menu.
Windows Ribbon for WinForms, Part 10 – Working With Images
12 Mar 2010 by
Arik Poznanski
In this article, I'll present how to work with images in the ribbon.
Windows Ribbon for WinForms, Part 12 – CheckBox and ToggleButton
14 Mar 2010 by
Arik Poznanski
In this article, I'll present how to use the ribbon check box and toggle button controls.
Windows Ribbon for WinForms, Part 17 – Contextual Tabs
21 Mar 2010 by
Arik Poznanski
In this article, I'll present how to work with ribbon contextual tabs.
Windows Ribbon for WinForms, Part 19 – RecentItems
23 Mar 2010 by
Arik Poznanski
In this article, I'll present how to work with the ribbon recent items control.
Hacking the Mono C# Compiler.
9 Oct 2010 by
Stefan Savev 2
Describes how to dump information from the C# parse tree
Dependency Injection with ObjectPoolManager (OPM)
31 Oct 2010 by
NavnathKale
Lightweight and simple
XTree - A Generic Implementation
30 Nov 2011 by
Marc Clifton
Revisiting the XTree implementation, using a generic controller.
ASP.NET User Control: File Browser
16 Dec 2011 by
Henryk Filipowicz
A web user control for selecting a file from the file system.
MSTest or TRX to HTML with Animated Charts
16 Oct 2012 by
Sunasara ImdadhuseneDOM Classes for Solution and Project Files (Part 5)
30 Nov 2012 by
KenBeckett
CodeDOM objects for VS Solution and Project files.
MATPaint - Simple App with Simple Features
10 Dec 2012 by
Zaid Pirwani, Maaz Ahmed
MATrix Paint - A simple app with many C# and mostly Windows Forms features for a class project.
Microsoft Interop API to convert the .doc, .docx, .dot, .dotx and .xls,.xlsx, .rtf to HTML
13 Dec 2012 by
Vijay Tanwar
Convert Word documents, Excel sheets to HTML files using Microsoft Office Interop API and render the result back to a client browser.
Async Await and the Generated StateMachine
28 Jan 2013 by
Amit Bezalel
The StateMachine internals displayed
Happiness is good logging
11 Feb 2013 by
DahlSailRunner
Really effective logging using Enterprise Library and just a little custom code.
WebBrowser Element Events and Values
16 Feb 2013 by
Marc Clifton
Sinking WebBrowser button element events and getting/setting input element values programmatically, without a web server.
Conway's Game of Life - A Rule Framework and Implementation
15 Apr 2013 by
tumbledDown2earth
A rule engine based approach to add and remove rules to play Conway's Game of Life
A Study of Gage Repeatability and Reproducibility for Automated Measuring Systems using VB.NET
24 Jan 2015 by
syed shanu
Gage R&R using VB.NET.
Enhanced Skype Chatter Robot
4 Aug 2013 by
Osman Kalache
An Enhanced Skype Chatter Bot, with a friendly user interface, programable knowledge base, testing interface with Export/Import knowledge base to files
Transient Fault Handling Application Block Simplified
6 May 2014 by
Igor Vigdorchik
How to use the Transient Fault Handling Application Block
Kinect v2 Point Cloud Scanner and Viewer
3 Apr 2017 by
Edgar Maass
Display a Point Cloud grabbed by the Microsoft Kinect v2 in a OpenGL control
Accessibility for Universal Windows apps
28 Feb 2015 by
Pooja Baraskar
Make your app usable by people who have limitations.
Undo/Redo Implemented via Stateless Command Stacks in WPF Applications (Sprint 1/4)
17 Nov 2018 by
MarkWardell
Undo/Redo Commands implemented with Minesweeper game example
WPF Custom Visualization Intermezzo 2: Bindings
24 Aug 2016 by
Serge Desmedt
(Yet Another) Investigation of WPF bindings
MDI Application Case Study - Part III - Child Forms
20 Nov 2015 by
stebo0728
Chromium (CefSharp) Tor Browser
28 Jan 2016 by
ahmet_uzun
An alternative Tor Browser built with C# using CefSharp and Tor.NET.
Execution Extension Method
19 Apr 2016 by
Clifford Nelson
A set of extension methods to support conditional Expression Bodied Functions and Properties
LINQ to Entities, Cross Apply, and Left Outer Join
12 May 2017 by
DaveDavidson
In this article, I show LINQ to Entities syntax that will produce queries with CROSS APPLY and LEFT OUTER JOIN clauses.
.NET Core Datagrid
18 Jan 2017 by
Bart-Jan Brouwer
.Net Core datagrid with server side paging, sorting and filtering
Fire Simulation and Prediction by Markov Chain Monte Carlo
5 Jun 2017 by
Mahsa Hassankashi
phenomenon prediction and simulation by Markov Chain Mont Carlo
Demo Data
30 Oct 2017 by
Kornfeld Eliyahu Peter
“Beware the Jabberwock, my son! The jaws that bite, the claws that catch! Beware the Jubjub bird, and shun The frumious Bandersnatch!” - LEWIS CARROLL
Advanced WPF TreeViews Part 2 of n
22 Sep 2017 by
Dirk Bahle
A list of advanced tips & tricks on Virtualized WPF TreeViews
SQLXAgent - Jobs for SQL Express - Part 1 of 6
27 Feb 2018 by
#realJSOP
Create and run jobs kinda like SQL Server Enterprise - Users Guide
Advanced WPF TreeViews in C#/VB.Net Part 3 of n
8 Dec 2017 by
Dirk Bahle,
Alaa Ben Fatma
Tips & tricks on visting and searching nodes in WPF TreeViews
LINQ Part 3: An Introduction to IQueryable
20 Apr 2018 by
Eric Lynch
Part 3 in the LINQ series, this provides an introduction to IQueryable, IQueryProvider, and LINQ expression trees.
Reflecting Within a Method Body
15 May 2018 by
Eric Lynch
Extends .NET reflection to decode the byte array returned by System.Reflection.MethodBody.GetILByteArray(), discusses the techniques to achieve this, and provides a brief primer on .NET reflection.
Building a DevOps CI/CD Pipeline for ASP.NET Core with VSTS
7 Jun 2018 by
Habibur Rony
This article mainly covers how to create new build and release definition using VSTS. There are short descriptions of DevOps, continuous integration, continuous delivery and continuous deployment.
Asynchronous Multicast Callbacks in C
29 Jan 2019 by
David Lafreniere
Simplify passing data between threads with this portable C language callback library.
noDB
11 Jan 2020 by
Mehdi Gholam
Using list of objects, LINQ and SQL like string query instead of a database with fastJSON serializer
Rolling Your Own? - A Simple CSV Parser Example
13 Jan 2020 by
Marc Clifton
Implementations in C# and F#
IoT Home Thing for Raspberry Pi
13 Mar 2018 by
Jose Motta
Home of Things based on Raspberry Pi, Linux, Swagger, Docker & .NET Core
How to Create a WCF WebService in VB.NET
16 May 2017 by
Rene Bustos
WCF WebService IN VB.NET Response JSON
Handling SoapException Detail with a WCF Client from a Web Service
4 Nov 2009 by
Larry Aultman
How to catch and handle ASMX based SOAP exceptions in a WCF client.
CsConsoleFormat: Introduction
3 Mar 2018 by
Athari
CsConsoleFormat library for .NET - Formatting in Console using modern technologies
Retro Game Cartography
29 Jul 2020 by
Mladen Janković
An algorithm for reconstructing game world map from captured game play
Microsoft Orleans - A Worked Example
19 Jul 2016 by
Duncan Edwards Jones
A quick example of how to use the Microsoft Orleans library to develop a distributed, fault tolerant fund accounting system
Client to Server File/Data Streaming
15 Dec 2021 by
Marc Clifton
Your one-stop guide for API and web-client Form, XHR, Blob, and Drag & Drop File/Data Uploading
An Insight into Region Creation and RegionAdapters in Prism based WPF Applications
17 Dec 2015 by
Snesh Prajapati
To work with Regions effectively in a Prism based WPF application, we must understand the relationship between WPF Controls, RegionAdapters and Regions. In this articles, we will learn about process of Region creation and critical role played by RegionAdapters with a demo application.
Enumeration RadioButton ListBox Control
3 Jan 2012 by
Clifford Nelson
An enumeration RadioButtion ListBox control.
Behavior to Make a UIElement Visible on MouseDown
16 Feb 2016 by
Clifford Nelson
This article presents a behavior that can make another UIElement visible when the mouse down event occurs on the UIElement this behavior is attached to. Have extended this to directly support fading of a Popup control
Capturing a Content Change in a ContentPresenter
5 May 2016 by
Clifford Nelson
This presents a way to capture a PropertyChanged on a DependencyObject, in this case to capture when the Content on a ContentPresenter changes and setting focus.
Service Locator Pattern in C#
13 Jul 2022 by
Mark Pelf
Beginner’s tutorial on Service Locator Pattern with examples
Part II: Web & Window Form Unification: Synchronous And Asynchronous Event Handling For Controls Created At Runtime
13 Jul 2002 by
Marc Clifton
This is the second part of a multipart article on unifying web and window form application development. This part demonstrates synchronous and asynchronous event handling of GUI control events, abstracting the implementation of web/window forms to be technology independant.
Implementing custom collection classes with MC++
12 Jun 2002 by
Nish Nishant
Tutorial on creating your own collection classes that are enumerable and sortable. Explains in detail the usage of the IEnumerable, IEnumerator, IComparable and IComparer interfaces
DataTableAdapter
4 Nov 2006 by
Craig G. Wilson
How to flatten collections for an ObjectDataSource using the Adapter Pattern.
Creating a DotNetNuke® Module using LINQ to SQL
24 Jan 2008 by
defwebserver
This tutorial will show you how to create a DotNetNuke module using LINQ to SQL.
A ServiceController Class that Contains the Path to the Executable
31 May 2008 by
Schmuli
Extends the System.ServiceProcess.ServiceController class to obtain the path to the process executable
Component for Customizing Menu Shortcuts
21 Oct 2008 by
Günther M. FOIDL
A component that allows the customization of menu shortcuts. This can be useful for barrier free applications.
Fight 404 errors with ASP.NET Routing
28 Dec 2008 by
avsol
Use ASP.NET Routing to avoid 404 Not Found errors.
Component for Fast Pass/Retrieve Data from Excel
13 Mar 2009 by
Jose Maria Estrade
ExcelCommunicator allows to pass and retrieve data to/from Excel as datasource/calculation-engine
Simple AI for the Game of Breakthrough
5 Jun 2009 by
Kel_
This article presents an implementation of a simple alpha-beta player for the board game of Breakthrough.
Is the Ready Queue FIFO?
26 Jul 2009 by
Nicholas Butler
The Truth and the Proof.
HTTP Binary Serialization through ASP.NET without WCF
15 Aug 2009 by
Ricardo Pineda Then
Shows how to serialize an object using binary serialization without using WCF.
How to Move, Resize, and Reconfigure Objects in Working Applications
30 Sep 2009 by
SergeyAndreyev
The algorithm and code to make objects in running applications moveable/resizable by users
Automatic Script SQL Server 2005 Objects and Commit under Subversion
9 Oct 2009 by
Ferreri Gabriele (Megasoft78)
Automatic script SQL Server 2005 objects and commit under Subversion
How to Configure TFS Server to Build Solutions v.2008 and v.2010 Side by Side on the Same Machine
9 Jan 2010 by
Sergey Arhipenko
This article shows how to build different versions of Visual Studio solutions on the same build server..
WCF by Example - Chapter XIV - Validation & Exception Management
25 Oct 2012 by
Enrique Albert
WPF Validation using the IDataErrorInfo interface combined with Validation attributes
C# & SQLite - Storing Images
15 May 2011 by
kribo
How to insert images / binary data into a database.
How to Use Symbol Server? (and Why You Really Like To Do It...)
13 Jan 2012 by
baruchl
How to setup .NET symbol server and enable production debugging without source code
Windows Form Screenshot and Print Preview in VB.NET
12 Mar 2012 by
ledtech3
How to take a screenshot of a Windows form and then print it.
Runtime variables class to support multiple application development
29 May 2012 by
Clifford Nelson
A runtime variables class to support multiple application development.
ASPxGridView Excel style – Adding notes to grid cells
5 Jan 2013 by
Mario Majčica
Adding notes to grid cells and visually mark them.
Reading Ultrabook Sensor Data with the Windows 8 Sensor API
6 Nov 2012 by
Yvan Rodrigues
A head start for App Innovation contestants
i00 NAT Forwarder
4 Mar 2013 by
i00
Automatic port forwarding for your UPnP enabled router.
Async/Await in WPF to invoke WCF with Busy Indicator and Abort Feature
30 Nov 2015 by
Nejimon CR
Implement WCF web service access from WPF with busy indicator and premature cancellation feature without using delegates, background worker, or separate event procedure
CourseLearner: Azure based E-Learning product
9 Jun 2013 by
Ravi Gadag
Azure based e-learning product.
Using WebSocket in .NET 4.5 (Part 4)
29 Jul 2013 by
Zhuyun Dai
Using WebSocket with Microsoft.WebSockets.dll.
Universal Numeric Edit Control
17 Sep 2013 by
Adam Zgagacz
User control for editing numbers writtem using different numeral base.
Dialogs the MVVM Way
9 Jan 2014 by
JP van Mackelenbergh
This article and the attached example will show how to show dialogs the MVVM way with databinding and no code-behind in the view.
Programming the Roma Widget Set (C# X11) - a zero dependency GUI application framework - Composite widgets
9 Mar 2015 by
Steffen Ploetz
How to develop Linux/Unix (X11) GUI applications in C# efficiently without dependencies to GUI frameworks like GTK or KDE. Description of composite widgets.
APOD Website Scraper, a HOPE demonstration
2 Jun 2014 by
Marc Clifton
Using the Higher Order Programming Environment, scrape the APOD website's 20 years of photos and explore APOD's.
Using MVVM to create Tabbed Interfaces with Calcium for Xamarin Forms
17 Sep 2014 by
Daniel Vaughan
Create a Xamarin Forms tabbed page or carousel page by binding to a collection of ViewModels; extending beyond the current capabilities of Xamarin Forms.
RunCmd - (A WPF-MVVM Batch File Editor/Runner Utility. Automate your repetitive tasks using commandline batch files)
27 Aug 2018 by
amitthk
RunCmd is a windows batch file editor,runner utility. It can be used to automate our repetitive tasks using commandline batch files.
UNITY 3D – Leap Motion Integration
8 Jul 2015 by
Vahe Karamian
This article will cover the basics of Leap Motion integration into your Unity 3D project. We will look at the basic setup and implementation of the basics to get you started. In order for you to try the code, you will need to have the Leap Motion hardware.
A Beginner's Tutorial for Understanding and Implementing a CRUD APP USING Elasticsearch and C# - Part 1
2 Oct 2020 by
Paulo Henrique S.S.
Elasticsearch and C# integration
A Generic and Advanced PDF Data List Reporting Tool
10 Feb 2020 by
Shenwei Liu
Creating PDF reports for grouped or non-grouped data lists in C# with many custom options and configurations (providing source code with .NET Framework 4.6.1 and .NET Core 3.1)
Creating an in-memory "L1" Cache for StackExchange.Redis .NET Clients
3 Feb 2016 by
Jonathan Cardy
Account of why and how I have written an open-source library for caching Redis data within a .NET client.
Learning C# (Day 11): Events in C# (A Practical Approach)
6 Jan 2017 by
Akhil Mittal
This article of the series "Diving into OOP" will explain all about events in C#. The article focusses more on practical implementations and less on theory.
ASP.NET Core WebAPI secured using OAuth2 Client Credentials
11 Jun 2017 by
Livio Francescucci
Use a JWTToken to access a .NET Core Web API leveraging IdentityServer4 / OAuth2.
Compiling Your C Code to .NET - Part 2
14 Dec 2019 by
Alexandre Bencz
With this new OrangeC/C++ compiler back-end, you can compile your C code to .NET.
Separation of Concerns and Smart Mixins with the help of Roxy IoC Container and Code Generator
10 Apr 2018 by
Nick Polyak
Achieving separation of concerns using Roxy IoC Container and Code Generator.
A Simple Pathfinding Laboratory
7 Sep 2018 by
Robert Vandenberg Huang
Experiment, run and compare different pathfinding algorithms and heuristic functions
Serverless - DevOps Little Helper
29 Apr 2019 by
Florian Rappl
Why not use serverless computing to perform maintenance tasks in Azure DevOps?
Debuggable Windows Service Template Project with C#
21 Jul 2019 by
Mustafa Kok
Easily debuggable Windows service project template written in C#
AutoUpdate: A GitHub Enabled autoupdater
19 Aug 2019 by
honey the codewitch
Automatically update your winforms app using github release binaries
Constant Reservation and Git Hooks using C#
23 Jan 2020 by
Ivan Yakimov
In this article, I'll explain how to build a robust Git hooks system using C#. Also, I'll show how to use it to solve a couple of nasty problems with development collaboration.
A Sudoku Puzzle Solver using Strategies
4 Feb 2021 by
DavidHancock
A .NET 5.0 Windows application written in C# that attempts to solve Sudoku puzzles
Tracking Objects with Pixy Visual Sensor on Raspberry Pi using Windows 10 IoT Core
26 May 2018 by
Victor Dashevsky
Processing the positioning information of visual objects detected by Pixy camera and received on Raspberry Pi via I2C, and using common design patterns in a C# program parsing robotics sensor data
Brief Introduction of a Continuous SQL-stream Sending and Processing System (Part 2: MySQL)
4 Apr 2021 by
Yuancai (Charlie) Ye
Continuous SQL-stream Sending and Processing System
SelfServe: A Self-hosting Self-installing Windows Service
14 Jan 2020 by
honey the codewitch
Add the ability to run a service in console mode and to control or install your service from the command line
Unified Concurrency I - Introduction
24 Mar 2019 by
ipavlu
The Cross-Platform Object-Oriented approach to Synchronization Primitives for .NET and .NET Core based on one shared pattern between two interfaces for General Threading and Async/Await.
Drawing and Evaluating Math Formulae in WPF Applications
10 Mar 2019 by
Sergey L. Gladkiy
The article describes a simple way of realizing math formula evaluation and drawing in WPF applications.
ASP.NET Gridview in Web Forms using Bootstrap 4
30 Jul 2019 by
Don Hoang
This post describes implementing ASP.NET Gridview using Bootstrap 4.
WPF Image Pixel Color Picker Element
30 May 2009 by
Oleg V. Polikarpotchkin
WPF element to pick up an image (either bitmap or drawing) pixel color.
Understanding Synchronization Context; Task.ConfigureAwait in Action
28 Aug 2021 by
Mohammad Elsheimy
SynchronizationContext class and how it affects code behavior in action, and a look at Task.ConfigureAwait()
Invisible Ink
24 Aug 2017 by
Daniel Vaughan
Using steganography to conceal text within a document or watermark a code file, using a whitespace encoder. Hide text in plain sight!
Build Simple AI .NET Library - Part 6 - ML Algorithms
29 Sep 2017 by
Gamil Yassin
ML algorithms based on function or type of problems they solve
Invoking TensorFlow AI (Python) from a C# Desktop Application
11 Oct 2019 by
Thomas Weller
Demonstrates how to invoke TensorFlow neural networks from a C# application and also how to use a Python-generated chart to display the results.
Value Converter to Evaluate User Equation Input
19 Jan 2012 by
Clifford Nelson
This value converter makes it very quick and easy to add the ability for the user to input equations in text boxes that are bound to numeric properties.
Corona SEIR Workbench
24 Apr 2022 by
Marcus Müller
Pandemic SEIR and SEIRV modelling software and infrastructure for the Corona SARS-COV-2 COVID-19 disease with data from Johns-Hopkins-University CSSE, Robert Koch-Institute and vaccination data from Our World In Data.
BriefMaker – An App for Processing Real-Time Market Data
10 May 2021 by
Ryan S White
Converts past and real-time stock market tick data into time-sliced summaries called Briefs
How to Write a Custom Logging Provider in ASP.NET Core
15 Apr 2019 by
Theo Bebekis
How to write a custom logging provider in ASP.NET Core
Create a Digital Ocean Droplet for .NET Core Web API with a real SSL Certificate on a Domain
1 Mar 2022 by
Marc Clifton
I want to host some simple applications under a real HTTPS domain. This article describes my foray into doing exactly this with a Digital Ocean Droplet.
SWAT - A simple Web-based Anomalies Tracker - Part 8
23 Sep 2003 by
Al Alberto
An account of my experience in learning to develop in the .NET environment
BindingSource, Transaction Sandboxes, and Pre vs. Post Add Modalities
13 Mar 2006 by
Marc Clifton
An investigation into different data entry modalities and the need for a transaction sandbox.
TableDataSource - Binding DataTable to Rich Data Controls
20 Jun 2007 by
brtnik
Binding DataTable to Rich Data Controls
SharePoint 2007 Flash Animation Web Part
11 Jun 2007 by
Mahdi Abdulhamid
SharePoint 2007 Flash Animation Web Part
WatiN Test Recorder
14 Jun 2007 by
Daaron
Automate web test recording into C#, VB.NET and PHP
Session Vizualizer for Visual Studio 2005
29 Nov 2008 by
Radu Chirila
Debug tool for analyzing Session content in web applications.
Extension Methods Exemplified: Sorting Index-based Generic Lists
23 Aug 2008 by
Björn Friedrich
This article shows how extension methods can be used, e.g., for sorting index-based generic lists.
Parsing XSD Schema with SOM
13 Oct 2008 by
CodingBruce
Pull metadata from a schema or generate XML mappers
Share User Settings Between Applications
17 Dec 2008 by
#realJSOP
A not-so-dotNet way to allow multiple programs to share a single settings file
Creating the Microsoft Outlook Appointment View in WPF - Part 3
21 Apr 2009 by
Richard Gavel
Part 3 of a series describing the creation of a WPF based appointment control with the Outlook look and feel.
WWW DSL using Irony - Part 1
1 Jun 2009 by
Polanek
A Domain Specific Language for WWW operations created with Irony.
Microsoft Windows Workflow Foundation
31 Aug 2009 by
logicchild
An artilce that explains how to call external data and methods.
Programmer's Guide to Starting a Software Company and Building an Enterprise Application - Article 4
27 Jul 2009 by
Paul Rony
Programmer's Guide to Starting a Software Company and Building an Enterprise Application
Wrapper Pattern for Silverlight and WPF
14 Feb 2010 by
Nicolas Dorier
A design pattern to easily bind or animate properties that do not exist on an element, and which works in both Silverlight and WPF
Dynamic DeepZoom ASP.NET User Control using Seadragon
19 May 2010 by
Lang Deng
A deepzoom user control doesn't need to generate deepzoom image files
Genuilder Extensibility
13 Nov 2011 by
Nicolas Dorier
Generate your own code during compilation without MSBuild knowledge
Embedded Controls in HMIs
10 Nov 2017 by
knockNrod
Creating Embedded Controls for WonderWare InTouch and WinCC
Applying Data Templates Dynamically by Type in WP7
19 Oct 2010 by
Florin Badea
This article presents a way to apply data templates dynamically by type in the Windows Phone 7 platform
Add Aspects to Object Using Dynamic Decorator
29 Sep 2010 by
Gary H Guo
Discuss how to add aspects to object at runtime and enhance them using Dynamic Decorator
DynamicObjects – Duck-Typing in .NET
4 Nov 2010 by
Paulo Zemek
Using structural-typing and duck-typing in .NET via interfaces
Generic WPF/Silverlight Value Converter
24 Nov 2011 by
Clifford Nelson
A generic WPF/Silverlight value converter.
Running Any Command Line exe Remotely Using the Process Class
23 Dec 2011 by
Dan Randolph
Builds on the existing RunRemote project to run commands on a remote server.
Native under Managed
26 Jan 2012 by
paladin_t
A guide about how to mix native and managed code in one solution
Time Moving Average
21 Jan 2013 by
kosmoh
An introduction to a special type of Moving average, which considers not the last N events, but the last events that happened in the given time interval.
Different Ways to Access Excel 2003 Workbooks using C#
21 Feb 2012 by
Christian Leutloff
Comparison of the Excel Object Library and the native C# library NPOI to extract information from .xls files.
Unit test and the man in the middle
22 May 2012 by
Nicolas Dorier
How to unit test network resources access : The hacker way.
Using FluentMigrator with MSBuild
12 Jun 2012 by
Miroslav Popovic
MSBuild database migrations/upgrades with backup and restore functionality
How to Create a Spam Filter or Automatic Category Sort Algorithm with Your Mail Application
29 Jul 2012 by
Higty
This article describes automatic category filters in mail applications.
ASPxGridView master-detail data presentation with context menus
24 Oct 2012 by
Mario Majčica
A real-life detailed example of usage of DevExpress ASPxGridView control.
Writing DirectShow Demultiplexors in C#. Part 1 - Windows Media Splitter example.
7 Oct 2012 by
Maxim Kartavenkov
Article describes basic task which are requre to solve for developing your own DirectShow Splitter filters.
UltraDynamo (Part 1) - It All Starts Here!
14 Jan 2013 by
DaveAuld
In this section, we look at the basics to get going.
UltraDynamo (Part 5) - Building, Code Signing and Packaging
14 Jan 2013 by
DaveAuld
In this section, we will take a look at what is required to build, sign and package the application.
AvalonDock [2.0] Tutorial Part 4 - Integrating AvalonEdit Options
31 Jan 2014 by
Dirk Bahle
Integrate AvalonEdit with text editing options into AvalonDock [2.0]
CTM - Clone To Modify Model
14 May 2013 by
Paulo Zemek
Create data structures that implement the right Clone To Modify Pattern the easy way.
Edumatter-MT
17 Feb 2015 by
DrABELL
5-in-1 educational software package for Tablet PC/Win8: Fraction Calculator, Prime Factoring, Linear, Quadratic and System of Equation solvers (AIC-2013)
Modeling the Biochemical System Using VB
6 Oct 2013 by
Mr. xieguigang 谢桂纲
Mathematical method of S-system equation to simulate a biochemical network system
Automating Semantic Mapping of a Document With Natural Language Processing
13 Aug 2014 by
Marc Clifton
Using AlchemyAPI, we create visualizations of keyword and sentence relationships so the user can extract meaningful concepts quickly and efficiently.
Trees - Part I
16 Aug 2014 by
dietmar schoder
An introduction to trees: generating and drawing.
.NET Web API 2.0 Service with a Java Client
9 Oct 2014 by
Louie Bacaj
Web API was introduced and was recently streamlined into Web API 2.0. This framework is heaven for C#/.NET services developers. It allows you to get a RESTful API in .NET up and running in less than an hour. As you'll see it's also just as easy to consume that API in another programming language.
Display HTML in WPF and CefSharp Tutorial Part 2
9 Apr 2015 by
Dirk Bahle, Alex Maitland
How to implement a ResourceHandler in CefSharp to display custom HTML in WPF
OWASP #6 Preventing Sensitive Data Exposure in ASP.NET – Part 1
16 Feb 2016 by
Max R McCarty
OWASP's #6 most vulnerable security risk has to do with keeping secrets secret.
C# Gets Pattern Matching, Disjoint Unions, Tuples and Ranges
8 Mar 2016 by
Qwertie
Well, not literally. Enhanced C# supports pattern matching, ADTs, and tuples, so Plain C# gets all that by transitivity.
VisualBasic Machine Learning, Step 1: The Q-Learning
28 Mar 2016 by
Mr. xieguigang 谢桂纲
machine playing snake game
Tool Window Support for LINQ and Lambda, PerfTip and Diagnostics Tool Window in Visual Studio 2015
14 Jun 2016 by
Akhil Mittal
This article will cover other debugging improvements of VisualStudio 2015 like the tool window support for LINQ and Lambda expressions, the newperftips, and the new diagnostic tool window.
Angular2 & WebApi (SPA) for Enterprise App - Part 7 - Manage Application Lifecycle
29 May 2017 by
tranthanhtu.vn
In this article, We will learn why do we need to manage the stages of our application.
A Walkthrough to Implement 2048 Game
4 Mar 2017 by
Robert Vandenberg Huang
An introduction to make a simple 2048 console application in C#
Magic Blocks (game tutorial)
18 Aug 2017 by
VisualMonsters
Magic blocks -Simple logical game tutorial
Generate C# Client API for ASP.NET Core Web API
11 Feb 2020 by
Zijian
Code First approach for generating client APIs for ASP.NET Core Web API, in C# and in TypeScript for jQuery, Aurelia, Axios and Angular 2+.
Extending Visual Studio to Provide a Colorful Language Editor
20 May 2018 by
Eric Lynch
In this article, we explore the implementation of a Visual Studio editor that allows editing of a fictitious "Colorful" language. The editor minimally implements both syntax classification / coloring and IntelliSense completion.
PDF417 Barcode Decoder .NET Class Library and Two Demo Apps
2 May 2019 by
Uzi Granot
The PDF417 barcode decoder class library allows you to extract PDF417 barcode information from image files. The library is written in C# for the .NET framework. The two demo projects allows you to explore the library and read PDF417 barcodes.
WiFi Password Recovery and Management Tool
27 Sep 2019 by
Mohamed Kalmoua
In this article, I will discuss a WiFi password recovery and management tool that I created in WPF using Visual Studio 2019.
Inside Out C# Development using Visual Studio Code
2 Mar 2020 by
Sem Shekhovtsov
What if one day you felt that ReSharper autocomplete, intellisense, inbuilt debugger, and other modern programming enhancements are making development boring, too fast so that the process becomes unattractive.
Easy Set Up of .NET Core on Raspberry Pi and Remote Debugging with VS Code
25 May 2020 by
Jonathan Nethercott
Automated Raspberry Pi Setup for .NET Core development and remote debugging using Visual Studio Code
Castle Dynamic Proxy Interceptors to Track Model Changes and Trigger Rules
25 Oct 2020 by
Ev Uklad
Add the ability to track changes in a model class; use a proxy interceptor to execute a rule attached to a model property
Benchmarking .NET Core SIMD Performance vs. Intel ISPC
11 Jan 2018 by
Allister Beharry
.NET SIMD programs using the Vector types show performance comparable to Intel ISPC and open source C++ SIMD libraries while satisfying the same goal of SIMD developer productivity in a high-level language.
Working with CLR Objects in SQL Server 2005 or Above Part 2
2 Aug 2009 by
Abhishek Sur
Gives an introduction of how to create SQL CLR managed objects in SQL server.
Fun With State Machines: Incrementally Parsing Numbers Using Hacked Regex
2 Jan 2021 by
honey the codewitch
Hoodwink your computer into doing your work for you using regular expressions
Quick and Simple WPF Month-view Calendar - Updated
21 Aug 2009 by
kirkaiya
A very simple, XAML-based month-view calendar that shows appointments, exposes events, and allows dragging appointments in the current month.
Excelsior! Building Applications Without a Safety Net - Part 0
11 May 2021 by
Pete O'Hanlon
Introduction to a series of articles where we build an application showing the entire thought process when writing it
Multiselect Combobox in WPF
26 May 2021 by
Nilay M Joshi
Multiselect Combobox - Custom control for WPF
Real-time Web Updates from Your PostgreSQL Database
4 Aug 2021 by
dsuryd
Combine PostgreSQL logical replication feature with dotNetify to broadcast data changes to your website in real-time
Authentication and Authorization in ASP.NET Core 2.0 using Azure Active Directory and OpenID Connect
1 Aug 2018 by
Habibur Rony
This article mainly covers how to setup and configure Azure AD tenant and integrating Azure AD into ASP.NET Core 2.0 web app for authentication and role based authorization.
Thread Apartment Safe Open/Save File Dialogs for C#
24 Nov 2014 by
Christian Kleinheinz
Using the .NET OpenFileDialog and SaveFileDialog for an application in multithreaded apartment mode (MTA)
Simple WPF Bar Graph Control
1 Apr 2016 by
Clifford Nelson
This article presents a simple bar graph using an ItemsControl with a custom DataTemplate
MvvmCross for WPF: A Basic Primer
7 Jul 2020 by
Meshack Musundi
An overview of MvvmCross for WPF application development
Custom Winamp-Style TrackBar (Slider)
2 Jun 2015 by
Johnny J.
A custom drawn TrackBar that looks like the one in the classic Winamp skin
Entity Framework Dynamic Report
5 Sep 2015 by
Maxim Kurayan
EF Dynamic Report is a small open source project which allows you to use Entity Framework mapping between types and tables as a dynamic report data source
How To Disable FlashPlayer (AxShockwaveFlash) Right-click ContextMenu
5 Sep 2008 by
IncureForce
How to disable FlashPlayer (AxShockwaveFlash) right-click ContextMenu
SPA^2 using ASP.Net Core 1.1 + Angular 2.4 - part 6
21 Mar 2017 by
Robert_Dyball
How to use NSwag to create Typescript data models and data services for Angular 2 and to generate Swagger Web API documentation.
Learn Angular Tutorial - Part 2
21 Sep 2017 by
Shivprasad koirala
Create your first Angular project and understand various concepts like Components and modules
Theming and Localization Functionality for Multiplatform Avalonia UI Framework
18 Nov 2021 by
Nick Polyak
New simple and flexible package for Theming and Localizing multiplatform Avalonia applications is described here with samples
Andrew's CodeProject Screen Saver
20 May 2002 by
Andrew Peace
(Yet) another screen saver for the Code Project competition, with code in C# and (coming soon) some details about how certain aspects of the code involved work.
Issues with UdpClient.Receive
9 Mar 2002 by
Christian Rodemeyer
Strange errors I experienced which led me to a major bug in the UdpClient implementation
An instrumented synchronous/asynchronous event manager utilizing EventHandler and Reflection
16 Oct 2002 by
Marc Clifton
Implements an instrumented event manager which can be used to invoke event sinks both synchronously and asynchronously. The event sink can be declared using either the System.EventHandler delegate or by reflection.
Building a BallonToolTip provider in C#
3 Mar 2004 by
wilsone8
Shows how to create a ToolTip provider that supports Balloon Tooltips, including issues related to creating extender properties and using the NativeWindow class.
Using Amazon FPS (WinForms, ASP.NET, and C#)
21 Dec 2007 by
Keng_Mycos
Using Amazon FPS as an alternate to Paypal and Google Checkout.
Thread Synchronization Constructs Used in the CLR
4 Jun 2009 by
logicchild
This article is meant to sort through and explain some of the complexities in threading.
GALib
24 Jan 2010 by
Jeroen De Dauw
A small C# library that provides scaffolding for genetic algorithm based functionality.
Show thumbnails of XPS documents
26 Jan 2010 by
Pravesh Soni
How to show thumbnails of XPS documents.
Fast Updating of Treeview Control With a Database in VB.NET
6 Apr 2010 by
seejay1120
A Fast Way to Update Treeview Nodes Using a Database as a Source
Silverlight Binary Serialization using Protobuf-net
29 Apr 2010 by
Sangsu Park 99
How to serialize a pure .NET object class to a fast binary data
General DynamicObject Proxy and Fast Reflection Proxy
15 Sep 2010 by
Yury Goltsman
Extending functionality by wrapping entity using DynamicObject. Improving performance of Reflection by using cache and expressions
Project Silk Navigation for ASP.NET Web Forms
13 Dec 2012 by
GrahamMendick
A conversion of Project Silk to ASP.NET Web Forms using the Navigation for ASP.NET Web Forms codeplex project, concentrating on the navigational aspects
Static and Type markup extensions for Silverlight 5 and WPF
22 May 2012 by
Henrik Jonsson
An extended Static markup extension implementation for Silverlight 5 and WPF supporting invoking static methods with arguments, and a Silverlight Type markup extension implementation.
ASP.NET Automatic Object to UI Binding
25 Apr 2012 by
Razi Syed
Easily bind a class to .NET data controls like GridView, FormView, etc., and get an updated object or list back in the code-behind effortlessly.
FastCGI .NET and ASP.NET self-hosting
1 Oct 2012 by
Luigi Grilli
C# fastcgi protocol implementation. A good example on how to self-host your web application without the need of iis or mono, for example using Nginx on both Windows and Linux
VS2008 Panel
19 Jun 2012 by
Burak Ozdiken
How to make a custom panel control like in Visual Studio 2008 for a Windows Forms Application using the .NET Framework.
Add Most Recently Used Files (MRU) List to Windows Applications
26 Nov 2012 by
Adib Saad
A .NET4.0 alternative for "Add Most Recently Used Files (MRU) List to Windows Applications"
Augmented reality - XNA Models
23 Aug 2012 by
Harald Heide Gundersen
Geocoordinate positioned Xna model viewable thru Photocamera
Moq - Mock Database
18 Oct 2012 by
Indranil Pal
Mocking database in Unit Tests using Moq.”.
Line Fitting in Images Using Orthogonal Linear Regression
12 Apr 2013 by
Jonathan Nethercott
Describes an algorithm for calculating the equation of a line in an image using orthogonal linear regression.
Capture object state with visualizers
1 May 2013 by
Praveen P R
Visualizer to capture object state.
Resolving an Unreferenced Partial Type Name using Fusion
16 Sep 2020 by
John B Oliver
Resolve unreferenced type in .NET app using partial type name from GAC
A generic equality comparer library which will work across types
14 Nov 2013 by
shijo joseph
An extension methods library which could do the equality comparison operations easily
How to Use enum with Entity Framework 5 ?
26 Nov 2013 by
Sampath Lokuge
This blog post shows how to use enum with Entity Framework 5.
Multithreading with Netduino and .NET Microframework
11 Jul 2014 by
Georgi Hadzhigeorgiev
.NET Microframework makes multithreading with Netduino easy job. Let’s have a look how.
The Kitchen Sink
17 Dec 2014 by
Marc Clifton
APOD, Horoscopes, Weather Radar, Windyty, Tech Feeds, Chromium, NOAA Weather
ASP.NET Webform Generator
5 Apr 2015 by
J.L. MacDonald
When supplied with a connection string and table name, this tool will read the field data types and create asp controls for you to copy and paste in your own project.
Learning AngularJs - Episode 3 of 15
9 May 2015 by
Abhishek Maitrey
Part 3 of learning AngularJS
WPF and IronPython Business Rules - Part 2
9 Jun 2015 by
beep
A full WPF sample application demonstrating IronPython business rules
How to run .Net Micro Framework 4.4 on STM32F4Discovery
6 Jun 2016 by
Alexandr Surkov
How to build and run .Net Micro Framework 4.4 on STM32F4Discovery board.
Cool Privilege Control System Part 2 -- asp.net MVC with WCF
29 Feb 2016 by
wells cheung
Privilege Control System based on MVC and WCF.
Dynamic Modules with Prism and the Modern UI for WPF Toolkit
23 Mar 2016 by
Rubén Hinojosa Chapel
Prototype for a plugin architecture based on the Prism Library and the Modern UI for WPF (MUI) toolkit
Semi-Prime Ordered Sequences (Part 2)
31 May 2016 by
William Hey
Semi-Prime Ordered Sequences (Part 2) is the follow-on to “Exploring Computational Number Theory (Part 1)” and describes a process for ordering the semi-prime base sequences.
How to scroll and view millions of records
9 Jul 2016 by
DataBytzAI
A simple and useful pattern when you need to allow user access to large volumes of data
C# Lectures - Lecture 11: LINQ to 0bjects Part 2. Nondeferred Operators
13 Sep 2016 by
Sergey Kizyan
Next article from the C# series. Continuation about LINQ operators for LINQ to objects
Classificiation Using Logistic Regression in Visual Basic
19 Dec 2016 by
petrostherock
Machine Learning. What languages come to mind? R? Python? Matlab? Bet you didn't think Visual Basic.
Using Unity Framework in ASP.NET MVC 5
28 Dec 2016 by
Snesh Prajapati
In this article we will learn how to use Unity framework with ASP.NET MVC 5 application to register and resolve dependent objects.
HoloLens first impression
4 Jan 2017 by
Sergey Kizyan
My first article about HoloLens from user perspective and little bit from development environmental point of view.
Simple POCO Mapper for EPPlus
26 Aug 2017 by
Erik Drent
Simple POCO mapper for EPPlus
Introducing IoCy - Simple and Powerful IoC Container
13 May 2018 by
Nick Polyak
New simple but powerful IoC container
Music Notation in Blazor - Part I
1 Aug 2018 by
Ajcek84
Client-side music notation rendering in Blazor
Require Confirmed Email in ASP.NET Core 2.2 - Part 1
22 Dec 2018 by
Ken Haggerty
Scaffold and modify Identity in the new ASP.NET Core 2.2 Razor pages template
PocoClassGenerator: RDBMS All Table/View Generate Dapper POCO Class Code
30 Apr 2019 by
ITWei
PocoClassGenerator RDBMS All Table/View Generate Dapper POCO Class Code
Image Classification Using Neural Networks in .NET
26 Jun 2019 by
hemanthk119
Image Classification implementation using Deep Belief Networks and Convolutional Neural Networks in .NET
Entity Framework with Audit Tables
10 Sep 2019 by
Alexandros Pappas
This project describes how to use Entity Framework with update triggers and audit tables.
Developing .NET Applications for the Raspberry Pi: Part 2
25 May 2020 by
Jonathan Nethercott
A framework for developing Raspberry Pi .NET applications including unit tests, mocking and dependency injection
Thread Safe Quantized Temporal Frame Ring Buffer
6 Sep 2020 by
Marc Clifton
Ring buffer to track count of events within a temporal frame
Adding $type to System.Text.Json Serialization like in Newtonsoft for Dynamic Object Properties
5 Nov 2020 by
Ev Uklad
This article describes a technique to serialize models containing dynamic types with System.Text.Json JsonSerializer, that doesn’t support $type.
jQuery DataTable Integration - Dynamic Columns and Records
16 Aug 2018 by
Proneetkumar Pradeep Ray
JQuery Datatable (Dynamic columns) populate after Ajax JSON response via server side processing - Using EF Raw SQL query
Client and Server-Side Data Filtering, Sorting, and Pagination with Angular NgExTable
20 Dec 2020 by
Shenwei Liu
A custom and configurable Angular data grid tool and demo application presenting both client and server-side data filtering, sorting, and pagination (updated to Angular 11)
RedisProvider for .NET
12 Jun 2020 by
KimJohnson
.NET Redis container and strongly typed data objects
Adaptive Hierarchical Knowledge Management - Part I
1 Apr 2021 by
Marc Clifton
What I'm embarking on is writing an actual product that performs the task of what is called "Knowledge Management."
Entity Factory - Get Your ORM-less Freak On!
4 Nov 2021 by
#realJSOP
A tool to generate model and viewmodel classes directly from your selected database
Sudoku Solver using C# Windows Application
25 Sep 2021 by
Senthil Kumeresh
An overview of how the coding is done to solve the Sudoku problem
Using Managed Extensibility Framework to Build a Modular Console Application
24 Jul 2019 by
Sau002
This article takes you through a step by step journey of building a fairly large console application which is modular and also extensible by using the principles of Managed Extensibility Framework.
Natural Language Interface to Database using SIML
14 May 2015 by
DaveMathews
Using SIML, a language designed for Digital Assistants, to create a Natural Language Interface to an SQL database.
ORM-less CRUD Operations with Audit, Authentication and Authorization
8 Feb 2022 by
Marc Clifton
Reduces number of per-table controllers, models, services, and other code you end up writing or having auto-generated!
How to do CreateFileMapping in a C++ DLL and access it in C#, VB and C++
10 Mar 2009 by
nkrscorpio
This is yet another example for memory mapped files. What is cool though is unlike other samples, I have a SetData(TCHAR* Key, TCHAR* value) / GetData(TCHAR* key) pattern here.
C# WPF listview Drag & Drop a Custom Item
26 Mar 2018 by
Massimiliano Brugnerotto
This article explains how to implement the drag & drop of a custom item within a ListView control with WPF technology.
C# MVVM Toolkit Demo
19 May 2022 by
Jo_vb.net
This article and the demo are about getting started using the MVVM Toolkit and some self-created interfaces / services for MessageBox and some dialogs.
Dynamic Language Runtime in C#/.NET
30 Jan 2022 by
Uladzislau Baryshchyk
An overview of Dynamic Language Runtime DLR in C#
Avalonia DataGrid - Advanced Features coming from NP.Avalonia.Visuals Package
15 Apr 2022 by
Nick Polyak
Explain the new code whose purpose is to add Filtering, Layout Saving/Restoring and Column Visibility functionality to Avalonia DataGrid
WPF Split Panel
8 Aug 2017 by
LostTime76
A custom panel which allows elements to be resized using splitters
The Implementation of Model Constraints in .NET
19 Mar 2002 by
Alex Mikunov
.NET Extensions that provide an infrastructure for enforcing database-like data integrity constraints
Using Nhibernate in VB.NET
7 Jan 2008 by
S.SRIVATHSAN
Implementation Nhibernate concept in VB.NET
Hacking FontDialog
23 Aug 2008 by
legcsabi
How to hide UI elements of a FontDialog (e.g., Font Size).
How to get the correct file time in C# in .NET Framework 2.0
9 Jan 2009 by
pablodg
Workaround to get the correct LocalDateTime of files no matter which date settings your computer has.
Draggable Popup Window in Silverlight 3
19 Nov 2009 by
dsmolen
Allows a user to drag a popup to any location in the Silverlight window.
Forwarding a type from one assembly to another: TypeForwardedToAttribute
23 Mar 2010 by
Ashish Kumar Mukherjee
Walkthrough: Forwarding a type from one assembly to another by using the TypeForwardedToAttribute attribute.
Load Clean HTML Fragments using jQuery and MVC
3 Dec 2010 by
Dr. Song Li
This article presents a simple method to load clean HTML fragments from the web servers using jQuery and MVC.
Search Selectable Virtual List
3 Jan 2013 by
Young Ye
This article is the part 3 of the data display Performance Optimization series. It talks about performing multiple searches against the virtual list.
Non-Stopping Upgradable Service Framework
27 Jan 2012 by
CooperWu
A framework designed for support upgrade components in service without stop running
Memory and time efficient Levenshtein algorithm
29 Jun 2012 by
Horatiu-Andrei Stoianovici
This is an alternative for "Fast, memory efficient Levenshtein algorithm"
ToolStrip with Custom ToolTip
1 May 2012 by
Ivan Ičin
Custom WinForm ToolStrip that fixes some of the ToolTip related problems and adds few related features
Basic Help on NxBRE (Rule Engine)
16 Dec 2014 by
Suvabrata Roy
Here is a help on NxBRE (Rule Engine) for basic business rules
Sound in games - Rooms
31 Jul 2012 by
Kenneth Haugland
How to calculate a reverbration time in a room
ASP.NET MVC3 Slideshow Control using jQuery and XML
11 Sep 2012 by
Bryian Tan
Article on how to create an ASP.NET MVC3 slideshow user control/partial view using jQuery and XML
Quick Retouch+
7 Oct 2012 by
Briti Sundar
This app will help users to quickly add different type of effects on a picture like sketch, oldphoto, emboss, nightvision, cartoon, oilify, etc.
Flavours (AppInnovation)
8 Nov 2012 by
Nrupal Prattipati
Starting with Recipe creation and sharing, to a full fledged Kitchen Assistant
Event Finder - Google Places Event App
25 Oct 2012 by
Simon Key
Event Finder - A WinRT app making use of the Google Places API and other data sources to display a lists of local events
Accessing Assembly Metadata with Reflection or Mono Cecil (Part 6)
2 Dec 2012 by
KenBeckett
Calculating Metrics and Searching with a CodeDOM (Part 8)
6 Mar 2013 by
KenBeckett
Calculating metrics on and searching a CodeDOM.
How to Read a PE Image's Manifest Resource using an Undocumented Internal .NET Class Method
21 Jan 2013 by
Kerem Guemruekcue
This short article shows how to use an undocumented internal class method from the System.Deployment.Application.Win32InterOp namespace to get a PE images manifest resource.
The Roads We Take
11 Feb 2013 by
SergeyAndreyev
To give users the full control over the running application. While an application is running, users can move, resize, and tune all the screen objects through which the communication with an application is going.
Procedural Content Generation Part I: Generic Asset Factory
8 Sep 2017 by
CoderGirl42
An extensible procedural generation framework
Integrate dynamic HTML pages in your Silverlight app
12 Apr 2013 by
NightWizzard
...for example a WYSIWYG HTML editor to edit or display emails...
SVN Commenter
18 Apr 2013 by
Pieter Alec Myburgh
Subversion Comment Editor
Pick Your Enumerator & Me.Understand Yield and IEnumerable (VB)
21 Apr 2013 by
Mike-MadBadger
This is an alternative for "Pick Your Enumerator & Me.Understand Yield and IEnumerable (C#)"
Keeping Sensitive Config Settings Secret with Azure Websites and GitHub
8 Jun 2013 by
Phil Lee NZ
A strategy for keeping sensitive configuration values, such as connection strings, out of your source control repository, but still available to your app both locally and in the cloud. We're looking specifically at Azure websites and GitHub.
ASP.NET SignalR Basis Step by Step (Part 2)
2 Sep 2013 by
Zhuyun Dai
Introducing Hub, scaling out and extensibility in SignalR
Violating Liskov Substitution Principle (LSP)
6 Sep 2013 by
Ryszard Dżegan
How to not damage yourself when using inheritance.
Ultra High Quality Image Rotation on a GPU
16 Sep 2013 by
Nick Kopp
Ultra high quality frequency domain image rotation on a GPU.
WorkflowChannel for Windows Azure BizTalk Service (WABS)
30 Jan 2014 by
Roman Kiss
This article describes how a Windows Azure BizTalk Service Bridge pipeline can be extended for message mediation by Workflow (VETER + WORKFLOW Pattern).
CCTreeMiner: An algorithm for Subtree Mining Problems
8 Apr 2014 by
Claude He
CCTreeMiner: An algorithm for Subtree Mining Problems
State Machine - State Pattern vs. Classic Approach
5 Aug 2014 by
Chris875
State pattern and procedural solution illustrated
iPhone like controls for .Net, Part 2: IOS switch
28 Jul 2014 by
hgbecker
Animated IOS like On/Off switch.
The List Trifecta, Part 3
12 Aug 2014 by
Qwertie
SparseAList and some AList benchmarks
SonyAPILib
6 Apr 2015 by
HKHerron
A C# API Library for Discovering, Registering and Controlling Sony devices equipped with a LAN or WiFi port.
WPF Custom Visualization Intermezzo: Resources
24 Aug 2016 by
Serge Desmedt
(Yet Another) Investigation of WPF resources
Scripted Business Rules with .NET and IronPython, Part 1
28 May 2015 by
beep
Introduction to the Aim framework for dynamic scripting
Writing a XAML application with geometry objects (shapes) for X11
12 Jun 2015 by
Steffen Ploetz
Currently none of the big Linux/Unix (X11) GUI application frameworks (GTK+, KDE) support XAML based application development. The Moonlight project (including XAML support) was abandoned on May 29, 2012. This article reviews a XAML based application with WPF geometry objects (shapes).
Getting startet with OpenGL/OpenTK in MONO/.NET for serious applications
26 Mar 2019 by
Steffen Ploetz
Check OpenGL as a basis for appealing applications, that are not necessarily games.
Create Word table using OpenXML and C# Without Automation/Interop
8 Nov 2015 by
koolprasadd
This article help you to create word table using OpenXML without interop object
MDI Case Study Purchasing - Part IV - Events
20 Nov 2015 by
stebo0728
MDI Case Study Purchasing - Part VIII - Copy & Paste
2 Dec 2015 by
stebo0728 Reactive Extensions - cold observables
27 Mar 2016 by
Kenneth Haugland
Create cold observables, intercept observables and split observable into async tasks.
modds Drag and Drop Programming for C# Sample Stock Chart (Part 2)
1 Aug 2016 by
douglas young
Drag and drop programming
UWP Alien Sokoban - Part 3
26 Oct 2016 by
Daniel Vaughan
A fun UWP implementation of the game Sokoban, demonstrating some new features of XAML and C# 6.0. Part 3
Behaviors to create double or TimeSpan Value TextBox for WPF Masked TextBox
26 Oct 2016 by
Clifford Nelson
Presents a concept for creating a masked TextBox, and has the implementation for a TimeSpan and double value
How to migrate DevExpress XAF SecuritySystemUser to PermissionPolicyUser
8 Nov 2016 by
mblataric
Instructions on how to migrate existing XAF security system to new permission policy.
Find the Pointer
14 Nov 2016 by
Peter N Robinson
Press either CTRL key to find out where the mouse pointer is...
Bootstrapper Loader for Layered Architecture
10 Nov 2017 by
David Nguyen Hung Phuong
A tiny library to load and execute bootstrapper classes in layered architecture by convention
MRU (Most Recently Used) WPF control
26 Aug 2017 by
Dirk Bahle
Implementing a WPF/MVVM Control libray (with backend) that manages a Most Recently Used list of files.
Simplest WPF Dependency Property For Beginners On 'ValidState'
22 Nov 2017 by
Graeme_Grant
This is an alternative for "Simplest WPF Dependency Property For Beginners On Background Color"
First and Extremely fast Online 2D Convex Hull Algorithm in O(Log h) per point
28 Feb 2018 by
Omar Saad (IREQ), Eric Ouellet
Ouellet Convex Hull is currently the only ‘Online’ Convex Hull in O(log h) per point, where 'Online' stands for dynamically add one point at a time. Based on our own test against many other algorithm implementations, including Chan and Voronoi/Delaunay, it appears to be the fastest one.
CSV/Excel File Parser - A Revisit
7 Apr 2018 by
#realJSOP
An example of evolving code to fit new demands
The New Era Of Clustering: CLOPE Algorithm in C#.NET
27 Apr 2018 by
Arthur V. Ratz
In this article, we will formulate and discuss CLOPE data mining clustering algorithm that allows to drastically increase the quality and efficiency of categorized data clustering and can be easily used for recommendation-specific purposes
Dynamic Highcharts – ASP.NET Core, Angular6
14 Aug 2018 by
Shashangka Shekhar
In this post, we are going to implement dynamic highchart with Angular6 and ASP.NET Core.
Orbital Mechanics Introduction: Part 2
16 Jan 2019 by
charles922
Introduction to Orbital Mechanics - 2 Body Problem WPF
Xamarin Forms - Theming Made Simple
21 Feb 2019 by
Chandru BK
This article will assume that you have basic knowledge of C#, XAML Styles and Xamarin Forms and shows how to implement theming using simple styles.
HTTP Live Streaming (HLS-VOD)
22 Apr 2019 by
Shashangka Shekhar
In this post, we are going to create a video server that can serve videos with multiple bit-rate also known as adaptive bit-rate streaming.
UpdaterApp - a Library for Easy Update
26 Sep 2019 by
William Costa Rodrigues
This article explains an easy method to download and update your WinForms application
How to Implement Full-Text Search in .NET Application with Elasticsearch
6 May 2020 by
Daniele Fontani
Learn how to read and write documents with custom full-text queries in C# using NEST
SpaceVIL Framework. Cross-Platform GUI with .NET & JVM
30 Jan 2020 by
Roman Sedaikin
SpaceVIL is a cross-platform and multilingual framework for creating GUI client applications for .NET Framework, .NET Core and JVM. This article discusses the SpaceVIL framework, its capabilities and a brief story of its creation.
GLR Parsing in C#: How to Use The Most Powerful Parsing Algorithm Known
18 Feb 2020 by
honey the codewitch
A crash course in GLR parsing which can be used to parse highly ambiguous grammars
P/Invoke Jujitsu: A Data Kata
11 Jul 2020 by
honey the codewitch
Exploit the memory layout of your data to make your P/Invoke code more accessible and maintainable
Matrix Library in C
24 Oct 2020 by
Roozbeh Abolpour
A matrix library in the C language that is useful for primary platforms and large data
Contextual Data Explorer
1 Mar 2018 by
Marc Clifton
One approach to creating the bidirectional relationship between context and data -- a declarative strongly typed relational contextual system using C#
The Clifton Method - Part II
25 Aug 2016 by
Marc Clifton
Service Manager - Instantiation by Interface Specification
Public API Events and Breaking Changes
14 Nov 2020 by
Paulo Zemek
Understanding breaking changes caused by event changes and how to avoid them.
Global Hotkeys within Desktop Applications
29 Dec 2018 by
Kfir Eichenblat
Learn how to create Global Hotkeys properly in a C# desktop application (e.g. Windows Forms or WPF)
Centralizing WCF Client Configuration in a Class Libary
3 Dec 2015 by
Nejimon CR
This article describes how to put your WCF client configuration in a class library's config file instead of client application's config file
.NET settings files in class library projects
26 Aug 2011 by
Jecho Jekov
How to use .NET settings files in class library projects.
Ms. Wordbler - A Cute Little Warbler!
11 Apr 2019 by
Mehedi Shams
Word-making game!
Tropical Tunes. Scratch Versus C#.
8 Feb 2021 by
Uzi Granot
If you are a programmer that tried to introduce a kid to programming with Scratch, this article is for you. Comparing a simple game between Scratch and C#.
Cinchoo NACHA
17 Feb 2017 by
Cinchoo
Simple NACHA driver for .NET
Data Scraping from Image using Tesseract
31 Mar 2018 by
Eric M. H. Goh
Scrape data from image using Tesseract OCR engine
Gradient Color Picker - Revised Again
14 Jun 2021 by
gggustafson
This article revises an earlier revision of the Gradient Color Picker (V2). The incentive for the revision was a reader request for a larger number of initial color choices.
Parse, understand and demystify Enhanced Meta Files (EMF) with C#
27 Mar 2019 by
Steffen Ploetz
A simple approach to inspect Enhanced Meta File (EMF) content and find/fix inconsistencies. Easy to adopt to your specific purpose.
SortedBucketCollection: A memory efficient SortedList accepting multiple items with the same key
12 Nov 2021 by
Peter Huber SG
A detailed guide how to write your own collection.
UltraDynamo (Part 4) - Graphics and Fonts
14 Jan 2013 by
DaveAuld
In this section, we will take a look at some of the graphic and font handling routines.
Writing a XAML ribbon application for X11
29 ribbon application with the Roma Widget Set (Xrw) in C#
ASP.NET Gridview Editable in Web Forms using Bootstrap 4
30 Jul 2019 by
Don Hoang
This post describes implementing ASP.NET Editable Gridview using Bootstrap 4
Sponge Constructions and SHA-3 Hashing Functions: A C# Implementation
29 Jan 2018 by
phil.o
C# implementation of sponge construction and SHA-3 hashing operations
Importing Excel Data to a Generic List Using Open XML SDK and Object Model Mapping
5 Jun 2014 by
Shenwei Liu
C# class that populates a generic list with data retrieved from Excel data file
UT2003 Gameserver Status
16 Oct 2002 by
Rüpel
Getting the current Status of a UT2003 Gameserver via UDP Queries
Serialization for Rapid Application Development: A Better Approach
25 Apr 2008 by
Daniel Gidman
Serialize and Deserialize your objects with ease and simplicity
Using Serialization to Produce RSS Feeds from C# Classes
2 Sep 2008 by
Derek Burnett
Creating classes that model an RSS, in C#
EHFileDiff - File Compare Utility
2 Sep 2009 by
Eric Haddan
My entry to the Code Lean and Mean File Comparison Contest..
How to compile and use Xapian on Windows with C#
9 Apr 2010 by
Sean Goodpasture
A look at how to compile and use the Xapian search technology on Windows, and its pitfalls.
A Better Visual Studio 2008/2010 Development Server Test Fixture
2 Oct 2010 by
Sky Sanders
Leverage the built-in development web server in testing and other scenarios.
Silverlight 4 OData Paging with RX Extensions
29 May 2010 by
defwebserver
An example of Silverlight 4 OData Paging with RX Extensions.
A SOA Approach to Dynamic DOCX-PDF Report Generation - Part 1
23 Aug 2010 by
Erion Pici
Generating docx reports in a client-server architecture, without using MS Office
Back to Basics – Get Client Computer Name in ASP.NET
1 Sep 2010 by
Gil Fink
How to get the client's computer name using ASP.NET
Exception logging using Elmah - Error Logging Modules and Handlers for ASP.NET
29 Apr 2011 by
Mohammad A Rahman
Exception logging using Elmah - Error Logging Modules and Handlers for ASP.NET
MVC PLUS for MVC.NET 3.00
8 Aug 2012 by
Brian Samiee
WebLights Component Library
WPF/Silverlight Binding Using Flags Class
8 Jul 2011 by
Clifford Nelson
A special class is needed to support binding a set of flags to a View.
Renaming User Settings Properties between Software Versions
30 Aug 2011 by
jsharrison
How to migrate User Settings properties between software versions after you've renamed them
SSRS Multi-Data Source DPE (Data Processing Extension)
23 Oct 2011 by
jkrebsbach
A way to combine data from two different sources into one datasource for SSRS reporting
Make your Page Social with the Open Graph Protocol
28 Oct 2011 by
Yvan Rodrigues
The Open Graph protocol specifies additional meta tags that can be added to the page to supplement social networking sites with more information about your page.
DevForce Code First Walkthrough: From New Project to Running
2 Dec 2011 by
johnlantz
This tutorial shows how to build a simple WPF application using Code First in DevForce.
TaskbarNotifiers, Resizable Skinned MSN Messenger-Like Popups with Video
8 Jan 2012 by
William SerGio
Resizable Skins Made from Web Pages with Video
Native (Delphi) callbacks in .NET (C#) COM assembly
26 Apr 2012 by
Issam Ali
How to pass native (Delphi) callback pointer to a .net COM assembly
Orchestration of asynchronous communication
31 May 2012 by
Jani Giannoudis
How to centralize and unify asynchronous execution of actions and functions.
Writeable Application Scope Settings
18 Jun 2012 by
Niel M.Thomas
Create and use writeable Application Scope settings.
CLRBinding - Properties Binding
23 Jun 2012 by
igkutikov
Binding Properties of non GUI elements that still implement INotify
Validate AJAX Combobox in ASP.NET using JavaScript
3 Sep 2012 by
Adittya Gupta
Validating combobox at client side and displaying item list properly.
Using Events: Filerenamer II Project
24 Feb 2019 by
chuck in st paul
This is a utility program for bulk/batch renaming of files that demonstrates using and creating events
QuickAccent - A Tool for Accents and Symbols
29 Oct 2014 by
Dave Kerr
Use QuickAccent to quickly copy accents and symbols to your clipboard. Also read the article to find out about the essentials when writing System Tray based applications
UltraDynamo (Part 3) - Real Time Trends
14 Jan 2013 by
DaveAuld
A look at achieving real time trends in UltraDynamo
All about XmlSerializer Performance and Sgen
21 Jan 2013 by
Amit Bezalel
Improving XmlSerialization performance.
OSGi.NET - An OSGi-based modularization framework for .NET
25 Mar 2013 by
Sam Ma, Xi'an
This article describes the usage of a modularization framework called OSGi.NET.
Simple Metro Style Application with WCF service and MS Excel Database
16 Apr 2013 by
Muhammed Anseer K K
Creating a metro style application with WCF
Volatile As It Should Be
22 Apr 2013 by
Paulo Zemek
This article presents a class that allows volatile reads and writes as they are expected to work.
An Experiment in HTML5 Gaming
20 May 2013 by
Jon Honess
Using Windows Azure to build an online board game.
Using Azure Lease Blob
9 Jun 2013 by
Roman Kiss
This article describes how the Azure Lease Blob can help the composition of the business model during the runtime in the distributed event-driven pub/sub architecture.
Introducing BuildButtons
24 Jun 2013 by
Dave Kerr
In this article, we'll look at how you can add social networking buttons to your website to connect it to other networks. We'll use BuildButtons for the heavy lifting.
LINQ to Family Tree (Prolog Style)
31 Jul 2013 by
Hisham Abdullah Bin Ateya
Querying a family tree in LINQ fashion.
Semaphon™ semantic phone number-to-text converter
8 Oct 2015 by
DrABELL
App implements bi-directional semantic phone number-to-text converter, extended with novel Lottery+Quiz engine
A Windows Service for moving and renaming scanned documents depending on file contents.
14 Aug 2013 by
Martin-Hallonqvist
This article describes how I wrote a small Windows service for handling the task of sorting and renaming scanned (and run throgh OCR) documents depending on contents.
Using JayData to Consume the Visual Studio LightSwitch OData Business Layer in a AngularJs CRUD Application
26 Oct 2013 by
defwebserver
You can consume your backend OData Visual Studio LightSwitch services in AngularJs
Creating Test Objects With FakeModel
17 Dec 2013 by
Member 9913858
An introduction to using FakeModel to create test aata for you.
Basic WPF Way to Implement and Include Animation in XAML
5 May 2014 by
Gerald Gomes
This article will make an attempt to describe a basic way to start implementing animation in WPF.
Non Blocking C# Task Cancelling
13 May 2014 by
Michael Adaixo
Non blocking C# task cancelling
Building and Running Embedded Linux .NET Applications from First Principles
23 Feb 2016 by
Alex J Lennon
.NET applications on Yocto/OpenEmbedded Linux
Writing a XAML dialog application for X11
10 dialog application with the Roma Widget Set (Xrw) in C#
Getting Mono Running on a Raspberry Pi Using Yocto
9 Nov 2014 by
Richard Dunkley
Demonstrates how to use the Yocto Project to get a custom Linux operating system with Mono up and running on the Raspberry Pi development board.
Creating SharePoint Word Documents with AngularJS using LightSwitch
19 Jan 2015 by
defwebserver
You can implement SharePoint documents in your AngularJS applications much easier when you create your code in a Visual Studio LightSwitch Cloud Business app..
CodeProject New Questions Tracker - An Application to Keep Track of CodeProject's Recent Questions using the API
27 Sep 2015 by
Thomas Daniels
Application that displays a notification when a new question is posted on CodeProject
MultiBinding for WPF Command Combining
16 May 2015 by
Leonid Osmolovski
Techniques for joint execution of a group of commands after single user interface action.
Geolocalize a Device and Store Coordinates on Webserver
19 Jun 2015 by
Emiliano Musso
Geolocalize a device and store coordinates on webserver
Language Madness Naming Time Elements
6 Nov 2015 by
Jorge Gomez Prada
Time is simple but programming time is cumbersome. Programmers still have serious difficulties coding with time values.
MDI Case Study Purchasing - Part VII - Document Form II
27 Nov 2015 by
stebo0728
MDI Case Study Purchasing - Part X - Smart Saving
14 Dec 2015 by
stebo0728
Learn Windows Workflow Foundation 4.5 through Unit Testing: CodeActivity
20 Mar 2016 by
Zijian
Workflow CodeActivity
Creating AutoComplete HTML Tags in C#
1 May 2016 by
Pritam Zope
In this article we will automatically close the HTML tags when starting tag is typed in RichTextBox in C#
Yet Another Duplicate File Detector: MVVM Pattern
11 Jun 2016 by
kaviteshsingh
A simple utility to find duplicate files in a folder (including sub-directories).
Creating detail grid template at runtime using devexpress gridview
28 Aug 2016 by
Ali Adly
A simple example that shows how to create detail grid template at runtime using ASPxGridView
Generate a WPF Frontend from a Console Application
25 Oct 2016 by
Zebedee Mason
How to structure a command line application so that as it is modified, the GUI automatically changes.
21st Card Magic in C#.NET
10 Nov 2016 by
Mehedi Shams
Coding a simple magic with cards!
Data quality for developers
21 Dec 2016 by
DataBytzAI
A quick look at data quality, and using expression trees to automate QA data testing.
Face Detection and Recognition with Azure Face API and C#
21 May 2017 by
Emiliano Musso
In the present article, we'll analyze some functionalities offered by Microsoft Azure Cognitive Services, and in particular that part of Cognitive Services dedicated to facial recognition (Face API). At the end of the article, the reader will be able to develop a simple C# application to detect face
Browser Update for WebBrowser control in VB.NET
29 May 2017 by
Kourosh K Tari
In this article I will show you how to update WebBrowser control to use the latest installed browser on the host machine.
Developing Non-ASP.NET Websites running under IIS
9 Jul 2017 by
Marc Clifton
Discovering some of the nuances of IIS and looking under the hood at how Katana/Owin does its initialization.
Sequence Detection With a Finite-State Machine
1 Dec 2017 by
Dmitrii Nemtsov
A way to build a finite-state machine identifying predefined sequences in a stream of characters.
IoT Starter Raspberry Pi Lirc
15 Feb 2018 by
Jose Motta
IoT.Starter.Pi.Thing powered by Linux Infrared Remote Control
First Steps to Make NoesisGUI, a WPF Competable Framework, Running on Linux with C#
18 Mar 2018 by
Steffen Ploetz
How to run the -IntegrationSample- of the incredible feature-rich NoesisGUI, that might be the best WPF competitor, on Linux using MonoDevelop and C#.
Writing Distributable .NET Application with x2net
5 Apr 2018 by
Jay Kang
Introduction to a new approach to distribution
Multiplatform Radar Chart
23 Jul 2018 by
Ajcek84
Implementation of radar chart for various .NET platforms
WPF Drag and Drop using NP.Visuals Library
9 Sep 2018 by
Nick Polyak
Drag and drop using NP.Visuals package
oops - A Cross-Platform, General Purpose Undo/Redo Framework
8 Oct 2018 by
outbred
Design, implementation, and usage of the oops framework
Visual Studio Loader With Arguments
24 Oct 2018 by
Mark Kruger
Visual Studio loader with arguments
Writing to a Slack Channel - .NET Core Edition
7 Jan 2019 by
Ryan Peden
Writing to a Slack Channel - .NET Core Edition
Mimick - A Fody Aspect-Oriented Weaving Framework
9 Jun 2020 by
Chris Copeland
A managed library for automated dependency injection, contract validation, and custom aspect-oriented decorator implementations
A Custom WPF Slider Button
24 Apr 2019 by
Leif Simon Goodwin
This article describes a simple slider button using dependency properties and a template.
Soma Cube Solver
23 Mar 2019 by
charles922
WPF 3D Graphics Program to solve Soma Cube Puzzle
How to Make an LL(1) Parser: Lesson 3
14 Jul 2019 by
honey the codewitch
Creating a simple parser in 3 easy lessons
CodeDOM Go Kit: The CodeDOM is Dead, Long Live the CodeDOM
11 Dec 2019 by
honey the codewitch
If you use the CodeDOM, here's an indispensable package to make it awesome.
Use Trace and TraceSource in .NET Core Logging
4 Oct 2020 by
Zijian
How to use Trace and TraceSource in .NET Core Logging
Lex: An Optimizing Compiler for Regular Expressions
3 Feb 2020 by
honey the codewitch
A Pike virtual machine and optimizing compiler for regular expressions using an NFA engine
C# Implementation of Basic Linear Algebra Concepts
12 Mar 2020 by
Mohammad Elsheimy
My C# implementation of linear algebra concepts (matrix elimination, multiplication, inverses, determinants, etc.)
Castle Dynamic Proxy Interceptors to Build Restartable Flows
3 Nov 2020 by
Ev Uklad
Another way of using proxies and interceptors from Castle Dynamic Proxy framework
In Search of Streaming... Part 1 of 2
8 Jun 2020 by
D Sarthi Maheshwari
Discussing about streams... about streaming... about functional streaming... and nothing else
MsTest 101: Using the MsTest Runner
19 Oct 2018 by
Sean Rand
Getting the most from your test runner
The Clifton Method - Part III
25 Aug 2016 by
Marc Clifton
Bootstrapping with Module Manager and Service Manager
The Clifton Method - Part IV
25 Aug 2016 by
Marc Clifton
The Semantic Publisher/Subscriber
Windows-based Version of grep in C#
28 Mar 2021 by
Marijan Nikic
grep in C# - Windows-based version
Validation of Interpreted Colors
26 Apr 2021 by
gggustafson
How well does the Interpolation of Colors match the Colors produced by Microsoft's Linear Gradient Brush?
Excelsior! Building Applications Without a Safety Net - Part 2
13 May 2021 by
Pete O'Hanlon
Second part of a series of articles where we build an application showing the entire thought process when writing it
VariableSizedWrapGrid for WPF
28 May 2015 by
Magnus Rindeberg
An implementation of VariableSizedWrapGrid for the Windows Desktop.
EPPlus Excel Template Report Engine
14 Jul 2018 by
Mehdi Gholam
Fill Excel files with data from DataTables based on EPPlus
MVC Angular JS and WCF Rest Service for Master/Detail HTML Grid
27 May 2015 by
syed shanu
MVC, AngularJS and WCF Rest Service for Master / Detail HTML Grid
Implement Virtual List with Paged Data
3 Jan 2013 by
Young Ye
This article solve the performance issue while loading and displaying large amounts of data by using a virtual list with paged data technique.
Cloning Objects in .NET Framework - Part II
11 Apr 2017 by
Juan Francisco Morales Larios
Continues with the cloning objects .NET Framework
DryWetMIDI: Working with MIDI Devices
27 Jun 2021 by
Maxim Dobroselsky
Overview of how to send, receive, play back and record MIDI data with DryWetMIDI
Display Loading Indicator in Windows Form Application
7 Dec 2017 by
Dukhabandhu Sahoo
This article explains how to display a loading indicator (a GIF image) in Windows Forms application when some long running task is performed in the background.
Advanced WPF TreeView in C#/VB.Net Part 6 of n
11 Jan 2018 by
Dirk Bahle
Tips & Tricks on using checkboxes within a WPF treeview.
LDAP Search Utility
24 Oct 2017 by
Mike DiRenzo
An easy to use programmatic LDAP search utility is a single C# class file that can be dropped into any project and used right away.
WinForm VB.NET Hosting WPF Ribbon
1 Jan 2022 by
Jo_vb.net
Host WPF usercontrol with Ribbon within winforms VB.NET project
Description of the Enumeration Members in Swashbuckle
16 Apr 2021 by
Ivan Yakimov
How to show XML comments for enum members in Swagger UI
Auto-generated columns in a WPF ListView
18 Feb 2021 by
#realJSOP
A WPF ListView that automatically generates columns (that are also sortable) based on decorated entity properties
NewtonPlus - A Fast Big Number Square Root Function
19 Mar 2022 by
Ryan S White
A fast, possibly the fastest, square root function for large integers and floats in C# and Java.
Using SpriteLibrary to develop a Role Playing Game
4 Aug 2016 by
BouncyTarget
A sample Role Playing Game using SpriteLibrary to do the graphics
LXUI.NET - Compact Cross-Platform GUI Framework - Part 1
18 Jun 2022 by
Leonid Ustyugov
A quick guide to how to create a project on the LXUI.NET framework and demonstrate some of the features
An Improved WYSIWYG Print Dialog and Page Preview for Rich Text
13 Aug 2020 by
Howard 9448490
Windows Forms Print Dialog for rich text with accurate page preview and zooming
SPA^2 using ASP.Net Core 1.1 + Angular 4.0 - part 8
10 Apr 2017 by
Robert_Dyball
Covering conversion from Angular 2.40 to Angular 4.0 + Publishing the ASP.Net Core / Angular 4 SPA to IIS using VS2017
Candlestick Based off WPF Toolkit
4 Dec 2011 by
Xavier John
Candlestick
Introducing R# Language
3 Aug 2022 by
Mr. xieguigang 谢桂纲
R# language is a kind of R liked language implements on .NET environment
Useful Generic Avalonia Controls located within NP.Avalonia.Visuals Package
20 Dec 2021 by
Nick Polyak
Generic Avalonia controls located within NP.Avalonia.Visuals open source library
ATL Server Tutorial - TipOfTheDay
18 Apr 2001 by
Erik Thompson
Create an ATL Server to generate random tips using a Server Response File
Regasm2.exe – The .Net/COM+ Installation Tool.
22 Oct 2001 by
Roman Kiss
This article describes how to design, build and install .Net Application into the COM+ Catalog without using the ServicedComponent class in your application. The solution shows retrieving the assembly and class attributes (included custom) from the assembly file and their storing into the COM+ Catal
Color Scale Filter
17 Jul 2007 by
Miran.Uhan
Grayscale and color scale filters.
Knit - A Visual Studio Add-In
30 Dec 2007 by
AGD-H
Knit is a Visual Studio add-in tool that allows a developer to apply multi-step patterns to solution and assembly meta-data.
Advanced Phone Number Type Implementation
24 Dec 2008 by
Flamewave4
A phone number structure that can be used for parsing, validating, and normalizing phone numbers.
Shared Navigation for SharePoint Site Collections
29 May 2009 by
Marian Dumitrascu
A SharePoint navigation provider for sharing top navigation with any site collection inside the same farm.
FTP Activity for Windows Workflow Foundation
18 Jul 2009 by
Giorgio Minardi
Custom activity for file operations over FTP folders.
Enhanced ListView Operations Using MVVM
29 Jun 2010 by
Izhar Lotem
Filter and export to Excel ListView data using MVVM standards.
WPF Simple Puzzle
9 Jul 2010 by
Nanung
Developing a drag and drop technique in a simple puzzle game application.
UpnpStat – List and Modify Port Mappings on your UPnP Enabled Router
16 Sep 2010 by
Alex Soya
A simple console utility that allows you to query and modify port mappings on a UPnP enabled home networking router.
MBG XML to Class Generator
3 Nov 2010 by
vnmatt
Code generator for creating XML serializable classes from scanning the XML file itself.
Using SPMetal
15 Mar 2011 by
Not Active
Using SPMetal to generate Linq to SharePoint classes
Embedded Scripting using F#
22 Aug 2011 by
Vladimir Ivanovskiy
This article shows how to compile and run F# code during runtime.
Configurable Aspects for MEF
6 Sep 2011 by
Gary H Guo
Add AOP capabilities to MEF by configuration using Dynamic Decorator.
Validation in WPF Toolkit’s DataGrid
5 Nov 2011 by
Frank Augustin
Describe validation when presenting data in WPF Toolkit’s DataGrid.
Knockout Navigation for ASP.NET Web Forms
17 Dec 2011 by
GrahamMendick
Progressively enhanced ASP.NET Web Forms version of Knockout tutorial sample
One EditorTemplate for all DropDownLists in ASP.Net MVC
16 Jan 2012 by
Wahid Bitar
Get the DropDownList items at OnResultExecuting
A Simple Example for the SoapBox Framework (WPF, .NET)
10 Aug 2012 by
dreamgarden
SoapBox Core uses WPF's MEF to provide a base application framework that is easy to extend. This is a simple example that includes elements of a basic application (toolbar, statusbar, document area, etc.).
Error Logging to the Windows Event Log using ELMAH
5 Mar 2012 by
Aleksandrs Vorobjovs
Error Logging to the Windows Event Log using ELMAH
Using path parameters when binding data in WPF
28 Mar 2012 by
Michael Soloduha
Extends WPF framework with binding that supports runtime path parameters
Time Series Analysis in C#.NET Part I
8 May 2012 by
Jeff B. Cromwell
This article examines the use of the ABMath and MathNet .NET packages for time series analysis..)
Converting Postfix Expressions to Infix
20 Jun 2012 by
Andreas Gieriet
This is an alternative for "Converting Postfix Expressions to Infix"
Navigating the different modules through a TreeView and ToolBar with Prism
21 Jun 2012 by
Andrzej Skutnik
Developing a navigation theme started in the article "Navigating the different modules through a TreeView in Prism."
Managed MAPI (Part 2) – New Mail Notification
6 Feb 2013 by
Fred Song (Melbourne)
Implement a WPF new mail notification.
Creating a Generic (Static and Unchanging) WCF Interface
11 Dec 2012 by
Aron Weiler
Learn how to create a static and unchanging WCF interface that still supports most WCF capabilities.
Leveraging MemoryCache and AOP for Expensive Calls
20 May 2013 by
Darek Danielewski
How to use AOP and System.Runtime.Caching.MemoryCache to improve application performance
WCF by Example - Chapter XV - RavenDB Implementation
3 Feb 2013 by
Enrique Albert
Unit of Work and Repository RavenDB implementation example
UltraDynamo (Part 2) - It Is All About the Sensors
17 Jan 2013 by
DaveAuld
In this section, we will take a look at the sensors, the sensor manager and the simulation
FoxTools Screen Shooter
14 Feb 2013 by
Alеksey Nemiro
Capture screen, edit, and send images to the Internet.
Visual Studio Visualizer: Part 3 - Collection visualizer
10 Jun 2013 by
Frederico Regateiro
This project creates a Visual Studio visualizer for .NET collections
On-demand data population, custom paging, client-side sorting and other general functionality in GridView
4 Jul 2013 by
Zafar Sultan
An article describing general functionality in GridView.
Easiness Duality
4 Aug 2013 by
Paulo Zemek
A possible polemic article on why easiness is not always good.
EtwDataViewer - Analyze, visualize, and make sense of your ETW logs
6 Aug 2013 by
Mattias Högström
Event tracing for Windows is a super efficient log technology, alas logs are still flat raw logs. EtwDataViewer is a prototype for adding browsability, analysis, and a visual tree representation.
Dynatrade-Bell™, Quantitative Trading Engine
17 Feb 2015 by
DrABELL
Innovative Market Data analytical and Equities/Derivatives Quantitative Trading Engineding
Adding JavaScript scripting support to one application: One easy way
2 Sep 2013 by
V.Lorz | https://www.codeproject.com/script/Content/Tag.aspx?tags=.NET | CC-MAIN-2022-40 | en | refinedweb |
suzuki gz250 for sale craigslist
leather hole punch amp belt hole
hamefura manga
italian wholesale clothing
cosmopolitan cover this is healthy
2012 ford escape ac not blowing cold air
relationship names telugu to english
soldier of godrick
every manx27s bible niv deluxe
mhsaa bowling 2022 rankings
giant tcr advanced 2 pc 2022
roblox fly script pastebin gui
mha poly x pregnant reader
rare otf knives
ford f650 for sale
aspose html jar download
cheap rentals near me
pt250 wiring diagram
fun thanksgiving activities
import wallet dat
blender animation pose library
utg op3 micro review
reiki laws in alabama
what does a drowned body look like after a week
sims 4 castle download
does a contract have to be signed by both parties uk
kofire ug 06 wireless gaming headset manual
swing arm lamps for bedroom
skyrim vr sharper image
edgar flores 1040 answer key
metahuman to unreal
does gucci offer discounts
famous songs from carmen opera
mega everdrive x7 reddit
ech home care packages
bior charcoal pore strips
network model excel
oracle sql group by comma separated list
bad boy zero turn mowers prices
dojrp logo
winchester wildcat 22 sr review
wix animate on scroll
full hd gif wallpaper 1920x1080
used backhoe attachment for skid steer for sale near maryland
volka food jobs 2022
tokyo marui shell ejecting
rush strawberry banana
pampers baby diapers for adults
aero precision m16a4 lower
myiptv4k ios download
reversed and set aside meaning
libgpiod pwm
amazon essentials womenx27s lace up
is orangeburg pipe illegal
barefoot hoof trimming tools
lg 29um69g b review
party animals download
decimal places for currency codes sap
dokkan battle summon banners
driving intervention program
java download 64 bits
festival spirituel 2022
best tape deck ever made
group vbs 2021 treasured
gcse physics syllabus
signal jammer uk law
dutch bros grant pass
moon conjunct north node synastry double whammy
inkredible handwriting
hermione gives birth to twins fanfiction
ptz camera control app
wpf validation rule binding parameter
aseprite slice tool
heavy duty lawn roller rental
dcuo atomic tank loadout
frost king gutter guard
mushoku tensei x male reader
foxy and boxy videos
davidson county police reports online
unity additive alpha blend
southwestern stores in tucson
bose quietcomfort 35 headphones
gumroad down
messagekit swiftui
bilibili comics romance
liquidation pallets texas
young cute golfer
best headers for chevy 350
zillow bath uk
cudatoolkit install
free spin promo codes no deposit
pet simulator clicker
liberty 1776 safe vs fatboy jr
flutter ble advertising
renault clio problems starting
colorforms reusable stickers
payment system
fs 22 mobile
obito speech to kakashi lyrics
alexa actionable notifications node red
llamas for sale new mexico
bungalows to rent in wales dss accepted
wholesale trim suppliers
batman beyond season 1
trulia homes for rent 89110
pencil drawing flowers
scheduling display zoom
321 cast bullets
gerald cotten exhumation
aquila simbolo usa
napa downtown
ao3 best drarry fics
how to use rk84 software
byk altn ka gram
high side pressure is low
rooster crowing meaning in islam
best led replacement for t12 fluorescent tubes
wall linen cabinet bathroom
openldap docker compose
most expensive fursuit
six pack booty workout
is john walsh still alive
the four seasons of the year
the vanishing at the cecil hotel
mlf payouts
index ventures team
correct order for recording a blockchain transaction
ajenti 2 demo
starsector d class
neuropsychology courses online free
working remotely on the road
hyaron mesotherapy
portland cement type 1
2004 f450 gvwr
mini cooper r56 fuel consumption
ikea malm daybed
how to clean printer head epson l3150
fitaid zero no artificial
do dogs know when they are going to be put down
maybelline superstay shade finder
aaf themes
high school lacrosse stats
unlock tool modern warfare ps4 free
vvx 411 phone
moose hunting season 2022
sharex ffmpeg
dc ev charger design
46237 franklin homes for sale
craigslist dayton ohio cars for sale by owner
smith brothers dog training
unique lds temple dresses
bl4 veneers
dupage housing authority hours
router as dhcp server
emulsified body butter formulation
stormcast wahapedia
azurescens grain spawn
life in the fast lane
from 4g to 5g
rent a girlfriend season 2 ep 1 eng sub
nectre wood heaters australia
john deere infant toys
lion of judah song
unraid thin client
piece of eight replica
select which 2 of the following statements are true about mcs
psalm 84 commentary spurgeon
nevada rural housing portal
444 river lofts income guidelines
brass wall light with switch
roosters brewery
two blocks are connected by a string of negligible mass
hack wifi github termux without root
vacuum tube manual
n54 stock timing
lands of america highland county va
tomb of annihilation roll20 assets download
keyboard with cat typing
ahk get pixel color
uconn cap and gown
british army wallpaper 4k
home assistant input text lovelace
slack time meaning
brush hill bus to foxwoods
openbullet config file
airplane io unblocked
best op 10 gunzerker build
2014 hyundai santa fe brake pad replacement
air compressor cross reference
2 bedroom flat to rent in southernwood east london
benefits of star fruit for skin
import pygame could not be resolved
powder in gloves allergy
3rd grade math jeopardy common core
nipple slips and upskirts
morismos giant teddy bear
herpes vaccine name
marvell 92xx sata 6g controller driver
matlab scatter border
are any of the bts members dating 2020
the burden of the aeon
autotrail adventure 55 for sale
nexplore oil
veiled virgin stl
zing plant based protein bar oatmeal
ian swanson email
harbor freight towable backhoe price
revit api category filter
nc bamboo nursery
the tourist movie
magnetic cartridge diamond stylus
skydive ohio
nginx proxy manager docker compose
outdoor plants for all weather
thermal grizzly kryonaut the high
lavender care colorado
myflixer arabic
goldman sachs email address format
1965 to 1970 gto for sale
inside higher ed conferences
ss officer uniform for sale
leaked password database download
w900l custom
ryzen master disable prochot
weekly reader 1980s
apsara beautiful
mossberg compact cruiser discontinued
divinity 2 griffs key
jobs for 15 year olds detroit
mercedes garmin map pilot kartenupdate
sniper ghost warrior contracts 2 free download
will the straw hats get another ship
9mm glock mag ar
what to level on phoenix ark
evony protection bubble
911win la o
betting tips telegram
spamton lines
hathi cartoon song
guitar rig 6 metal presets
ford hennessey for sale
gimp brushes free download
bluegill axolotl for sale
underground shelter
cold steel hudson bay clamp hatchet
siemens energy ag
citadel software engineer intern online assessment
cricket hotspot apn
eso best motifs 2022
dell optiplex 3070
squishville series 1 list rare
kidzlane floor piano mat for kids and
nikon color profile download
metro 2033 book summary
what happens when a pfa expires in pa
yoasobi songs the book
coleman mach 15 model 48254c869
return of the mack lyrics
how to install samsung camera app
generac 50g won t start
dragon ball super manga plus
tcl and or
connecticut post mall movies
the complete instant pot for
msop visiting
vasagle industrial storage bench shoe
twin commander poh
regal jumping spider lifespan in captivity
eewa racial traits
steam summary art
mushroom applique crochet
vsim error
asip long whip antenna nsn
van buren county police scanner
510 design shawnee
venus conjunct neptune man
lancescript download
ark controls xbox one
unifi xbox open nat
ender 5 cad model
avoin colorlife home fall buffalo check plaid
alpine overlook
burt baby bee shampoo review
earth day 2022 reading comprehension
trading hub gpo
herren hosen mit gummizug im bund
century dine on
fat wheel bicycle for sale south africa
vp9 magwell
dating a scorpio woman reddit
hpe proliant dl380 gen9 datasheet
asv parts
reference solar cell price
check palindrome string in java
huzzah32 micropython
cheap riding lawn mowers for sale by owner in corpus christi tx
hot tub lodges derbyshire
invalid caa records zerossl
living alone in alaska
webview2 python
food sensitivity test kaiser
qnap mainboard red light
dog kennel roof material
ford edge power liftgate reset
infant insert mamaroo
pacman python install
used small tractor slasher combinations for sale victoria
olay commercial model 2022
phd projects in finance
lucas magneto parts
rent to own shipping container home
belkin ac1200 openwrt
darryl jr victory concrete
faster hdt smp reddit
overall application status under review erap
types of walking sticks
colorado cast bullet co
ceph lifecycle policy
crash bandicoot 2 iso
nba 2k21 download
fearful avoidant after break up reddit
java basic certification hackerrank solution
contour pillow or normal
merge saehd
panama city beach police officers
grand prairie accident beltline
tr7 tr8 for sale
sonic at the olympic games tokyo 2020 crazy games
natural gas intelligence
gainesville craigslist farm and garden
long way 12v battery
ktel heraklio timetable
hungry the highly
maidenform womenx27s love the lift demi
lufgt huron
mantras of ganesha
kidde alarm no light
maven runtime scope
samsung health build prop
tinyusb hid keyboard
ebay motors bbc engines
what does it mean when a guy says he just wants to be friends for now
mymahdi digital compact and portable
tampermonkey scripts for firefox
vortex razor uhd 18x56 vs swarovski 15x56
spring fling 2022
zomedica price target 2022
proc mixed nested random effects
ted naiman protein ice cream
pastor retirement invitation wording
rative rb 71112 non skid anti
flite test shop deutschland
surefire ep4 sonic defenders
craftables mint heat transfer vinyl
cinema hd alternative for mac
i forgot my friends birthday reddit
live funeral services today limerick
flowfly insulated lunch bag
2022 tamil movie download moviesda
bypass emulator detection 2021
qcaa civics and citizenship
qnap bios checking memory
mtg add mana of any color
tapo c200 problems
digital energy surge protector
kenwood repair parts
hyundai walk away lock
changing serial number of an already configured log collector is not allowed
pathfinder ability score
toyota corolla for sale near me
stribog sp9a1 tailhook
aggravated manslaughter in the second degree
inscryption goobert
mercedes c class nox sensor replacement
the legend of dragon pearl eng sub
lcd interfacing with atmega32
absentee business for sale florida
mackinac island store map
girls getting fuckes
jazz transformers death
what is it called when you soak a tampon in alcohol
type 1 diabetes grocery list
unity 2d slider
creature comforts athena
cummins isx15 shifting rpm
vizio tv menu without remote or wifi
ufreegames fidget trading
why is my yealink phone going straight to voicemail
29 cfr 1926 subpart p
1863 springfield ramrod
the longmire mystery series books
the remote desktop server encountered an error and has closed the connection aws
dead by encore
juneau and skagway tours
dmi toilet seat riser
will rogers turnpike toll fees
pbr anaheim 2022
amerigo vespucci ducksters
karaoke revolution american idol encore 2
interactive shell jupyter notebook
jang hyuk action movies
silverscript drug prices for 2022
cost of living in leipzig for international students
buku panduan unreal engine 4
angel investors canada
kegan kline dad delphi
renogy tracer mppt
safety 1st window lock
renault kangoo automatic gearbox problems
vintage solex carburettor spares
huntz self adhesive laminating sheets letter size9 x
medical downfall of the
rimworld hauling
petrol station for sale nsw
nsw2u retroarch
web3 js approve erc20
wgu c207
rca atlas 10 pro frp bypass
gangstalking geheimdienst
julia colorbar ticks
check egl report number
big maps fs22
bengali story books pdf
vankyo leisure 470 manual
cool cars and bids
aidg prompts
female eyeless jack x male reader lemon
snakebyte xbox one battery
piano practice for beginners
fileboom premium generator
antique arrowheads
master class unreal engine
madden 22 face of the franchise linebacker tips
hp pavilion gaming ryzen 5
bay terrace apartments
dell precision 7550
e grizzly electric bike 1000w
bitlocker dell laptop
grand designs season 21 streaming
toyota tacoma salvage yards near me
hallmark signature wood valentines day card
alchemy animal symbols
american idol season 4 contestants
sequelize belongstomany
nginx ipv4 to ipv6 proxy
2017 ford f250 tailgate actuator
bissell little green leaking from bottom
why do estps hate infjs
jetbrains fleet roadmap
topping l50 manual
best album art downloader
smartratswitch app
maia knight suny
mobile homes in florida with low lot rent
dating questions and answers
raspberry pi play sound python
electronics recycling richmond va
car accident dublin yesterday
palomino horse for sale near moscow
razer basilisk v3 vs v2
2015 mercedes ml350 battery location
tmc2208 vs a4988 print quality
subaru misfire after warm up
mountain house plans for sloped lots
should i stay with my boyfriend
how to check drain pump on washing machine
smtp authorization failed
j4125 vs n5100
dell ftp server firmware update username password
hydraulics software free download
monsta mad hatter bat
wire transfer money laundering red flags
unable to validate the following destination configurations s3 lambda
serta hannah ii office chair
5 degrees in astrology
dj paul store
estes park today
gottlieb pinball manuals pdf
avery white self adhesive
ispot commercial actress
tent jacks
comotomo baby bottle green 8 ounce 2
prayer intentions for lent
picrew me gacha heat
fairlife protein shake recall 2022
rachel loeb edc email
interstate 8d deep cycle battery
16x12 pergola cover
ceiling fan mounting bracket installation
fortigate restart ssl vpn process
free xfinity username and password 2021
buffalo freestyle drake mp3
acls exam questions and answers
hp tuners bcm programming
french brittany puppies colorado
little killer sudoku online
valentina in the heights
us navy crew list
the count of monte cristo
vrchat avatar udon
matthews yachts
multiplication table in javascript using for loop
pixhawk rangefinder
unit 76 the mornington
intel grade 5 salary hillsboro
fujifilm xt3 vs x100v
hot bird channels
mechwarrior 5 hero annihilator
17 design upper receiver
long term rentals grand lake ok
liquidation buyers
tremec 3160 parts
washington state law on abandoned vehicles
forward vs deferred rendering ue4
sabot slugs 12 gauge
inspector gadget niece
how to switch off samsung s20 fe
8 hrs security job in singapore
generate random string python uuid
potaroma flopping fish
wizarding world harry potter house quiz
broken trust dark legacy book 2
tronxy x5sa pro mod
snow white with the red hair boyfriend quiz
watchyoursixx hunter sim
peugeot dtc e608
snare mutants and masterminds
henry rifle peep sights for sale
how to make a sequin leotard
caravan parks tasmania
wifi power outage monitor
forest lawn cemetery records
funko marvel dancing groot bobble
diff command windows
matlab xticklabel
c2440 initializer list
500 grams flour to cups
truck trader malaysia
5k timer app
idot pothole claim
bmw quad bike for sale
introductory mathematical analysis
redmi note 8 pro nv data is corrupted
safe harbor marinas locations
dress up america princess heels for
midori pullover
homebrew dreamcast games for sale
sabrent usb type c dual hdmi
bella modeling agency
joe rogan jordan peterson carnivore diet
susan after 60
plotting coordinates in 4 quadrants worksheet
recovery rebate credit college student
joe camel t shirt
word text recovery converter online
3 pin to 16 pin obd2 adapter cable connector for fiat alfa romeo lancia
prodigy chromebook
cock rooster
mansoob meaning in english
chicken lights and chrome
porthcawl car boot sale 2021
pegasus 5e mount
zsh escape quotes
best price polymer 80
ikea lommarp cabinet assembly
animation composer old version
rectangle woven basket large
luxury homes in tucson
paughco pre wired handlebars
hidl interface
flim vivian hseih xxx
creatine slow comt
atlanta girl beat to death on instagram live video
doom slayer costume buy
wellness wednesday quotes 2022
asrock amd x470
outlet mall leeds uk
telerik autocomplete blazor
dirty turkey jokes for adults
6x12 beam span
ffxv comrades curved hollow horn
postgresql not equal
globe apn free internet
set paragon degree btd6
general lee horn meaning
maverick 88 stock magpul
vehicle detection and tracking github
how to find the sum of the first 10 terms of an arithmetic sequence
cosmoprof hong kong 2022
female news presenters uk 1980s
shutterstock little girl
fanbox free access
electric sawmill for sale
refrigerator defrost cycle
append to tuple python
drivers license roblox
ezgo ex1 price
centerpiece rentals houston
systembuild kendall 36quot
volume profile range mt4
reheat bob evans mashed potatoes
equilibrium point calculator
555 wilson ave review
fox sports 1
how to unlock characters in mortal kombat 11 ultimate edition
battletech dropship firing arcs
sunbeam mixmaster replacement parts
ror2 void items
panda vrchat avatar
fortigate export logs
portable solar simulator
dmarc office 365 configuration
cheap resin garden statues
lynk pleasure products anal lube water
tower structural analysis software
chargepoint gateway installation
bluebeam show markup toolbar
cypress logging in louisiana
zeda 100cc engine
cloudfront static ip
firekirin xyz 8680 login aspx
bottle dynamo
lmt pool registration
lotus caravan dealers melbourne
2005 dodge dakota transmission control module location
dell usb dvd
replacement usb for ps5 headset
welgun loadout
webview2 cookie manager
emui 11 p20 pro download
best toasts funny
bass cabinet and head
felipe athayde wife
17 bus route to london bridge
psychiatry recruitment 2022
motor para caminadora bh fitness
real estate principles exam 2
character count in c
low speed clicking noise
tw200 saddlebags
simple gospel choir songs
2018 chevrolet silverado 3500hd towing capacity
med surg hesi practice exam
dffoo weapon skins
50 cal sniper rifle range
atude to daju
most common causes of intellectual disability
this excerpt best supports the conclusion that odysseus is
p3d in rafaela
steelseries arctis 5
pinterest short hairstyles for black woman
sponsored by adidas
sba caweb
vray 5 for sketchup crack
dulce domum lyrics
usb c to 35mm dongle
among us mod roles explained
hprt mt800 driver
8kw solar inverter
minimizing trauma reddit
jensen cassette tape recorder
link crosshair valorant
day trip to crystal beach
land of little horses cafe
gpd win 3 teardown
vonage set up new phone
sky fnf real person
military canteen for sale
taipan veteran standard model
wheelchair seat cushion roho
long fluffy hair male
math in english grade 1
how to prevent carpal tunnel
newmar motorhome dealers
11 bus times
otterbox mobile charging kit
github instagram private account viewer
best places to live in asia for english speakers
feng shui pictures for success
older sirius black x reader
mydethun moon lamp 35 inch
get 2 months back date in sql
logback pattern mdc
converted trawlers for sale uk
tunnel carpal syndrome
of black girls fucking
yangi uzbek klip
fated to the beta
png silhouette
unpaid carers forum
gas grill with led knobs
stars baseball 2022
revolutionary war coat for sale
final fantasy x x 2 hd remaster
mold girl tiktok
bioinformatics remote internship
whiteboard finance spreadsheet
best developmental psychology masters programs
pspice latest version
my hero academia fashion novelty charm
bootloader adafruit
oracle 11g to 19c upgrade
how to reset the computer in a 2002 cadillac deville
metal scales for armor
thyssenkrupp elevator revit
what do dead nits look like
english short story for grade 6
2016 chevy malibu throttle position sensor location
old aimpoint red dot
filtfilt ignore nan
norma 350 legend ammo
cape falcon f1 for sale
deshmukh warehouse bhiwandi
melvor agility potion
men women sling backpack anti
franke parts
mneb swap error
wife hides friends on facebook
rv hot water heater control module
cartus relocation reviews
shroomery unmodified shoebox
20 nintendo eshop gift card digital code
amtrak 6 ride pass cost
xtream iptv link
laravel websocket api
sunshine coast council fees and charges
3000 toys trucks
japanese food displays plastic
kea dhcp option 82
anydebrid premium
2021 silverado oem led headlights
ssacli ubuntu
fps checker for pc
how to join telegram channel with link
dominican porn videos
bepco dealers
westermeyer oil separator
funny superlatives
withdraw money with expired debit card
animal rental
how to remove password from samsung phone without losing data
convert attic to loft
tobacco boxing cards
ds4 windows not working on warzone
used spare parts sharjah online
moodle default username and password
zenitco wiki
qtcinderella instagram
dry fertilizer blockage monitor
iguro obanai x reader wattpad
podman network host
primary past papers 2020
d965 datasheet
onan generator fuel line size
drug bust in abbeville
stampede rodeo valley center
salient arms barrel canik
certainteed weathered wood
underworld unleashed the 25th anniversary edition
python reading pdf files
enable http server on asa
san bernardino county probation check in online
church hymns lyrics
delta point partners
pontiac tempest 1968
moto g7 apn settings
freed fifty shades of grey
ford f350 forum problems
susan after 60 summer dresses
kusto render color
vrbo lake ouachita houseboat
index of icloud photos
microsoft 365 inventory management
women erotic pics
tic tac toe game 2 player
self adhesive waterproof numbers
over under 22 410 guns
nhl win loss records
power bi calendar first day of month
godzilla kaiju list
zeny 10x30 tent assembly instructions
2023 predictions baba vanga
motorola phone volume problems
7z to iso converter online free
texas law enforcement training
california vehicle code 2020 pdf
ls3 head cc
your guide to the national
smb logs windows 10
hang on while we load your workspace
vintage car radio for sale
ithaca serial numbers
lisa ann lust for lisa
peep sight for remington 572
switchbot raspberry pi
ford kuga radio no sound
hx front bumper
aqua jewel wow
acca student
jl w7 13
wood lathe tool rest assembly
free vaseline samples for healthcare professionals
davinci shingle warranty
office 365 security and compliance
irish brands
bacp ethical framework
roblox music script
index of mp4 boba
2013 rav4 transmission fluid change interval
mens satin robe silk
mathcounts test pdf
wwise unity scripting
lvm show extents
spudnik beet defoliator
duracraft funster
genelle padilla
masn orioles tv schedule 2022
project nursery wall decals
cort earth 100 vs yamaha fg800
the tower of swallows
performance boats for sale in missouri
chris scanlon husband
hunting eve an eve duncan
captivated by you meaning
wavesurfer typescript
truth hardware casement window parts
staffy pups for sale sydney
old victoria magazines for sale
unlock a125u z3x
mind pump maps pdf
call information
power bi gruppieren
lgbt love story movies
import serial python
apriltag aruco
north dakota hastings fs22
new mexico hunting units
keycloak azure ad sync
clark county employment drug test
american top 40 july 9 1983
shark cnc machine for sale
land cruiser 1997
gx460 fuelly
gilmore girls a year in the life season 2
f1 colors
tech sights ruger american rimfire
zilxi foam how to use
nest connect error na023
etekcity luggage scale digital portable handheld
a level further maths questions by topic
monk spells
good night yoga a pose by pose bedtime
qupath tutorial fluorescence
sun square mercury
winter night out outfits 2022
oppo phone unlock code
ubuntu efi partition size
generational curses bible verses
file to pdf converter
retired devon rex cats for sale
ppg deltron color chart
razer lancehead tournament edition 5g
horus heresy legions list
xemu xbe files
60 inch freestanding tub with end drain
american business group shipping
how to wire intermatic digital timer
cubicsdr anleitung deutsch
metal puzzle solutions
escort girl shemale
handgun with most stopping power
lovecraft happy hour
project xl script
osrs range bot
progress in mathematics grade 3 textbook pdf download
jf011e fluid capacity
scrubs season 3 episode 15
aether sx2 games download
findfiles jenkins example
first pyramid scheme
pack of 6 meaning
starter solenoid wire replacement
dbzdutch guru gossip 2022
wombo dream not loading
old ditch witch trencher models
zelotes t80
pearson 7th grade literature book
current services and obituaries
macrium reflect 7 free download
casanova fnf hd
evercore modeling test
ace hardware yeti sale
nh oil undercoating mobile
riviera property management san diego
netless vr script
yoyo babyzen accessories
quarter midgets for sale in washington
blitzway marilyn monroe
how to take motion photos samsung
screamin eagle 95 heads
ms office 2019 activator
ikea vadso mattress
new rage cycles
loving angel wings
10 meter linear amplifier
open source 2d unity games
scott and lindsey love after lockup
dynasty warriors 5 ps2 iso
barren synonyms
fannie mae social security income gross up
vexille movie
amplified holy bible large
honda gx340 specs
raidforums osed
mitsubishi eclipse 1997
strep skin infection pictures
dell latitude 5520 freezing
thomasville swivel chair costco
aries sun pisces venus woman
best side mount bipod
accident on route 3 east rutherford
fanfiction naruto genius english
tek launcher ark
signs you have hurt a girl
activities to release anger
technical bulletin tb 0119 efs cq
convert uppercase to lowercase in excel
runcorn bridge payment
48v dc wire size chart
bcozzy neck pillow for travel
accident grand junction
raquel from laguna beach now
sa german dagger authentication
lost ark cursed doll support
true star mtl
ucla housing options for freshman
surah kausar 129 times
2600 sq ft modern house plans
baltic blue pothos soil
opinel no 8 black
airline training academy
wordle solver extension
slide buckle
3d house tours furnished
asian love symbol
john deere 42 inch hydraulic tiller
cannibal cafe link
cavapoo puppies for sale cape town
colorado abandoned property law
cahokia il zoning map
image to video deep learning
nigeria student telegram group link
5 ways to avoid conflict
solo skiff seat
pisces physical appearance female
skada conan exiles
nintendo link cable
tekken lidia guide
akun resmi dispatch
bts v meaning
tensorflow checkpoint restore
tiktok job interview 2021
samsung enodeb commands
dixie mafia documentary discovery channel
where to sell nascar trading cards
time life 60s infomercial
what is worse chlamydia or herpes
bachan pandey full movie online watch
scan qr code to excel spreadsheet
salesforce picklist value api name
churches for sale east yorkshire
base64 encode in python
how to pair wiz led strip
congestive heart failure fluid overload treatment
rtx 3080 undervolt settings
samsung syncmaster sa300 not turning on
anova in real life
benign fasciculation syndrome causes
anvil brand clothing
pes file viewer online
view h5 file online
medtronic minimed 770g price
oh dip dab rig
diy gold dredge
men shelter
pistol movie 2022
fck trump an adult coloring book
mt shasta hot springs
leesburg air show
art deco jewelry for sale
gamma correction in image processing
hs honkai
gta 5 police skins
domestic battery wv
impp outstanding shares
orange trucker hat wholesale
ruby buckle results 2021
nyfd death 2022
proprietary trading firms houston
2005 rialta hd | https://cs-advert.pl/237/11/2005.html | CC-MAIN-2022-40 | en | refinedweb |
Stellar Phoenix BKF Recovery 2.0 With Crack 64 Bit
Actual a Hidden Archive Z keygen crack trainer.. Stellar Phoenix BKF Recovery v2.0 with crack 64 bit SysTools BKF.
RUNNAR OMEGA QUARTZ ACTIVATION DIESEL OFFICE 3.8 crack. Stellar Phoenix BKF Recovery 2.0 v.4.3 Crack. Stellar Phoenix BKF Recovery.
Stellar Phoenix Windows Data Recovery – Professional v.5.0 serial. Accent ZIP Password Recovery (64-bit) v.4.2 keygen. Outlook Recovery Toolbox v.2.0.11 serial keygen. Stellar Phoenix Windows Data Recovery Professional v9.0.0.1 keygen.One person has died and three others have suffered life-threatening injuries after a collision between a bus and a stationary lorry in London, police said.
The bus collided with the lorry in Tower Bridge Road shortly before 11.30am on Monday.
Two people, an adult man and woman, and an eight-year-old girl who was a pedestrian, were taken to St Thomas’ Hospital.
A 40-year-old man was taken to King’s College Hospital after he was hit by a second lorry on Tower Bridge Road.
The road was closed while firefighters cut the lorries apart, Scotland Yard said.
A Metropolitan Police spokesman said: “A collision occurred on Tower Bridge Road where a bus collided with a lorry.
“A man has been taken to hospital in a critical condition. Three others were taken to hospital by London Ambulance Service and have been discharged.”Live4
Live4
Overall guest ratings
Nearby
About
Nestled in the mountains between Florence and Siena, this hotel is just 2.2 mi (3.5 km) from the center of Siena and the Opera di San Domenico. In addition, attractions like the Palazzo Pubblico and the Piazza del Campo are within 1 mi (2 km). With city views and a rooftop terrace, apartments are spacious and offer parquet flooring and free WiFi. Each apartment features a private bathroom with a shower and bathrobes. Guests at this Siena hotel can relax in the sunshine on the rooftop terrace. An on-site restaurant serves regional food and has outdoor seating. Siena Airport is 3 mi (5 km) away and a shuttle-
our most recent programs & applications,. and Stellar Phoenix BKF Recovery 2.0 With Crack 64 Bit. once again with a Microsoft Office 2013 product key on the market,. our clients a simple way to perform a logical recovery of all of the. The Compaq Hard Drive Diagnostic Tool.//===———————————————————————-===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===———————————————————————-===//
//
// template
// class lognormal_distribution
// lognormal_distribution(lognormal_distribution&&);
#include
#include
int main()
{
{
typedef std::lognormal_distribution D;
D d1(1.5, 1);
D d2;
assert(d1!= d2);
d2 = std::move(d1);
assert(d1 == d2);
}
{
typedef std::lognormal_distribution D;
D d1(1.5, 1);
D d2(1.5, 2);
D d3;
assert(d1!= d2);
d3 = std::move(d1);
assert(d1 == d3);
assert(d2!= d3);
}
}
using System.Runtime.InteropServices;
namespace Sledge.BspEditor.UserInterface.Dialogs
{
public static class ErrorControls
6d1f23a050 | https://ibipti.com/stellar-phoenix-bkf-recovery-2-0-with-upd-crack-64-bit/ | CC-MAIN-2022-40 | en | refinedweb |
Extension for os module, for POSIX systems only
Project description
filesystem module
import filesystem as fs
Testing if a path is a file (shortcut for try/with open):
fs.isfile('something') fs.isfile('something', mode='r')
Shortcut for rsync -a
Uses `sh module <>`__.
fs.sync('name@somehost:~/somedir/', 'local_path') fs.sync('~/somedir', '.')
Returns exit code and does not catch any exceptions raised by sh.
Check if a file is the same based on modified time
Example use: determine if a file is the same based on a HEAD HTTP request using the Last-Modified header.
from urllib2.request import urlopen req = urlopen('') req.get_method = lambda: 'HEAD' last_modified = None for line in str(req.info()).split('\n'): if 'last-modified' in line.lower(): last_modified = line.split(': ')[1].strip() last_modified = time.strptime(last_modified.replace(' GMT', ''), '%a, %d %b %Y %H:%M:%S') break # Actual check fs.has_same_time('./sgon5YP.jpg', last_modified)
Delete a set of files
Use fs.rm_files(list_of_files, raise_on_error=bool_val).
pushd usage with the with statement
from osext.pushdcontext import pushd with pushd('some_dir') as context: pass
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
OSExtension-0.1.5.tar.gz (3.1 kB view hashes) | https://pypi.org/project/OSExtension/0.1.5/ | CC-MAIN-2022-40 | en | refinedweb |
DGL Adapter
The ArangoDB-DGL Adapter exports graphs from ArangoDB into Deep Graph Library (DGL), a Python package for graph neural networks, and vice-versa
The Deep Graph Library (DGL) is an easy-to-use, high performance and scalable Python package for deep learning on graphs. DGL is framework agnostic, meaning that, if a deep graph model is a component of an end-to-end application, the rest of the logics can be implemented in any major frameworks, such as PyTorch, Apache MXNet or TensorFlow.
Resources
Check out this lunch & learn session to get an introduction and see how to use the DGL adapter.
The ArangoDB-DGL Adapter repository is also available on Github.
Installation
To install the latest release of the ArangoDB-DGL Adapter, run the following command:
pip install adbdgl-adapter
Quickstart
The following examples show how to get started with ArangoDB-DGL Adapter. Check also the interactive tutorial.
from arango import ArangoClient # Python-Arango driver from dgl.data import KarateClubDataset # Sample graph from DGL # Let's assume that the ArangoDB "fraud detection" dataset is imported to this endpoint db = ArangoClient(hosts="").db("_system", username="root", password="") adbdgl_adapter = ADBDGL_Adapter(db) # Use Case 1.1: ArangoDB to DGL via Graph name dgl_fraud_graph = adbdgl_adapter.arangodb_graph_to_dgl("fraud-detection") # Use Case 1.2: ArangoDB to DGL via Collection names dgl_fraud_graph_2 = adbdgl_adapter.arangodb_collections_to_dgl( "fraud-detection", {"account", "Class", "customer"}, # Vertex collections {"accountHolder", "Relationship", "transaction"}, # Edge collections ) # Use Case 1.3: ArangoDB to DGL via Metagraph metagraph = { "vertexCollections": { "account": {"Balance", "account_type", "customer_id", "rank"}, "customer": {"Name", "rank"}, }, "edgeCollections": { "transaction": {"transaction_amt", "sender_bank_id", "receiver_bank_id"}, "accountHolder": {}, }, } dgl_fraud_graph_3 = adbdgl_adapter.arangodb_to_dgl("fraud-detection", metagraph) # Use Case 2: DGL to ArangoDB dgl_karate_graph = KarateClubDataset()[0] adb_karate_graph = adbdgl_adapter.dgl_to_arangodb("Karate", dgl_karate_graph) | https://www.arangodb.com/docs/3.9/data-science-dgl-adapter.html | CC-MAIN-2022-40 | en | refinedweb |
table of contents
NAME¶
new_form, free_form - create and destroy forms
SYNOPSIS¶
#include <form.h>
FORM *new_form(FIELD **fields);
int free_form(FORM *form);
DESCRIPTION¶
The function new_form creates a new form connected to a specified field pointer array (which must be NULL-terminated).
The function free_form disconnects form from its field array and frees the storage allocated for the form.
RETURN VALUE¶
The function new_form returns NULL on error. It sets errno according to the function's success:
- E_OK
- The routine succeeded.
- E_BAD_ARGUMENT
- Routine detected an incorrect or out-of-range argument.
- E_CONNECTED
- The field is already connected to a form.
- E_SYSTEM_ERROR
- System error occurred, e.g., malloc failure.
The function free_form returns one of the following:
- E_OK
- The routine succeeded.
- E_BAD_ARGUMENT
- Routine detected an incorrect or out-of-range argument.
- E_POSTED
- The form has already been posted.. | https://manpages.debian.org/testing/ncurses-doc/new.3form.en.html | CC-MAIN-2022-40 | en | refinedweb |
Nico Meyer782 Points
What the correct code? Got it working but challenge don't accept answer.
In this task we're going to write a simple function that takes two numbers and returns the remainder of dividing one number by the other.
Step 1: Declare a function named getRemainder that takes two parameters, a.
// Enter your code below func getRemainder(a value: Int, b divisor: Int) -> Int { return (value % divisor) }
1 Answer
andren28,359 Points
You have the local and external names of the parameters the wrong way around. The parameters are meant to be called
a and
b locally and
value and
divisor externally. Also it's not really necessary to wrap the equation is parenthesis, though it won't produce an error either.
If you fix the code like this:
func getRemainder(value a: Int, divisor b: Int) -> Int // Swapped local and external names { return a % b // Change names to account for the above change }
Then your code will pass task 1.
josh kinney1,576 Points
Why doesn't this pass the second part?
func getRemainder(value a: Int, divisor b: Int) -> Int { return a % b }
let result = getRemainder(a:10, b:3)
Nico Meyer782 Points
Nico Meyer782 Points
Thanks, that dit the trick. Appreciate the help | https://teamtreehouse.com/community/what-the-correct-code-got-it-working-but-challenge-dont-accept-answer | CC-MAIN-2019-35 | en | refinedweb |
Learning time-lapse of coding the game, the whole thing took around 40 minutes.
This tutorial will use Java to show you how to use the LibGDX framework to get a working game on your android phone and your computer. The great thing about LibGDX is that you code your game and can then export to a variety of platforms, namely PC (Mac, Linux, and Windows), Android, IOS, and HTML5. This tutorial will focus on Android but if you want to deploy to iOS you can code the game following the tutorial, then follow these instructions to deploy to iOS.
I will show you how to get the basic game working on your phone with touch controls. After making this Instructable I also added more features like gesture controls and released it to the Google Play Store, which you can see here.
This is by no means intended to be a straight-up Java tutorial and having some experience with Java will help you greatly here, there are already plenty of excellent Java tutorials online, so do one of those before following this. I do believe that 'doing' is one of the best ways of learning, and putting your Java skills in the context of a real thing can really help you learn, understand, and remember key concepts.
As always, comment questions or message me and I'll do my best to help.
Oh and feel free to offer improvements or tips for my code, I'm by no means an expert and am always willing to learn. And do let me know if I've made any mistakes in the included text files/screenshots/instructions.
Let's jump right in.
Teacher Notes
Teachers! Did you use this instructable in your classroom?
Add a Teacher Note to share how you incorporated it into your lesson.
Step 1: Your Programming Environment and You
Install an IDE
It is definitely worthwhile using an IDE (Integrated Development Environment) to simplify and speed up things. I use IntelliJ IDEA and so the screenshots and IDE-specific instructions will relate to that. Eclipse is a classic IDE you could use instead. If you're new to coding it may be easier to use IntelliJ IDEA to make it easier to follow along, as my instructions are IDEA-specific.
Install the Android SDK
To export your project to Android you'll need the Android SDK which can be found here. Android Studio isn't needed for this tutorial and you can download the SDK separately (scroll down to the bottom), but installing Android Studio will install the SDK for you.
Once you have an IDE and Android Studio/SDK, proceed to the next step to install LibGDX.
Step 2: LibGDX
LibGDX is a cross-platform, open source, fairly well-documented framework for making games. Essentially, LibGDX will handle all the boring boilerplate stuff and free you up to make a game quickly. Without LibGDX you'd have to worry about how to draw an image on a screen at a particular location, along with a plethora of other boring stuff. Not only is LibGDX easy to use, it's easy to set up and install.
Follow this link to LibGDX's download page and download the 'setup app'. Create yourself a folder for all of the Android games you're going to make after this one, and within that create a folder for this project specifically called 'snake'. Put the gdx-setup.jar you downloaded in the outer folder so that it's easy to find for future projects. This jar file will download all the files you need and create a base project, upon which you'll build your game. Go ahead and open it up and you'll see the Project Setup screen.
Setup
- Name: You can choose your own name for this, I just called mine 'Snake'
- Package: A Java package is a way of organising classes, similar to a folder on a computer. By convention, Java programmers name their packages after some internet domain that they own (reversed), for example, com.myWebsite.someProject. Java packages need to be unique to avoid clashes with other Java programmers' work, and since domains are unique they are used to name packages. If you have a website use that, but if you don't, don't worry too much. For a small project, as long as you pick a package name that is probably going to be unique then you'll be fine. Try not to pick one that starts with 'com.' if you don't actually own that website. A package that could be fine would be 'personal.yourNameHere.projectname'. As soon as your indie games studio gets big though, you'll want to start using proper package names.
- Game Class: This is just the name of the main game class. I called mine 'Main', but you can call it what you like.
- Destination: This is where the base game files will be downloaded. Pick the folder that you made for the game.
- Android SDK: The location of the SDK you installed from the previous step. If you installed Android studio, you can find the location by launching Android Studio and going to Configure -> SDK Manager
- Sub Projects: These are the platforms you would like your game to run on. I just chose Desktop and Android, but feel free to tick more if you want to deploy to other platforms.
- Extensions: These are some very useful libraries that will definitely come in useful in your Indie Gaming career. For now, all we need is 'Tools', so check that and leave the others unchecked.
Before generating the project, click Advanced-> and make sure 'IDEA' is checked to automatically generate project files for IntelliJ IDEA (check 'Eclipse' if you are using that). Press Save, then Generate.
(Side note: You can get pretty cheap domains online if you want your own guaranteed package name)
Step 3: Into the IDE
So you have your IDE and SDK installed, the LibGDX files are downloaded and in the right place, it's time to get coding. There are a couple of things to sort out first. Launch your IDE choose 'Open' or 'Open Project'. If you ticked the 'IDEA' or 'Eclipse' option in the previous step, your project files will have been generated. For IDEA, navigate to your game directory and double-click the 'yourGame.ipr' file.
- In the bottom right a box will pop up prompting you 'Import Gradle Project'. Press this, then in the pop up make sure to untick 'Create separate module per source set'. Leave everything else as it is and press ok. You'll see a loading bar at the bottom and give this some time to complete.
- Once this is done, close and re-open the project and you'll get a prompt to update Gradle to 3.3 (at the time of writing). Do this, and you'll see that an 'Android' configuration has been made for you (top of the screen to the left of the green 'Run' arrow).
- Double click the folder icon with the name of your game in the top left to reveal the file browser.
You'll notice a number of folders. The folders for 'android' and 'desktop' (and 'ios' etc if you kept those) contain files to launch the game on a specific platform. For now, we're much more interested in the 'core' folder.
- Double-click folders to open them. Open core->src and you'll see a 'Class' called 'Main' (or whatever you chose to name your Main class). The 'C' icon next to it tells you that it's a class file. This has been automatically generated for you by the LibGDX setup app and has come preloaded with a simple application.
- Double click the Main class in the Core folder and you'll see its code.
I'll explain what this code is doing in the next step, but for now, let's run the simple auto-generated application to see what it's doing. We need to add a 'configuration' for the Desktop Launcher so that we can test out our game on the computer. This will tell the IDE that we need to use the files in the 'Desktop' folder to launch the game when we press the green arrow.
- Click the drop-down box which currently says 'Android', then click 'Edit Configurations'.
- In the Configurations window that has appeared, click the 'plus' in the top left to add a configuration. Select 'Application'.
- Now we tell it that we want to use the Desktop files. In 'Main class' type "your.package.here.desktop.DesktopLauncher". If you open up the 'desktop' folder in the explorer on the left of the IDE you'll see that there's a 'DesktopLauncher' class in the src folder.
- In the 'Use classpath of module' box select 'Desktop'.
- Add a suitable name in the box right up the to, like 'Desktop'.
- Change the working directory to yourGameFolder/android/assets - this folder is where textures and sounds should go
- Click OK
Make sure that 'Desktop' is the currently selected Configuration using the box that used to say Android, then click 'Run'. If all went well, you should see a window appear with a horrible red background and a BadLogic logo. You're ready to start coding!
If you don't see this window, double check that you've followed the steps carefully, and feel free to ask for help by posting your error message below.
Step 4: The Game Loop
Code for this step is provided in the text file and screenshots. Remember to change the package name in the text file if you use it.
LibGDX handles all the hard stuff for you. You just have to write the code that gets executed every 'tick'. You have underlying logic for the game that holds stuff like the position of entities, their health, their name, anything you could think of that needs to be stored and updated. Then to turn that in a game all you need is a bunch of images flying around the screen that represent the logic underneath.
The game loop:
LibGDX calls your 'render' method that you can see in the Main class. Your code in the render method takes some time to execute, images are drawn onto the screen, and when it's done, the engine calls render again. You can make something move by changing its position every time the render method is called. Let's do this now.
Add a member variable x to the Main class:
int x = 0;
In render, increment x:
x++;
Change the image's x position to use your x position:
batch.draw(img, x, 0);
Now every time render is called the image will move slightly to the right. This is because the x position of the image is increased every time the image is drawn.
As for the other provided methods, create() is called when the game is started. This is where the images are loaded and the SpriteBatch is created. Dispose() gets rid of unused resources. It's important to make sure to dispose of unused resources like images, fonts, and sounds when you are done with them. More details on that here if you're interested, but for this project, we won't have any assets to dispose of.
The SpriteBatch basically sends many images to the GPU at once to improve efficiency. More details here if you're interested, but don't worry we won't need to use the SpriteBatch for this game.
Step 5: Screens
We'll be using 'Screens' to implement the game. This is an interface provided for you by LibGDX, and like the Main class, each screen has a create, render, and dispose method, along with some others that you don't have to worry about yet.
You can think of screens as literal screens of a game. You might have one screen for level 1, another for level 2, another for the main menu, another for the options menu etc. For now, let's make a screen for the snake game, called 'GameScreen'.
In the 'core->src->your.package' folder, right click on the package and click New->Class, or right-click on your Main class and click New-> Class. Name this one GameScreen (remember in Java it's conventional to capitalise the first letter of classes). Make this class implement the Screen interface by typing 'implements Screen' after the class name, importing the Screen class from com.badlogic.gdx.screen.
public class GameScreen implements Screen
You should see a red line appear underneath it, saying that you need to implement methods in 'Screen'. Screen is an interface with abstract methods - methods that have no code in them - that you need to implement. Press Ctrl + i, then Enter to automatically add these methods to your GameScreen class. you should see 7 methods appear. The main one we'll add to is the 'render' method, which is called every game tick. It's just like the render method in your Main class, but it has a 'delta' float supplied to it.
Back to Main
In order to use Screens, we need to change something in the Main class. Main currently extends ApplicationAdapter, but we need it to extend Game. All this does is allow us to use Screens, as Game itself extends ApplicationAdapter. Change ApplicationAdapter to Game.
public class Main extends Game
We next need to add super.render() in the Main render() method, which needs to be done now we're extending Game, not ApplicationAdapter. Make it the first thing in the render() method.
Next, we don't actually need to draw anything in the Main class, since this will all happen in the GameScreen class. Because of this, delete everything in the Main render() method except super.render():
public void render () { super.render(); }
Since we're not drawing anything, we don't need the default example image provided in the class. Remove the 'Texture img' state, and any other references to the image.
Finally, we need a way of telling Main which Screen we want to switch to when the game starts. This would normally be a loading screen or the Main Menu, but for now, let's switch to our GameScreen Screen.
Add this at the very end of the create() method.
this.setScreen(new GameScreen());
You can now remove any import statements that are not used (greyed out).
Step 6: Delta
The delta value supplied to your render method by the game engine is the time taken for the last frame to draw, or the time in between the last frame being drawn and this frame to start drawing. It is measured in seconds, and typical values of delta may be around 0.008s.
This is actually an incredibly useful, simple, smart way to make things move at the speed you want them to.
The Problem
Let's imagine that in your render method you tell an image to move one unit to the right. The computer processes your code, calls the render method, in a loop over and over again. If you put this code on a slow computer, it will take longer to process the code, and your image will effectively move slower. If you put it on a fast computer, the image will move faster. What if the image represents your character in the game, shouldn't the character move at the same speed, regardless of the phone the game is running on?
The Solution
Introduce the hero delta, here to save your game from the woes of different computers/phones. Since delta is the time in between this frame and the last frame, you can scale the player's speed by delta to ensure that the player moves at the same speed.
Suppose you want your character to move 5 in-game units in 1 second. In your code, you give the player some state 'int velocity = 5;'.
Distance = speed x time, and we have the speed, and we have the time (delta). In the render method you calculate the distance the player should move:
float distanceToMove = velocity*delta; //example code, you don't need to add this
And you add this to the player's x:
x += distanceToMove; //also example code
Now, if delta increases, distanceToMove increases. This is what should happen, as if the time between frames is slower the player should move more distance between each frame. By multiplying velocity by delta you ensure that player velocity is constant no matter what platform the game is running on.
Confession: We're not actually going to use this technique in the snake game. Instead we're using a grid-based system and using delta as a timer to know when to update the game logic because it's a better fit for snake, but still I think it's really important for you to know this because you'll inevitably go on to build some platformer or top-down game or something and that's where this technique is invaluable.
Ok, let's whack out some quick code to show you delta values. In your render method in the GameScreen class simply put:
System.out.println(delta);
>>Epilepsy Warning<< - If you run the program now you'll see some flashing images because we haven't cleared the screen in the render method yet
Run the program and see the delta values stream onto the screen. Every new delta value is a new game tick. Start to feel the unlimited potential and opportunity to unleash your indie game creativity. You'll notice that the game just shows some weird flashing image. This is because we haven't cleared the screen. Add this to the beginning of the render method to clear the screen:
Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
Now you should just see a black screen when you run it. If you change the first 3 numbers from 0,0,0 to something else (they should be between 0 and 1) you can change the colour of the background. These are RGB values (the last value is alpha, for transparency), use an online colour picker tool to select some colours to try.
Step 7: Relax
Remember to frequently focus on something far away, stand up, stretch your arms and legs, and take a short break. You'll stay healthier and more focused for longer if you take a breather every now and then.
Aight that's enough, back to it.
Step 8: Camera
Last thing to do before we start actually coding the game I promise. We need to set up a camera and viewport so LibGDX knows we're making a 2D game and it knows how to project images up onto the screen. Don't worry if you don't understand this step, I'm not sure I properly understand it myself. Just add this code in the right places and everything will be fine.
In the GameScreen class, add some state for the width and height of the game screen. Since we're making a snake game, a portrait orientation ought to work. Remember state needs to be added inside the class declaration, and above any methods.
private int width = 600; private int height = 1000;
Next add the camera, importing Camera from badLogic:
private OrthographicCamera camera = new OrthographicCamera(width, height);
Add the viewport state - we haven't initialised it yet, also importing from badLogic:
private Viewport viewport;
We need to do something to the camera, then initialise the viewport using that edited camera. For this, we'll need a constructor, which is called whenever you build the class. It's a method like any other but it has no return type, and the name of the method is the name of the class.
public GameScreen() { camera.setToOrtho(false, width, height); viewport = new FitViewport(width, height, camera); viewport.apply(); }
The 'false' in setToOrtho means that y increases as objects move up the screen. Some prefer it the opposite way around. I don't.
A FitViewport ensures that everything is shown on screen. Not all phones will have a 10:6 aspect ratio (our 600 width and 1000 height). If a screen doesn't fit the aspect ratio, the FitViewport will scale the game down until it is all shown on screen, leaving black bars on the top and bottom. A FillViewport stretches to fill the screen, and might be useful as a HUD, but we don't need that for now.
In the render method add this at the beginning:
camera.update(); viewport.apply();
In the resize(int width, int height) method add:
viewport.update(width, height);
This updates the viewport when the game window is resized (for example if you drag the edges to make it bigger on a computer).
This is the basic camera-viewport setup you'll want for any game you make (with a different width and height if you want). Further reading on this can be found here.
Main game reference:
We want to be able to access the batch in our Main class from within the GameScreen class. We can do this by passing a reference to it in the constructor. Change the constructor to take a 'Main game' argument, and add private Main game state.
Add this state at the top:
private Main game;
Initialise it in the constructor:
public gameScreen(Main game) { this.game = game; //etc.... }
Finally go back to the main class and change it to pass a reference of itself to the new GameScreen:
this.setScreen(new GameScreen(this));
Step 9: Finally Actually Coding the Thing!
Time to put a snake on the screen. Let's create a new class called GameState that will hold our underlying logic for the snake game. Add two empty methods, one called update(float delta), and one called draw(). We'll create an instance of this in the GameScreen, and call the update and draw methods from within GameScreen.render.
Back in GameScreen add:
private GameState gameState = new GameState();
as state.
In GameScreen's render method add
gameState.update(delta);
near the top. This will call gameState's update method every tick and give it delta.
Add
gameState.draw();
after the screen clear, and remove the System.out.println while you're at it, we don't need it anymore.
The Board Outline
Let's create a square board for the game to take place on. A 30x30 board is a good choice. Add state to GameState for the board size:
private int boardSize = 30;
We'll need a ShapeRenderer to draw rectangles for us. For now, this is simpler than creating textures and loading them in. Instead, you specify the coordinates of a rectangle you want to be filled. Add this state to GameState:
private ShapeRenderer shapeRenderer = new ShapeRenderer();
We need to specify how far up our board is on the screen. To fill the screen, the board should be 600 units wide, and for a square board 600 units tall. Since we have 1000 units of height, let's put the board 400 units up to give as much space for the touch controls underneath it as possible. To make this adjustable, it's good to have it as state in GameState that can be changed:
private int yOffset = 400;
Now let's draw the board outline itself. To use shapeRenderer we'll need the reference to GameScreen's camera. We'll also need GameScreen's width and height state so we know how big the board should be. To do this, make the draw function take some more arguments:
public void draw(int width, int height, OrthographicCamera camera) {
importing OrthographicCamera from badlogic. Now we need to change GameScreen to pass it this information. In the render method change gameState.draw() to this:
gameState.draw(width, height, camera);
Back in GameState let's set up the ShapeRenderer in the draw method. Add this code in draw:
shapeRenderer.setProjectionMatrix(camera.combined); shapeRenderer.begin(ShapeRenderer.ShapeType.Filled) //rectangle drawing happens here shapeRenderer.end();
This sets up the ShapeRenderer to draw filled shapes in the correct position. To draw rectangles, we just need to add code in between the shapeRenderer.begin and shapeRenderer.end.
Do this now. Add this code in between the begin and end:
shapeRenderer.setColor(0,1,1,1); shapeRenderer.rect(300, 500, 100, 100);
To set the colour to yellow and draw a rectangle on the screen. If you run the game now you should see the rectangle appear.
The easiest way to draw the border is to draw two rectangles, one slightly bigger than the other:
Remove the old rectangle and add these:
shapeRenderer.setColor(1,1,1,1); shapeRenderer.rect(0, yOffset, width, width); shapeRenderer.setColor(0,0,0,1); shapeRenderer.rect(0+5, yOffset+5, width-5*2, width-5*2);
You should now see a board outline if the second rectangle colour is identical to the background clear colour you chose in the GameScreen class. I'm just using black for the retro appeal.
Step 10: The Snake Itself
We're going to be using a Queue to represent the Snake. Specifically, a queue of Bodypart objects, each holding an x and a y.
A queue is a data type where you can add things to the end, and take things off the front. It has a FIFO (first in first out) order, so the earlier you add something the earlier it gets taken out. Think of it as a queue in a shop. Customers come off the front of the queue to get served, and new customers get added to the end.
Using a queue as a snake gets rid of annoying issues like making the body follow the snake's path or trying to remember where the snake has been. To advance the snake, we just add a 'Bodypart' to the front and take one off the end. Easy.
Bodyparts
First, create the Bodypart class. Give it two pieces of state for x and y, and a constructor which takes three values, x,y, and boardSize.
private int x; private int y; public Bodypart(int x, int y, int boardSize) {}
By pressing Ctrl+N (Cmd N on Mac) you can automatically create a 'getter' for x and y so that we can access the coordinates safely from outside the class.
public int getX() { return x; } public int getY() { return y; }
This version of Snake is going to wrap around the edges, but it's easy to edit the code to make you die once you reach the edge. When we advance the snake we add a Bodypart in the direction the snake is going. If the Bodypart is outside the boardSize, we need to 'wrap around' using modular arithmetic.
Add this code in the constructor. The constructor here allows us to do input sanitisation, and makes it impossible to have a bodypart outside the board. The if statements are needed for negative x and y values.
this.x = x % boardSize; if (this.x<0) this.x += boardSize; this.y = y % boardSize; if (this.y<0) this.y += boardSize;
The Queue
Now go back to GameState and add some Queue state.
private Queue<mBody> = new Queue<>();
Make sure to import Queue from badlogic and not java.util.
We want to start the game with 3 Bodyparts so let's create a constructor for GameState and add them.
public GameState() { mBody.addLast(new Bodypart(15,15,boardSize)); //head mBody.addLast(new Bodypart(15,14,boardSize)); mBody.addLast(new Bodypart(15,13,boardSize)); //tail }
Now we need to create a way to draw all Bodyparts in the right place. We use our ShapeRenderer to draw the Snake.
Important: We need to put this code after the code to draw the board so that the snake draws on top of the board.
Remember to set the colour to white (or any visible colour) first:
float scaleSnake = width/boardSize; for (Bodypart bp : mBody) { shapeRenderer.rect(bp.getX()*scaleSnake, bp.getY()*scaleSnake + yOffset, scaleSnake, scaleSnake); }
The loop iterates through all Bodyparts and draws them, scaled by the scaleSnake factor which converts from the board size to the screen size.
If you run the game now you should see a 3-square-long snake on the board. Resize the window and the board should stay square.
Step 11: Make It Move!
This project's going to come together really fast now. You've done the work, time to reap the reward.
We're going to use the update method in GameState to add to the queue and take away from it. First, we need a way to limit the speed of the snake. If we add one and take one away every tick it's gonna fly across the screen faster than you can imagine. Let's make a simple timer using delta.
Add state to GameState for the timer:
private float mTimer = 0;
Now in the update method, we need to add delta to the timer every tick:
mTimer += delta;
After a preset time period, we want to reset the timer and advance the snake (update the game logic). Using a simple if statement:
if (mTimer > 0.13f) { mTimer = 0; advance(); }
And we need to create an advance() method that adds one to the snake and takes one off the end. This can be private since only GameState should call it:
private void advance() { mBody.addFirst(new Bodypart(mBody.first().getX(), mBody.first().getY()+1, boardSize)); mBody.removeLast(); }
Press Play and your snake should be moving! By changing the number in mTimer > 0.13f you can change the speed of the snake.
Next, we need a way to change direction.
Step 12: Controls
We need to create a controls class. This allows us to filter controls, for example not letting users press buttons they shouldn't, and makes it easy to rebind controls. For now, we'll use the keyboard but we'll add some touch buttons later, which will be easier with a separate controls class. Using a controls class we can make sure players don't turn back on themselves, i.e. they can't move down if they're moving up.
The Controls class will need state for the current direction and the next direction. The Snake only updates once every 0.13 seconds, which means that if the user presses two buttons in that time, we want the most recent press to become the next direction. We also need the current direction to know whether or not to allow a user to press a button.
Let's store the direction as an integer: 0,1,2,3 for up,right,down,left respectively (starting at up and going clockwise).
I really should have set some private final static int state here so that instead of, for example setting the direction to 0 for up, you set it to UP where UP = 0 like this:
private final static int UP = 0;
This would make the code much more readable, and less error-prone. I would recommend doing this for all four directions.
Controls
Add this state to Controls:
private int currentDirection; //0,1,2,3 U,R,D,L private int nextDirection;
We also need these methods:
public int getDirection() {}
public void update() {}
update() needs to be called every tick to poll the keyboard for keypresses. getDirection needs to be called every time advance() is called (every time the timer hits 0.13) so that the snake knows which direction it should be going in. Let's add the keypresses in the update() method:
In the if statements we also check the currentDirection to see if the desired keypress is allowed. For example, if the snake is moving up, it shouldn't be able to immediately move down or it would eat itself instantly. The only options really are left and right.
if(Gdx.input.isKeyPressed(Input.Keys.UP) && currentDirection != 2) nextDirection = 0; else if (Gdx.input.isKeyPressed(Input.Keys.RIGHT) && currentDirection != 3) nextDirection = 1; else if (Gdx.input.isKeyPressed(Input.Keys.DOWN) && currentDirection != 0) nextDirection = 2; else if (Gdx.input.isKeyPressed(Input.Keys.LEFT) && currentDirection != 1) nextDirection =3;
Next, add this in getDirection:
currentDirection = nextDirection; return nextDirection;
It returns the direction so that GameState knows where to put the next body part, and sets the currentDirection to the direction it just gave to GameState.
LibGDX also supports event-based input detection rather than poll-based, which you can read about here.
GameState
Go back to the GameState class so that we can make the snake change direction. We need to create an instance of the Controls class first. Add this state:
private Controls controls = new Controls();
We need to update the controls every tick so we add this to the update method:
controls.update();
Next, we'll change our advance() method. Change the code that's already in there to this:
private void advance() { int headX = mBody.first().getX(); int headY = mBody.first().getY(); switch(controls.getDirection()) { case 0: //up mBody.addFirst(new Bodypart(headX, headY+1, boardSize)); break; case 1: //right mBody.addFirst(new Bodypart(headX+1, headY, boardSize)); break; case 2: //down mBody.addFirst(new Bodypart(headX, headY-1, boardSize)); break; case 3: //left mBody.addFirst(new Bodypart(headX-1, headY, boardSize)); break; default://should never happen mBody.addFirst(new Bodypart(headX, headY+1, boardSize)); break; } mBody.removeLast(); }
Switch statements are like a series of if statements. Instead of writing if(1) else if (2) else if(3).. etc. we can just use a switch statement to clean things up a bit.
Run the game and you should be able to move the snake around with the arrow keys. Time to add food.
Step 13: Food
The Food Class
Making food appear is quite simple. Create yourself a 'Food' class.
We need to be able to get the x and y location of the food so we can draw it, and we need to be able to randomise the food's position.
So let's add some state for x and y:
private int x; private int y;
And we need getters for these, press Ctrl+N (Cmd N):
public int getX() { return x; } public int getY() {return y; }
To randomise the position of the food, it needs to know the boardSize. Let's use LibGDX's own MathUtils random method, which simplifies generating a random integer between two points. MathUtils.random(int range) provides a random number between 0 and range inclusive: (import MathUtils from badlogic)
public void randomisePos(int boardSize) { x = MathUtils.random(boardSize-1); y = MathUtils.random(boardSize-1); }
Finally, we need a constructor to create the food and randomise its position. We need to give the constructor a board size so it knows where it can legally initially place the food:
public Food(int boardSize) { randomisePos(boardSize); }
And we are done. Let's head back to GameState and create the food object, and find a way to draw it.
GameState
Create and initialise state for the food with the other state (but underneath boardSize):
private Food mFood = new Food(boardSize);
In the draw method add this to draw the food. Make sure it is under the board outline so it get's drawn on top, and make sure the colour is set to white or some other visible colour. We can use the same scaleSnake factor to draw our food so make sure this gets put under the scaleSnake initialisation.
shapeRenderer.rect(mFood.getX() * scaleSnake, mFood.getY()*scaleSnake + yOffset, scaleSnake, scaleSnake);
If you run the game now you should see the food appear in a random place.
Time to add the ability to eat the food.
Eating Food
Every time the snake advances we need to check if its head is in the same location as the food. If it is, we add one to the snake's length and randomise the food position.
We need some state to hold the current length of the snake. Add this as state:
private int snakeLength = 3;
In advance, underneath the switch statement, we'll detect if the newly placed head is touching the food. If it is, we increment the snakeLength and randomise the food position:
if (mBody.first().getX() == mFood.getX() && mBody.first().getY() == mFood.getY()) { snakeLength++; mFood.randomisePos(boardSize); }
This is fine but the snake doesn't ever get any longer because we always remove the tail. We need to detect if the current length of the snake is less than the 'snakeLength' variable, and if it is, we do not remove one from the tail. In other words, we only remove the last element if the current size of the snake is equal to 'snakeLength'.
if (mBody.size - 1 == snakeLength) { mBody.removeLast(); }
You'll notice that we use 'mBody.size - 1'. This is because this statement comes after the switch statement that adds one to the head, so we need to account for that extra bodypart.
Press play and you should be able to eat food and get longer.
Step 14: Death
It's not much of a game yet. There's no challenge if there's no way to fail, so let's add a fail condition.
If the head touches another part of the body, the length of the snake should reset to 3. This code should be put in the advance() method, which is called everytime the snake moves forward.
for (int i = 1; i<mbody.size; i++) { if (mBody.get(i).getX() == mBody.first().getX() && mBody.get(i).getY() == mBody.first().getY()) { snakeLength = 3; } }
Our mBody Queue uses zero-based indexing. We initialise int i as 1 so that it doesn't check if the xy of the head matches the xy of the head, as this would always be true.
We need to add this just before the if() statement that checks removes the last bodyPart from the Queue so that if the player has 'died' we can remove all extra bodyParts in the queue. We do this first by changing == to >=, because it is now possible for the actual body length to be greater than the desired length (when the snake dies). We then need to change the if statement to a while statement, which will keep removing body parts until the snake reaches length 3. Without the 'while', only one bodyPart would be removed per advance method, which doesn't actually shorten the snake at all.
while (mBody.size - 1 >= snakeLength) { mBody.removeLast(); }
Press play and test out the functioning snake game!
Congratulations on the start of your lucrative indie career. From here on out, we'll be adding some touch controls, colours, and then deploying the game to Android.
Step 15: Touch Controls
Let's just implement some simple touch controls using a DPad, which we'll draw onto the screen using rectangles.
Controls
We need to change our update() method in the Controls class to take a Viewport argument. The viewport is needed to convert screen coordinates of a touch to in-game coordinates. Add the Viewport argument:
public void update(Viewport viewport) {
Unfortunately, our viewport is in the GameScreen, but controls.update happens in GameState. An easy way to get around this would be to pass the viewport to our gameState.update(), then pass it down to controls.update().
GameScreen
Add viewport to the gameState.update arguments:
gameState.update(delta, viewport);
GameState
Add viewport to the update arguments, then pass it to controls.update():
public void update(float delta, Viewport viewport) { //update game logic mTimer += delta; controls.update(viewport); if (mTimer > 0.13f) { mTimer = 0; advance(); } }
Controls
Back to the controls class, let's add some touch detection. On a computer, you click the screen to send a touch, but on phones, you touch the screen.
First, add some Vector2 state to Controls:
private Vector2 touch = new Vector2();
This will store the two coordinates of the touch.
We use this code to detect touches:
if (Gdx.input.isTouched()) { touch.x = Gdx.input.getX(); touch.y = Gdx.input.getY(); viewport.unproject(touch); }
If the screen is touched, it sets the touch vector to the coordinates of the touch. It then 'unprojects' the touch using the viewport. This just converts the screen coordinates of the phone/computer to the in-game coordinates.
We have touch coordinates, we just need a way to make some buttons. Putting buttons in their own class is probably a good idea for larger projects, but for now, we can just put buttons in the Controls class. We'll describe the buttons as Rectangles, and we can use the Rectangle.contains method to check if the touch Vector is within the Rectangle.
We need four Rectangles, one for each direction. Add this as state:
private Rectangle upBox = new Rectangle(235, 265, 130, 130); private Rectangle downBox = new Rectangle(235, 5, 130, 130); private Rectangle leftBox = new Rectangle(65,135,130,130); private Rectangle rightBox = new Rectangle(365,135,130,130);
Now we just need to check if each of these boxes contains the touch. To do this we just add to our current keyboard-detection if statements. Watch your brackets. Make sure the OR statement is enclosed.
if ((Gdx.input.isKeyPressed(Input.Keys.UP) || upBox.contains(touch)) && currentDirection != 2) nextDirection = 0; else if ((Gdx.input.isKeyPressed(Input.Keys.RIGHT) || rightBox.contains(touch)) && currentDirection != 3) nextDirection = 1; else if ((Gdx.input.isKeyPressed(Input.Keys.DOWN) || downBox.contains(touch)) && currentDirection != 0) nextDirection = 2; else if ((Gdx.input.isKeyPressed(Input.Keys.LEFT) || leftBox.contains(touch)) && currentDirection != 1) nextDirection =3;
GameState
Finally, we need to draw the buttons using our ShapeRenderer. Add these after the colour has been changed from the background colour:
//buttons shapeRenderer.rect(235, 265, 130, 135); shapeRenderer.rect(235, 0, 130, 135); shapeRenderer.rect(105,135,130,130); shapeRenderer.rect(365,135,130,130);
(I know these aren't perfectly square but 3 doesn't go into 400 ok)
Now we have a functional game that would run on Android! Run it and make sure you can click the buttons to change direction. Now let's add some colour to the snake.
Step 16: Pretty Colours
Making the snake and controls a little more colourful is pretty simple. All we need to do is make the rgb value depend on the sine function.
GameState
Add this state to GameState:
private float colourCounter = 0;
Then in the update() method we increment the colour counter with delta:
colourCounter += delta;
Finally, in the draw() method we need to change the shapeRenderer colour to depend on the colourCounter:
shapeRenderer.setColor(MathUtils.sin(colourCounter),-MathUtils.sin(colourCounter),1,1);
Play around with this using sin and cos to come up with something you like. Be careful of all three rgb values being 0 at once, because then the snake might go invisible (if your background is black). You can use Math.abs() to turn a negative value into a positive one (because sin and cos go negative half the time). You can also add a scaled amount of delta to colourCounter if you want the colours to switch faster or slower, e.g. colourCounter += 2*delta. Get creative, and remember you can change the colour of the controls and board outline with this method too.
Step 17: Android Settings
There are a couple of things that need to be changed to make the game run properly on a phone.
Screen Orientation:
LibGDX defaults to a landscape orientation but we want portrait. In the file explorer on the left open android->AndroidManifest.xml. Look for the android:screenOrientation line and change it to portrait:
android:screenOrientation="portrait"
Then open src->your.package->AndroidLauncher.java and add this line to hide the status bar and navigation buttons:
config.useImmersiveMode = true;
This should come in-between the initialisation of the config variable and the initialize() method.
Step 18: Test It Out
Before exporting to Android it's a good idea to test it out on a virtual phone. Luckily it's pretty easy to do that from inside IntelliJ itself.
At the top, change the configuration from 'Desktop' to 'Android'. The Android configuration should have automatically been created for you. If it hasn't, follow these steps to create it yourself:
Skip this part if you already have the Android Configuration:
- Click desktop -> edit configuration
- Click on the plus icon in the top left, then 'Android App'
- Name it 'android'
- Change the module to 'android'
The Android Emulator:
Press the run button while the Android config is selected and you should see a 'Select Deployment Target' window pop up. We need to create a new virtual device, so press that button. You can choose any of these phones you like but I used the Nexus 5. Click next, next, finish, leaving all the options as they are. Now select your chosen phone in the original window and press ok.
You should see a virtual phone appear. If it is landscape, you can use the rotation buttons on the right to change its orientation. It runs a working version of Android, and you can use the touchscreen with the mouse. Give it a short while to load, and your snake game will automatically be installed and launched. Check that the game works as it should, i.e. everything is visible, it's in the right orientation, the buttons work, etc.
If everything is fine, you're ready to export!
Step 19: Exporting
We'll do this from the command line, although there are some Eclipse-specific instructions here. Open up your command line and navigate to the root folder of your project - the folder that contains the android, build, core, desktop, and gradle folders. Now execute the following code to package the project:
./gradlew android:assembleRelease
This will create an unsigned apk, which will work but your phone will need to have APK source checking disabled to install it. Let's sign the app so you and others can install it more easily.
There's a lot of info here about signing. I'll walk you through doing it via the command line.
The simple way to do this is copy across the required files from the Android SDK to your build folder. Open two file explorers. In one of them navigate to yourProject->android->build->outputs->apk. You should see an unsigned apk in there from the previous code. In the other window navigate to the location of the Android SDK. For me this was in users->myUser->Library->android->sdk.
Then navigate to build-tools->27.0.2. In this folder there should be many executables, we're interested in apksigner and zipalign. Copy across the apksigner and zipalign execs, and also copy across the lib folder because the execs depend on it.
Go back to the command line and navigate to the apk folder (android/build/outputs/apk). First we need to align the zip using:
./zipalign -v -p 4 android-release-unsigned.apk android-unsigned-aligned.apk
Run this code and you'll see another apk appear, this one aligned.
To sign the apk we need to create a certificate. This makes sure that if you update the app, you are the real developer because you've signed it with your certificate. Because of this, you need to keep your certificate safe and private.
We can use keytool to generate a certificate. This comes with the Java SDK, so you should just be able to run it from the command line.
keytool -genkey -v -keystore chooseName.jks -keyalg RSA -keysize 2048 -validity 10000 -alias chooseName2
Run this code from the apk folder, replacing chooseName and chooseName2 with names of your choice. chooseName.jks is the file name, and chooseName2 is the alias.
Press enter and answer the questions it asks, setting a strong password. You should see yourKey.jks appear in the apk folder. Now we can sign the apk.
Run this in the command line, changing yourName to the name of the keystore you just generated:
./apksigner sign --ks yourName.jks --out release.apk android-unsigned-aligned.apk
Finally, check that the apk signed properly using:
./apksigner verify release.apk
If nothing happens when you press enter, you're done! You can send the apk to your phone and install it now. You'll need to allow installation from unknown sources in your phone's options menu. This was under the security settings for me.
Step 20: And We Are Done - What Next
The journey was long and arduous, but you now have a working Android app running on your phone. This is just the start. There's much more to learn about LibGDX and much more you can add to this game.
Things to Explore:
- Textures - using images instead of the ShapeRenderer
- AssetManager - helps when you have many textures and sounds to keep track of
- Texture Atlas - improves performance when you have many textures
- Sounds
- Menu screens
- Score and High Score - using 'preferences'
- Gesture Controls
Download my version of the Snake app on Android here to get an idea of things to add to make this app better.
And there's much more. As a starting point, here are two tutorials you should work through and some helpful pages:
And finally a link to the Official Documentation.
Get creative. Build something cool.
~Keir
Participated in the
Epilog Challenge 9
daryllukas made it!
10 Discussions
2 months ago on Step 2
can you help me?
Question 12 months ago on Step 2
My libGDX somehow doesn't work.
Generating app in C:\Users\Buzivagyok\Desktop\snk
Executing 'C:\Users\Buzivagyok\Desktop\snk/gradlew.bat clean --no-daemon idea'
To honour the JVM settings for this build a new JVM will be forked. Please consider using the daemon:...
Daemon will be stopped at the end of the build stopping after processing
WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation'.
It will be removed at the end of 2018
:android:clean UP-TO-DATE
:core:clean UP-TO-DATE
:desktop:clean UP-TO-DATE
:ideaModule
:ideaProject
:ideaWorkspace
:idea
:android:ideaModule
:android:idea
:core:ideaModule
:core:idea
:desktop:ideaModule
:desktop:idea
Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
See...
BUILD SUCCESSFUL in 1m 25s
9 actionable tasks: 6 executed, 3 up-to-date
Done!
To import in Eclipse: File -> Import -> General -> Existing Projects into Workspace
To import to Intellij IDEA: File -> Open -> YourProject.ipr
Any idea?
Answer 11 months ago
Have you tried importing this into the IDE? If you set up the Desktop Application in further steps, does it run and show the badlogic logo?
Reply 11 months ago
No it doesn't. I get an error: WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation'.
Reply 11 months ago
Try this
You might need to try adding that code to the project's build.gradle
Reply 11 months ago
If I start the desktop application i get the: Could not execute build using Gradle distribution '' error.
Reply 11 months ago
Hmm, what gradle version are you using?
Reply 11 months ago
I am really a newbie. Is it how i should check it?
Reply 11 months ago
I am really a newbie. How do i check that?
1 year ago
The snake game is addictive and I can't believe you did this in 40 minutes! | https://www.instructables.com/id/How-to-Make-an-Android-Game-Snake/ | CC-MAIN-2019-35 | en | refinedweb |
Just about every project needs to interface with a REST API at some stage. Axios is a lightweight HTTP client based on the $http service within Angular.js v1.x and similar to the Fetch API.
Axios is promise-based and thus we can take advantage of async and await for more readable asynchronous code. We can also intercept and cancel requests, and there’s built-in client side protection against cross site request forgery. But the best part about Axios? The easy to use API!
Using it inside a React project is simple! In this example we’ll use Axios to access the common JSON Placeholder API within a React application. We can start by adding Axios to our project:
# Yarn $ yarn add axios # npm $ npm install axios --save
🐊 Recommended courses ⤵️⚛️ Learn React and React Hooks using a project-based approach
Video Please!
If video is more your thing, here’s one I recorded about this very topic:
GET Requests
If we then create a new component named PersonList, we’d be able to hook into the
componentDidMount lifecycle hook and perform a GET request after importing
axios.
import React from 'react'; import axios from 'axios'; export default class PersonList extends React.Component { state = { persons: [] } componentDidMount() { axios.get(``) .then(res => { const persons = res.data; this.setState({ persons }); }) } render() { return ( <ul> { this.state.persons.map(person => <li>{person.name}</li>)} </ul> ) } }
Using
axios.get(url) we then get a promise which returns a response object. As we’re looking for the response data, we’ve assigned the value of
person to
res.data.
We can also get other information about our request such as the status code under
res.status or more information inside of
res.request.
POST Requests
We can handle other verbs such as POST and PUT in a similar fashion. Let’s create a form that allows for user input and subsequently POST the content to an API:
import React from 'react'; import axios from 'axios'; export default class PersonList extends React.Component { state = { name: '', } handleChange = event => { this.setState({ name: event.target.value }); } handleSubmit = event => { event.preventDefault(); const user = { name: this.state.name }; axios.post(``, { user }) .then(res => { console.log(res); console.log(res.data); }) } render() { return ( <div> <form onSubmit={this.handleSubmit}> <label> Person Name: <input type="text" name="name" onChange={this.handleChange} /> </label> <button type="submit">Add</button> </form> </div> ) } }
Using POST gives us that same response object with information that we can use inside of our
then call.
DELETE Requests
We can delete items from our API using
axios.delete and passing the URL as a parameter. Let’s change our form to delete a user instead of adding a new one:
import React from 'react'; import axios from 'axios'; export default class PersonList extends React.Component { state = { id: '', } handleChange = event => { this.setState({ id: event.target.value }); } handleSubmit = event => { event.preventDefault(); axios.delete(`{this.state.id}`) .then(res => { console.log(res); console.log(res.data); }) } render() { return ( <div> <form onSubmit={this.handleSubmit}> <label> Person ID: <input type="text" name="id" onChange={this.handleChange} /> </label> <button type="submit">Delete</button> </form> </div> ) } }
Once again our
res object provides us with information about our request.
Base Instance
Axios allows us to define a base instance in which we can define a URL and any other configuration elements. Let’s create a file named
api.js and export a new
axios instance with these defaults:
api.js
import axios from 'axios'; export default axios.create({ baseURL: `` });
It can then be used inside of our component by importing our new instance like so:
// Omitted import API from '../api'; export default class PersonList extends React.Component { handleSubmit = event => { event.preventDefault(); API.delete(`users/${this.state.id}`) .then(res => { console.log(res); console.log(res.data); }) } }
Using async and await
We can make working with promises even simpler with
async and
await. The
await keyword resolves the promise and returns the value which we can assign to a variable. Here’s an example:
handleSubmit = async event => { event.preventDefault(); // Promise is resolved and value is inside of the response const. const response = await API.delete(`users/${this.state.id}`); console.log(response); console.log(response.data); }; | https://alligator.io/react/axios-react/ | CC-MAIN-2019-35 | en | refinedweb |
AR Face Tracking Tutorial for iOS: Getting Started
In this tutorial, you’ll learn how to use AR Face Tracking to track your face using a TrueDepth camera, overlay emoji on your tracked face, and manipulate the emoji based on facial expressions you make.
Version
- Swift 4.2, iOS 12, Xcode 10
Picture this. You have just eaten the most amazing Korean BBQ you’ve ever had and it’s time to take a selfie to commemorate the occasion. You whip out your iPhone, make your best duck-face and snap what you hope will be a selfie worthy of this meal. The pic comes out good — but it’s missing something. If only you could put an emoji over your eyes to really show how much you loved the BBQ. Too bad there isn’t an app that does something similar to this. An app that utilizes AR Face Tracking would be awesome.
Good news! You get to write an app that does that!
In this tutorial, you’ll learn how to:
- Use AR Face Tracking to track your face using a TrueDepth camera.
- Overlay emoji on your tracked face.
- Manipulate the emoji based on facial expressions you make.
Are you ready? Then pucker up those lips and fire up Xcode, because here you go!
Getting Started
For this tutorial, you’ll need an iPhone with a front-facing, TrueDepth camera. At the time of writing, this means an iPhone X, but who knows what the future may bring?
You may have already downloaded the materials for this tutorial using the Download Materials link at the top or bottom of this tutorial and noticed there is no starter project. That’s not a mistake. You’re going to be writing this app — Emoji Bling — from scratch!
Launch Xcode and create a new project based on the Single View App template and name it Emoji Bling.
The first thing you should do is to give the default
ViewController a better name. Select ViewController.swift in the Project navigator on the left.
In the code that appears in the Standard editor, right-click on the name of the class,
ViewController, and select Refactor ▸ Rename from the context menu that pops up.
Change the name of the class to
EmojiBlingViewController and press Return or click the blue Rename button.
Since you’re already poking around EmojiBlingViewController.swift, go ahead and add the following import to the top:
import ARKit
You are, after all, making an augmented reality app, right?
Next, in Main.storyboard, with the top level View in the Emoji Bling View Controller selected, change the class to ARSCNView.
ARSCNView is a special view for displaying augmented reality experiences using SceneKit content. It can show the camera feed and display
SCNNodes.
After changing the top level view to be an
ARSCNView, you want to create an
IBOutlet for the view in your
EmojiBlingViewController class.
To do this, bring up the Assistant editor by clicking on the button with the interlocking rings.
This should automatically bring up the contents of EmojiBlingViewController.swift in the Assistant editor. If not, you can Option-click on it in the Project navigator to display it there.
Now, Control-drag from the
ARSCNView in the storyboard to just below the
EmojiBlingViewController class definition in EmojiBlingViewController.swift and name the outlet
sceneView.
Before you can build and run, a little bit of code is needed to display the camera feed and start tracking your face.
In EmojiBlingViewController.swift, add the following functions to the
EmojiBlingViewController class:
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // 1 let configuration = ARFaceTrackingConfiguration() // 2 sceneView.session.run(configuration) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // 1 sceneView.session.pause() }
Right before the view appears, you:
- Create a configuration to track a face.
- Run the face tracking configuration using the built in
ARSessionproperty of your
ARSCNView.
Before the view disappears, you make sure to:
- Pause the AR session.
There is a teensy, tiny problem with this code so far.
ARFaceTrackingConfiguration is only available for phones with a front-facing TrueDepth camera. You need to make sure you check for this before doing anything.
In the same file, add the following to the end of the
viewDidLoad() function, which should already be present:
guard ARFaceTrackingConfiguration.isSupported else { fatalError("Face tracking is not supported on this device") }
With this in place, you check to make sure that the device supports face tracking (i.e., has a front-facing TrueDepth camera), otherwise stop. This is not a graceful way to handle this, but as this app only does face tracking, anything else would be pointless!
Before you run your app, you also need to specify a reason for needing permission to use the camera in the Info.plist.
Select Info.plist in the Project navigator and add an entry with a key of
Privacy - Camera Usage Description. It should default to type
String. For the value, type EmojiBling needs access to your camera in order to track your face.
FINALLY. It’s time to build and run this puppy… er… app… appuppy?
When you do so, you should see your beautiful, smiling face staring right back at you.
OK, enough duck-facing around. You’ve got more work to do!
Face Anchors and Geometries
You’ve already seen
ARFaceTrackingConfiguration, which is used to configure the device to track your face using the TrueDepth camera. Cool.
But what else do you need to know about face tracking?
Three very important classes you’ll soon make use of are
ARFaceAnchor,
ARFaceGeometry and
ARSCNFaceGeometry.
ARFaceAnchor inherits from
ARAnchor. If you’ve done anything with ARKit before, you know that
ARAnchors are what make it so powerful and simple. They are positions in the real world tracked by ARKit, which do not move when you move your phone.
ARFaceAnchors additionally include information about a face, such as topology and expression.
ARFaceGeometry is pretty much what it sounds like. It’s a 3D description of a face including
vertices and
textureCoordinates.
ARSCNFaceGeometry uses the data from an
ARFaceGeometry to create a
SCNGeometry, which can be used to create SceneKit nodes — basically, what you see on the screen.
OK, enough of that. Time to use some of these classes. Back to coding!
Adding a Mesh Mask
On the surface, it looks like you’ve only turned on the front-facing camera. However, what you don’t see is that your iPhone is already tracking your face. Creepy, little iPhone.
Wouldn’t it be nice to see what the iPhone is tracking? What a coincidence, because that’s exactly what you’re going to do next!
Add the following code after the closing brace for the
EmojiBlingViewController class definition:
// 1 extension EmojiBlingViewController: ARSCNViewDelegate { // 2 func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? { // 3 guard let device = sceneView.device else { return nil } // 4 let faceGeometry = ARSCNFaceGeometry(device: device) // 5 let node = SCNNode(geometry: faceGeometry) // 6 node.geometry?.firstMaterial?.fillMode = .lines // 7 return node } }
In this code you:
- Declare that
EmojiBlingViewControllerimplements the
ARSCNViewDelegateprotocol.
- Define the
renderer(_:nodeFor:)method from the protocol.
- Ensure the Metal device used for rendering is not nil.
- Create a face geometry to be rendered by the Metal device.
- Create a SceneKit node based on the face geometry.
- Set the fill mode for the node’s material to be just lines.
- Return the node.
ARSCNFaceGeometryis only available in SceneKit views rendered using Metal, which is why you needed to pass in the Metal device during its initialization. Also, this code will only compile if you’re targetting real hardware; it will not compile if you target a simulator.
Before you can run this, you need to set this class to be the
ARSCNView‘s delegate.
At the end of the
viewDidLoad() function, add:
sceneView.delegate = self
OK, time for everyone’s favorite step. Build and run that app!
Updating the Mesh Mask
Did you notice how the mesh mask is a bit… static? Sure, when you move your head around, it tracks your facial position and moves along with it, but what happens when you blink or open your mouth? Nothing.
How disappointing.
Luckily, this is easy to fix. You just need to add another
ARSCNViewDelegate method!
At the end of your
ARSCNViewDelegate extension, add the following method:
// 1 func renderer( _ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) { // 2 guard let faceAnchor = anchor as? ARFaceAnchor, let faceGeometry = node.geometry as? ARSCNFaceGeometry else { return } // 3 faceGeometry.update(from: faceAnchor.geometry) }
Here, you:
- Define the
didUpdateversion of the
renderer(_:didUpdate:for:)protocol method.
- Ensure the anchor being updated is an
ARFaceAnchorand that the node’s geometry is an
ARSCNFaceGeometry.
- Update the
ARSCNFaceGeometryusing the
ARFaceAnchor’s
ARFaceGeometry
Now, when you build and run, you should see the mesh mask form and change to match your facial expressions.
Emoji Bling
If you haven’t already done so, go ahead and download the material for this tutorial via the button at the top or bottom of the tutorial.
Inside, you’ll find a folder called SuperUsefulCode with some Swift files. Drag them to your project just below EmojiBlingViewController.swift. Select Copy items if needed, Create groups, and make sure that the Emoji Bling target is selected
StringExtension.swift includes an extension to
String that can convert a
String to a
UIImage.
EmojiNode.swift contains a subclass of
SCNNode called
EmojiNode, which can render a
String. It takes an array of
Strings and can cycle through them as desired.
Feel free to explore the two files, but a deep dive into how this code works is beyond the scope of this tutorial.
With that out of the way, it’s time to augment your nose. Not that there’s anything wrong with it. You’re already such a beautiful person. :]
At the top of your
EmojiBlingViewController class, define the following constants:
let noseOptions = ["👃", "🐽", "💧", " "]
The blank space at the end of the array is so that you have the option to clear out the nose job. Feel free to choose other nose options, if you want.
Next, add the following helper function to your
EmojiBlingViewController class:
func updateFeatures(for node: SCNNode, using anchor: ARFaceAnchor) { // 1 let child = node.childNode(withName: "nose", recursively: false) as? EmojiNode // 2 let vertices = [anchor.geometry.vertices[9]] // 3 child?.updatePosition(for: vertices) }
Here, you:
- Search
nodefor a child whose name is “nose” and is of type
EmojiNode
- Get the vertex at index 9 from the
ARFaceGeometryproperty of the
ARFaceAnchorand put it into an array.
- Use a member method of
EmojiNodeto update it’s position based on the vertex. This
updatePosition(for:)method takes an array of vertices and sets the node’s position to their center.
ARFaceGeometryhas 1220 vertices in it and index 9 is on the nose. This works, for now, but you’ll briefly read later the dangers of using these index constants and what you can do about it.
It might seem silly to have a helper function to update a single node, but you will beef up this function later and rely heavily on it.
Now you just need to add an
EmojiNode to your face node. Add the following code just before the
return statement in your
renderer(_:nodeFor:) method:
// 1 node.geometry?.firstMaterial?.transparency = 0.0 // 2 let noseNode = EmojiNode(with: noseOptions) // 3 noseNode.name = "nose" // 4 node.addChildNode(noseNode) // 5 updateFeatures(for: node, using: faceAnchor)
In this code, you:
- Hide the mesh mask by making it transparent.
- Create an
EmojiNodeusing your defined nose options.
- Name the nose node, so it can be found later.
- Add the nose node to the face node.
- Call your helper function that repositions facial features.
You’ll notice a compiler error because
faceAnchor is not defined. To fix this, change the
guard statement at the top of the same method to the following:
guard let faceAnchor = anchor as? ARFaceAnchor, let device = sceneView.device else { return nil }
There is one more thing you should do before running your app. In
renderer(_:didUpdate:for:), add a call to
updateFeatures(for:using:) just before the closing brace:
updateFeatures(for: node, using: faceAnchor)
This will ensure that, when you scrunch your face up or wiggle your nose, the emoji’s position will update along with your motions.
Now it’s time to build and run!
Changing the Bling
Now, that new nose is fine but maybe some days you feel like having a different nose?
You’re going to add code to cycle through your nose options when you tap on them.
Open Main.storyboard and find the Tap Gesture Recognizer. You can find that by opening the Object Library at the top right portion of your storyboard.
Drag this to the
ARSCNView in your View controller.
With Main.storyboard still open in the Standard editor, open EmojiBlingViewController.swift in the Assistant editor just like you did before. Now Control-drag from the Tap Gesture Recognizer to your main
EmojiBlingViewController class.
Release your mouse and add an Action named
handleTap with a type of
UITapGestureRecognizer.
Now, add the following code to your new
handleTap(_:) method:
// 1 let location = sender.location(in: sceneView) // 2 let results = sceneView.hitTest(location, options: nil) // 3 if let result = results.first, let node = result.node as? EmojiNode { // 4 node.next() }
Here, you:
- Get the location of the tap within the
sceneView.
- Perform a hit test to get a list of nodes under the tap location.
- Get the first (top) node at the tap location and make sure it’s an
EmojiNode.
- Call the
next()method to switch the
EmojiNodeto the next option in the list you used, when you created it.
It is now time. The most wonderful time. Build and run time. Do it! When you tap on your emoji nose, it changes.
More Emoji Bling
With a newfound taste for emoji bling, it’s time to add the more bling.
At the top of of your
EmojiBlingViewController class, add the following constants just below the
noseOptions constant:
let eyeOptions = ["👁", "🌕", "🌟", "🔥", "⚽️", "🔎", " "] let mouthOptions = ["👄", "👅", "❤️", " "] let hatOptions = ["🎓", "🎩", "🧢", "⛑", "👒", " "]
Once again, feel free to choose a different emoji, if you so desire.
In your
renderer(_:nodeFor:) method, just above the call to
updateFeatures(for:using:), add the rest of the child node definitions:
let leftEyeNode = EmojiNode(with: eyeOptions) leftEyeNode.name = "leftEye" leftEyeNode.rotation = SCNVector4(0, 1, 0, GLKMathDegreesToRadians(180.0)) node.addChildNode(leftEyeNode) let rightEyeNode = EmojiNode(with: eyeOptions) rightEyeNode.name = "rightEye" node.addChildNode(rightEyeNode) let mouthNode = EmojiNode(with: mouthOptions) mouthNode.name = "mouth" node.addChildNode(mouthNode) let hatNode = EmojiNode(with: hatOptions) hatNode.name = "hat" node.addChildNode(hatNode)
These facial feature nodes are just like the
noseNode you already defined. The only thing that is slightly different is the line that sets the
leftEyeNode.rotation. This causes the node to rotate 180 degrees around the y-axis. Since the
EmojiNodes are visible from both sides, this basically mirrors the emoji for the left eye.
If you were to run the code now, you would notice that all the new emojis are at the center of your face and don’t rotate along with your face. This is because the
updateFeatures(for:using:) method only updates the nose so far. Everything else is placed at the origin of the head.
You should really fix that!
At the top of the file, add the following constants just below your
hatOptions:
let features = ["nose", "leftEye", "rightEye", "mouth", "hat"] let featureIndices = [[9], [1064], [42], [24, 25], [20]]
features is an array of the node names you gave to each feature and
featureIndices are the vertex indexes in the
ARFaceGeometry that correspond to those features (remember the magic numbers?).
You’ll notice that the “mouth” has two indexes associated with it. Since an open mouth is a hole in the mesh mask, the best way to position a mouth emoji is to average the position of the top and bottom lips.
ARFaceGeometryhas 1220 vertices, but what happens if Apple decides it wants a high resolution? Suddenly, these indexes may no longer correspond to what you expect. One possible, robust solution would be to use Apple’s Vision framework to initially detect facial features and map their locations to the nearest vertices on an
ARFaceGeometry
Next, replace your current implementation of
updateFeatures(for:using:) with the following:
// 1 for (feature, indices) in zip(features, featureIndices) { // 2 let child = node.childNode(withName: feature, recursively: false) as? EmojiNode // 3 let vertices = indices.map { anchor.geometry.vertices[$0] } // 4 child?.updatePosition(for: vertices) }
This looks very similar, but there are some changes to go over. In this code, you:
- Loop through the
featuresand
featureIndexesthat you defined at the top of the class.
- Find the the child node by the feature name and ensure it is an
EmojiNode.
- Map the array of indexes to an array of vertices using the
ARFaceGeometryproperty of the
ARFaceAnchor.
- Update the child node’s position using these vertices.
Go a head and build and run your app. You know you want to.
Blend Shape Coefficients
ARFaceAnchor contains more than just the geometry of the face. It also contains blend shape coefficients. Blend shape coefficients describe how much expression your face is showing. The coefficients range from 0.0 (no expression) to 1.0 (maximum expression).
For instance, the
ARFaceAnchor.BlendShapeLocation.cheekPuff coefficient would register
0.0 when your cheeks are relaxed and
1.0 when your cheeks are puffed out to the max like a blowfish! How… cheeky.
There are currently 52 blend shape coefficients available. Check them out in Apple’s official documentation.
Control Emoji With Your Face!
After reading the previous section on blend shape coefficients, did you wonder if you could use them to manipulate the emoji bling displayed on your face? The answer is yes. Yes, you can.
Left Eye Blink
In
updateFeatures(for:using:), just before the closing brace of the
for loop, add the following code:
// 1 switch feature { // 2 case "leftEye": // 3 let scaleX = child?.scale.x ?? 1.0 // 4 let eyeBlinkValue = anchor.blendShapes[.eyeBlinkLeft]?.floatValue ?? 0.0 // 5 child?.scale = SCNVector3(scaleX, 1.0 - eyeBlinkValue, 1.0) // 6 default: break }
Here, you:
- Use a
switchstatement on the feature name.
- Implement the
casefor
leftEye.
- Save off the x-scale of the node defaulting to 1.0.
- Get the blend shape coefficient for
eyeBlinkLeftand default to 0.0 (unblinked) if it’s not found.
- Modify the y-scale of the node based on the blend shape coefficient.
- Implement the default
caseto make the
switchstatement exhaustive.
Simple enough, right? Build and run!
Right Eye Blink
This will be very similar to the code for the left eye. Add the following
case to the same
switch statement:
case "rightEye": let scaleX = child?.scale.x ?? 1.0 let eyeBlinkValue = anchor.blendShapes[.eyeBlinkRight]?.floatValue ?? 0.0 child?.scale = SCNVector3(scaleX, 1.0 - eyeBlinkValue, 1.0)
Build and run your app again, and you should be able to blink with both eyes!
Open Jaw
Currently, in the app, if you open your mouth, the mouth emoji stays between the lips, but no longer covers the mouth. It’s a bit odd, wouldn’t you say?
You are going to fix that problem now. Add the following
case to the same
switch statement:
case "mouth": let jawOpenValue = anchor.blendShapes[.jawOpen]?.floatValue ?? 0.2 child?.scale = SCNVector3(1.0, 0.8 + jawOpenValue, 1.0)
Here you are using the
jawOpen blend shape, which is
0.0 for a closed jaw and
1.0 for an open jaw. Wait a second… can’t you have your jaw open but still close you mouth? True; however, the other option,
mouthClose, doesn’t seem to work as reliably. That’s why you’re using
.jawOpen.
Go ahead and build and run your app one last time, and marvel at your creation.
Where to Go From Here?
Wow, that was a lot of work! Congratulations are in order!
You’ve essentially learned how to turn facial expressions into input controls for an app. Put aside playing around with emoji for a second. How wild would it be to create an app in which facial expressions became shortcuts to productivity? Or how about game where blinking left and right causes the character to move and puffing out your cheeks causes the character to jump? No more tapping the screen like an animal!
If you want, you can download the final project using the Download Materials link at the top or bottom of this tutorial.
We hope you enjoyed this face-tracking tutorial. Feel free to tweet out screenshots of your amazing emoji bling creations!
Want to go even deeper into ARKit? You’re in luck. There’s a book for that!™ Check out ARKit by Tutorials, brought to you by your friendly neighborhood raywenderlich.com team.
If you have any questions or comments, please join the forum discussion below! | https://www.raywenderlich.com/5491-ar-face-tracking-tutorial-for-ios-getting-started | CC-MAIN-2019-35 | en | refinedweb |
In this article we will see how to use the ILUSING directive to declare namespaces in your COBOL.NET programs using Micro Focus.
Latest Tips & Tricks Articles - Page 4
Introducing the Entity Framework
The Entity Framework provides a .NET class-based model of a data store, letting you query the model with LINQ, while the model do the background grunt work of contacting the data store to add, update, or delete data.
Using Team Build to Build Database Projects
Customize the Team Build project file to automatically deploy the database build script to a target database.
Install Dummy SSL certificate
If you need an SSL certificate in a testing environment only for testing purposes and not actual verification and authentication, then this article will show you how to create a dummy cert
Creating Flexible Constant Fields
Discover how to use constant fields without having to hard code the values into the class.
TIP: Closing your WCF Connections properly
This tip looks at properly closing a WCF connection from your application - whether you're using the proxy classes or a ChannelFactory.. | https://www.codeguru.com/csharp/.net/net_general/tipstricks/18/ | CC-MAIN-2019-35 | en | refinedweb |
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
select customer and get specific fields value
I'm trying to get 'title' automatically when customer will select. can anyone help me?
class res_partner(osv.osv):
_name = 'project.task'
_inherit = 'project.task'
_columns = {
'partner_id': fields.many2one('res.partner', string='Employees', groups='base.group_user'),
'title':fields.char('Tte'),
}
def onchange_partner_id(self, cr, uid, ids, partner_id, context=None):
if partner_id:
partner_id = self.pool.get('res.partner').browse(cr, uid, title, context=context)
return {'value': {'title': partner_id.title,}}
return {'value':{}}
xml::
<field name="partner_id" on_change="onchange_partner_id(title,partner_id)"/>
<field name="title" on_change="onchange_partner_id(title,partner_id)"/>
nahain,
First, You don't need to pass 'title' as an argument in on_change of partner_id at xml field defination...
then, under onchange_partner_id, u are having partner_id as an argument, but while browsing you are using 'title', which is not defined anywhere in function defination...
so please change title to partner_id in browse, as:
partner_id = self.pool.get('res.partner').browse(cr, uid, partner_id, context=context)
and in xml as:
<field name="partner_id" on_change="onchange_partner_id(partner_id)"/>
and no need of any onchange function in title field...
Hope it help!
Hi, Pawan. Thank you for your reply, I tried with change as you suggest me but still not working, no error and not getting data in title field.
Hi, Pawan. I change "partner_id" to "customer_project" (just changed the id) and customer_project= self.pool.get('res.partner').browse(cr, uid, customer_project, context=context), and in xml as: now its Working!!
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now | https://www.odoo.com/forum/help-1/question/select-customer-and-get-specific-fields-value-99021 | CC-MAIN-2017-22 | en | refinedweb |
Perl::Critic::Theme - Construct thematic sets of policies.
This is a helper class for evaluating theme expressions into sets of Policy objects. There are no user-serviceable parts here.
This is considered to be a non-public class. Its interface is subject to change without notice.
new( -rule => $rule_expression )
Returns a reference to a new Perl::Critic::Theme object.
-rule.
A theme rule is a simple boolean expression, where the operands are the names of any of the themes associated with the Perl::Critic::Polices.
Theme names can be combined with logical operators to form arbitrarily complex expressions. Precedence is the same as normal mathematics, but you can use parentheses to enforce precedence as well. Supported operators are:
Operator Altertative Example ---------------------------------------------------------------- && and 'pbp && core' || or 'pbp || (bugs && security)' ! not 'pbp && ! (portability || complexity)
See "CONFIGURATION" in Perl::Critic for more information about customizing the themes for each Policy.
cook_rule( $rule )
Standardize a rule into a almost executable Perl code. The "almost" comes from the fact that theme names are left as is.
$RULE_INVALID_CHARACTER_REGEX
A regular expression that will return the first character in the matched expression that is not valid in a rule.. | http://search.cpan.org/~thaljef/Perl-Critic-1.120/lib/Perl/Critic/Theme.pm | CC-MAIN-2017-22 | en | refinedweb |
I have seen the HIWORD and LOWORD in some winapi header file. As their name suggests they select the higher or lower WORD (16bit) from a DWORD(32bit). Whats the function of the '& 0xFFFF' in the definition of the HIWORD macro? I know what it does, but for me, it seems pointless. The right shift leaves 0s in the higher 16bits anyway, so whats the point in masking them out?
Simple test program:
Code:
#include <stdio.h>
typedef unsigned long DWORD;
typedef unsigned short WORD;
#define LOWORD(a) ((WORD)(a))
#define HIWORD(a) ((WORD)(((DWORD)(a) >> 16) & 0xFFFF))
int main()
{
DWORD d=0xABCD1234;
printf("Original value:\n");
printf(" d == %X\n",d);
printf("\nMacros:\n");
printf("LOWORD(d) == %X\n", LOWORD(d));
printf("HIWORD(d) == %X\n", HIWORD(d));
printf("\nSimple hiword:\n");
printf(" d >> 16 == %X\n", d >> 16);
return 0;
} | https://cboard.cprogramming.com/c-programming/109984-hiword-loword-macros-printable-thread.html | CC-MAIN-2017-22 | en | refinedweb |
Unico,
> Hi, sorry for replying so late, I have been experiencing mail problems
> and had to dig this one up from the archives.
No worries - this is unfortunately a part time persuit for me too.
> > I think the alternative constructor would do it definitely. Although
> > I would miss all the functionality that CocoonBean provides for
> > creating and initializing Cocoon.
> <uv>
> So what functionality are you referring to here? Surely you don't want
> to go configuring the Cocoon instance if it has already been
> configured elsewhere (by its containing servlet). </uv>
>
> <uh>
> No, but I could use it wherever I do create and configure it. Be that
> in a servlet or in an Avalon embedded component. Although it wouldn't
> be a problem to do that without the help of a utility class and I am
> doing exactly that right now, my suggestion was that it might be
> useful. </uh>
Okay. But why do you want to create a Cocoon object as independent from the
Cocoon bean? Why can't the bean create and configure it for you?
> <uv>
> Are you suggesting that we might want the bean to be able to generate
> a page from a webapp that isn't being served by the servlet? </uv>
>
> <uh>
> I'm saying that I see two separate areas of concern that CocoonBean
> could be useful for me. One is to help create and configure Cocoon,
> the other is to help run Cocoon and gather information about these
> runs. The former would be useful for me in a thread safe type
> component where I create and manage a shared cocoon instance, the
> latter I'd like to use in the per-thread situation of a publication
> request. </uh>
I'm afraid I don't quite understand. Can you explain more? I don't quite understand
what you mean by these two scenarios. You want the bean to create and configure
cocoon (which I presume it already does). By the latter, are you referring to stuff like
following links?
> > > >?
> >
> > I mean state that controls the way processing is done such as
> > followLinks flag and state that holds information about a single
> > processing run such as the brokenLinks List for instance.
> >
> > I'm wondering whether we should split up CocoonBean into a class for
> > creating and setting up Cocoon and one that holds all the code
> > related to a single run. The former would follow a singleton
> > lifestyle and the latter a transient one. What do you think?
>
> <uv>
> So, what do you mean by 'shared between clients'?
> </uv>
>
> <uh>
> I mean that the same Cocoon instance be accessible from different
> locations in the system. One client of this "Cocoon service" would the
> HttpServlet that handles regular http calls. Another a mail system
> that publishes pages over smtp, and yet another that receives commands
> to push pages onto a remote server as part of a publication action.
Why do you want to share the same Cocoon instance? Is it a performance thing?
> Actually that was what I started out from, because the publication
> system I have now follows this exact approach. It accesses the same
> Cocoon instance that is used to handle http requests as well. Since it
> is separated from the http servlet I needed to put the Cocoon instance
> somewhere from where I could access it from both locations.
So are you saying that you create a CocoonBean around the Cocoon instance
created by the HTTP Servlet and hand that bean over to other systems for them to
use in rendering URIs?
> But it isn't necessarily required for me to keep these two clients
> separated. It's just the way it works for me now, and divorcing Cocoon
> management from the code using it, is something that would be
> generally useful I think. </uh>
That is the primary purpose of the bean.
> <uv>
> Would you have the same bean running in multiple threads?
> </uv>
>
> <uh>
> No, the bean can be single threaded, but I would be running multiple
> CocoonBeans sharing the same Cocoon concurrently. </uh>
Okay.
> <uv>
> Let's understand exactly what your requirements are, then we can look
> at how we might achieve it. </uv>
>
> OK, thanks for sticking with me so long, I hope I am not being too
> annoying ;)
No, not at all, I appreciate the interest!
> The basic requirement that I have is that of a webservice that pushes
> files onto a target location such as a remote FTP server. I consider
> two different approaches. One is to integrate the service with Cocoon
> as it now runs as a servlet or come up with an implementation that is
> separate from it.
This is exactly what I have in mind for the bean/cli. I made the bean write to
ModifiableSources so that it can write directly to such things as remove FTP
servers. So I would create a PublishingGenerator or PublishingTransformer that
takes in a configuration (like the current cli.xconf) which tells the publisher what to do.
That then gets hold of a Bean and hands the info to the bean for processing. The
bean is then responsible for generating the pages and dispatching them to their final
location (by simply opening an output stream on a modifiable source). The Bean
could then write to a specified listener every time a file write is completed, which is
then passed on to the next stage of the pipeline.
So if you get it so that the Cocoon HTTP servlet can call the bean, you get delivery to
multiple destinations via multiple protocols pretty much for free. If you need to create
modifiableSources for your protocols, you can then also give those sources to the
whole Avalon and Cocoon communities.
> In the former case, publication requests might involve a protocol that
> is similar to Cocoon views. I am thinking that the sitemap could have
> a "targets" section that defines publication locations, the default
> being just the stream to the requesting client browser. Then, similar
> to the way views work, a cocoon request could be made by optionally
> specifying the target to publish to:
>
>
> The other possibility is keeping the publication service separate from
> the CocoonServlet. Configuration would be outside the sitemap and I
> would need a way to share CocoonServlet's Cocoon and
> PublicationService's Cocoon.
I would stick for the moment with the xconf format that the bean (well, actually the
CLI) uses. It would be possible to make the bean configure itself from an xconf file
passed in as SAX events, or as a Configuration object, which would enable it to be
configured in a number of ways.
But if the publicationService is just running as a Cocoon sitemap component, then I'd
suggest it gets its configuration from its incoming SAX stream (probably identified
with an appropriate namespace). Then the site builder can decide exactly where the
info comes from, and adapt it as required, even at runtime.
> I think I prefer the first approach because it wouldn't require
> additional setup and configuration is right where you'd expect it to
> be. Seems cleaner somehow. It also circumvents the issue of sharing
> the Cocoon instances we were discussing before. On the other hand,
> http being a request-response type of affair, the browser response is
> not well defined. There's also the additional complexity added to the
> core of Cocoon.
To my mind, the browser response in such a situation is a report saying whether or
not the generation of pages was successful.?
Regards, Upayavira | http://mail-archives.apache.org/mod_mbox/cocoon-dev/200306.mbox/%3C3EF7621C.716.15C1589F@localhost%3E | CC-MAIN-2017-22 | en | refinedweb |
1 /*2 File: SynchronizedVariable 30Jun1998 dl Create public version12 */13 14 package org.dbunit.util.concurrent;15 16 /**17 * Base class for simple, small classes 18 * maintaining single values that are always accessed19 * and updated under synchronization. Since defining them for only20 * some types seemed too arbitrary, they exist for all basic types,21 * although it is hard to imagine uses for some.22 * <p>23 * These classes mainly exist so that you do not have to go to the24 * trouble of writing your own miscellaneous classes and methods25 * in situations including:26 * <ul>27 * <li> When you need or want to offload an instance 28 * variable to use its own synchronization lock.29 * When these objects are used to replace instance variables, they30 * should almost always be declared as <code>final</code>. This31 * helps avoid the need to synchronize just to obtain the reference32 * to the synchronized variable itself.33 *34 * <li> When you need methods such as set, commit, or swap.35 * Note however that36 * the synchronization for these variables is <em>independent</em>37 * of any other synchronization perfromed using other locks. 38 * So, they are not39 * normally useful when accesses and updates among 40 * variables must be coordinated.41 * For example, it would normally be a bad idea to make42 * a Point class out of two SynchronizedInts, even those43 * sharing a lock.44 *45 * <li> When defining <code>static</code> variables. It almost46 * always works out better to rely on synchronization internal47 * to these objects, rather than class locks.48 * </ul>49 * <p>50 * While they cannot, by nature, share much code,51 * all of these classes work in the same way.52 * <p>53 * <b>Construction</b> <br>54 * Synchronized variables are always constructed holding an55 * initial value of the associated type. Constructors also56 * establish the lock to use for all methods:57 * <ul>58 * <li> By default, each variable uses itself as the59 * synchronization lock. This is the most common60 * choice in the most common usage contexts in which61 * SynchronizedVariables are used to split off62 * synchronization locks for independent attributes63 * of a class.64 * <li> You can specify any other Object to use as the65 * synchronization lock. This allows you to66 * use various forms of `slave synchronization'. For67 * example, a variable that is always associated with a68 * particular object can use that object's lock.69 * </ul>70 * <p>71 * <b>Update methods</b><br>72 * Each class supports several kinds of update methods:73 * <ul>74 * <li> A <code>set</code> method that sets to a new value and returns 75 * previous value. For example, for a SynchronizedBoolean b,76 * <code>boolean old = b.set(true)</code> performs a test-and-set.77 * <p>78 * <li> A <code>commit</code> method that sets to new value only79 * if currently holding a given value.80 * 81 * For example, here is a class that uses an optimistic update82 * loop to recompute a count variable represented as a 83 * SynchronizedInt. 84 * <pre>85 * class X {86 * private final SynchronizedInt count = new SynchronizedInt(0);87 * 88 * static final int MAX_RETRIES = 1000;89 *90 * public boolean recomputeCount() throws InterruptedException {91 * for (int i = 0; i < MAX_RETRIES; ++i) {92 * int current = count.get();93 * int next = compute(current);94 * if (count.commit(current, next))95 * return true;96 * else if (Thread.interrupted()) 97 * throw new InterruptedException();98 * }99 * return false;100 * }101 * int compute(int l) { ... some kind of computation ... }102 * }103 * </pre>104 * <p>105 * <li>A <code>swap</code> method that atomically swaps with another 106 * object of the same class using a deadlock-avoidance strategy.107 * <p>108 * <li> Update-in-place methods appropriate to the type. All109 * numerical types support:110 * <ul>111 * <li> add(x) (equivalent to return value += x)112 * <li> subtract(x) (equivalent to return value -= x)113 * <li> multiply(x) (equivalent to return value *= x)114 * <li> divide(x) (equivalent to return value /= x)115 * </ul>116 * Integral types also support:117 * <ul>118 * <li> increment() (equivalent to return ++value)119 * <li> decrement() (equivalent to return --value)120 * </ul>121 * Boolean types support:122 * <ul>123 * <li> or(x) (equivalent to return value |= x)124 * <li> and(x) (equivalent to return value &= x)125 * <li> xor(x) (equivalent to return value ^= x)126 * <li> complement() (equivalent to return x = !x)127 * </ul>128 * These cover most, but not all of the possible operators in Java.129 * You can add more compute-and-set methods in subclasses. This130 * is often a good way to avoid the need for ad-hoc synchronized131 * blocks surrounding expressions.132 * </ul>133 * <p>134 * <b>Guarded methods</b> <br>135 * All <code>Waitable</code> subclasses provide notifications on136 * every value update, and support guarded methods of the form137 * <code>when</code><em>predicate</em>, that wait until the138 * predicate hold, then optionally run any Runnable action139 * within the lock, and then return. All types support:140 * <ul>141 * <li> whenEqual(value, action)142 * <li> whenNotEqual(value, action)143 * </ul>144 * (If the action argument is null, these return immediately145 * after the predicate holds.)146 * Numerical types also support 147 * <ul>148 * <li> whenLess(value, action)149 * <li> whenLessEqual(value, action)150 * <li> whenGreater(value, action)151 * <li> whenGreaterEqual(value, action)152 * </ul>153 * The Waitable classes are not always spectacularly efficient since they154 * provide notifications on all value changes. They are155 * designed for use in contexts where either performance is not an156 * overriding issue, or where nearly every update releases guarded157 * waits anyway.158 * <p>159 * <b>Other methods</b> <br>160 * This class implements Executor, and provides an <code>execute</code>161 * method that runs the runnable within the lock.162 * <p>163 * All classes except SynchronizedRef and WaitableRef implement164 * <code>Cloneable</code> and <code>Comparable</code>.165 * Implementations of the corresponding166 * methods either use default mechanics, or use methods that closely167 * correspond to their java.lang analogs. SynchronizedRef does not168 * implement any of these standard interfaces because there are169 * many cases where it would not make sense. However, you can170 * easily make simple subclasses that add the appropriate declarations.171 *172 * <p>173 *174 *175 *176 * <p>[<a HREF=""> Introduction to this package. </a>]177 **/178 179 public class SynchronizedVariable implements Executor {180 181 protected final Object lock_;182 183 /** Create a SynchronizedVariable using the supplied lock **/184 public SynchronizedVariable(Object lock) { lock_ = lock; }185 186 /** Create a SynchronizedVariable using itself as the lock **/187 public SynchronizedVariable() { lock_ = this; }188 189 /**190 * Return the lock used for all synchronization for this object191 **/192 public Object getLock() { return lock_; }193 194 /**195 * If current thread is not interrupted, execute the given command 196 * within this object's lock197 **/198 199 public void execute(Runnable command) throws InterruptedException {200 if (Thread.interrupted()) throw new InterruptedException ();201 synchronized (lock_) { 202 command.run();203 }204 }205 }206
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ | | http://kickjava.com/src/org/dbunit/util/concurrent/SynchronizedVariable.java.htm | CC-MAIN-2017-22 | en | refinedweb |
Download presentation
Presentation is loading. Please wait.
Published byThomas Romero Modified over 3 years ago
1
1 eXtensible Markup Language
2
XML is based on SGML: Standard Generalized Markup Language HTML and XML are both based on SGML 2 SGML HTMLXML
3
HTML was designed to display data and to focus on how data looks. HTML is about displaying information, while XML is about describing information XML was designed to describe data and to focus on what data is. It is important to understand that XML was designed to store, carry, and exchange data. XML was not designed to display data. 3
4
XML stands for EXtensible Markup Language XML is a markup language much like HTML XML was designed to describe data XML tags are not predefined. You must define your own tags Extensible: can be extended to lots of different applications. Markup language: language used to mark up data. Meta Language: Language used to create other languages. XML uses a Document Type Definition (DTD) or an XML Schema to describe the data 4
5
Harry Potter J. K. Rowling 1999 Scholastic 5
6
Harry Potter J. K. Rowling 1999 Scholastic 6
8
1. XML is used to Exchange Data With XML, data can be exchanged between incompatible systems 2. XML and B2B With XML, financial information can be exchanged over the Internet. 3. XML can be used to Share Data With XML, plain text files can be used to share data. 8
9
4. XML is free and extensible XML tags are not predefined. we must "invent" your own tags. 5. XML can be used to Store Data With XML, plain text files can be used to store data. 6. XML can be used to Create new Languages XML is the mother of WAP and WML. 7. HTML focuses on "look and feel XML focuses on the structure of the data. 9
10
My First XML Introduction to XML What is HTML What is XML XML Syntax Elements must have a closing tag Elements must be properly nested 10
11
Element content book Mixed content Chapter Simple content para Empty content prod 11
12
Names can contain letters, numbers, and other characters Names must not start with a number or punctuation character Names must not start with the letters xml (or XML, or Xml, etc) Names cannot contain spaces Avoid "-" and "." in names. For example, if you name something "first-name," it could be a mess if your software tries to subtract name from first. Or if you name something "first.name," your software may think that "name" is a property of the object "first." 12
13
Names should be short and simple XML documents often have a corresponding database, in which fields exist corresponding to elements in the XML document. Attribute values must always be enclosed in quotes, but either single or double quotes can be used. Ex: 13
14
XML elements can have attributes. Attributes are used to provide additional information about elements. In HTML. The SRC attribute provides additional information about the IMG element. In XML 14
15
Data can be stored in child elements or in attributes. Attributes : Anna Smith Elements: female Anna Smith 15
16
A well-formed XML document conforms to XML syntax rules and constraints, such as: The document must contain exactly one root element and all other elements are children of this root element. All markup tags must be balanced; that is, each element must have a start and an end tag. Elements may be nested but they must not overlap. All attribute values must be in quotes. 16
17
According to the XML specification, an XML document is considered valid if it has an associated DTD declaration and it complies with the constraints expressed in the DTD. To be valid, an XML document must meet the following criteria: Be well-formed Refer to an accessible DTD-based schema using a Document Type Declaration: 17
18
The Document Type Definition (DTD) forms the basis of valid documents because it establishes the grammar of an XML vocabulary, which in turn determines the structure of XML documents. A DTD is necessary for performing document validation, which is an important part of XML content development and deployment. 18
19
ELEMENT is used to declare element names Ex: ATTLIST To declare attributes 19
20
TypesDescription CDATAUnparsed character data Enumerateda series of string values IDA unique identifier IDREFA reference to an ID declared somewhere NMTOKEN A name consisting of XML token characters NMTOKENS Multiple names consisting of XML token characters. 20
22
InternalDTDs Placing the DTD code in the DOCTYPE tag in this way products.xml 1 XYZ 300.00 XYZ descr 1000 22
23
SYSTEM the definitions are developed and used by the same comp or PUBLIC if the definition can be used by public 23
24
products.dtd products.xml 24
27
Xml Xsl Xsd 27
28
28 Apples Bananas African Coffee Table 80 120
29
XML Schema is an XML-based alternative to DTD. An XML schema describes the structure of an XML document. The XML Schema language is also referred to as XML Schema Definition (XSD). 29
30
An XML Schema: defines elements that can appear in a document defines attributes that can appear in a document defines which elements are child elements defines the order of child elements defines the number of child elements defines whether an element is empty or can include text defines data types for elements and attributes 30
31
1.Simple elements 2.Complex elements 31
32
A simple element is an XML element that can contain only text. It cannot contain any other elements or attributes. Xml: abc Xml schema: 32
33 33
34 34
35 35
37
A complex element is an XML element that contains other elements and/or attributes. 37
40
DTD supports types ID,IDREF,CDATA etc., Schema supports all primitive and user defined data types DTD supports No specifier, ?, *, + sign Schema hava minOccurs and maxOccurs attributes XML Schemas are extensible to future additions XML Schemas are richer and more powerful than DTDs XML Schemas are written in XML 40
41
An XML parser is a piece of code that reads a document and analyzes its structure. The parser is the engine for interpreting our XML documents The parser reads the XML and prepares the information for your application. How to use a parser 1. Create a parser object 2. Pass your XML document to the parser 3. Process the results 41
42
import com.ibm.xml.parser.*; import java.io.*; public class SimpleParser {public static void main (String a[]) throws Exception {Parser p=new Parser("err"); FileInputStream fis=new FileInputStream(a[0]); TXDocument doc=p.readStream(fis); doc.printWithFormat(new OutputStreamWriter(System.out)); } 42
43
There are two common APIs that parsers use. DOM is the Document Object Model API SAX is the Simple API for XML 43
44
DOM uses a tree based structure. DOM reads an entire XML document and builds a Document Object. The Document object contains the tree structure. The top of the tree is the root node. The tree grows down from this root, defining the child elements. DOM is a W3C standard. Using DOM, we can also perform insert nodes, update nodes, and deleting nodes. 44
45
Node: The base data type of the DOM. Methods: Element: Attr: Represents an attribute of an element. Text: The actual content of an Element or Attribute Document: Represents the entire XML document. A Document object is often referred to as a DOM tree. 45
46
46 Node getChildNodes(), getNodeName(), getNodeValue(), hasChildNodes(). Document createElement(), createAttribute(), createTextNode(), Element NodeList getLength() item()
47
SAX parsers are event-driven The parser fires an event as it parses each XML item. The developer writes a class that implements a handler interface for the events that the parser may fire. 47
48
DocumentHandler Functions in this interface startDocument() startElement() endElement() endDocument() void setDocumentLocator(Locator) void characters(char[ ],int start,int length) This event fires when text data is found in the XML Document 48 class HandlerBase is a sub class of DocumentHandler also called Adapter Class.
49
DOMSAX Uses more memory and has more functionality Uses less memory and provides less functionality The entire file is stored in an internal Document object. This may consume many resources The developer must handle each SAX event before the next event is fired. For manipulation of the document, DOM is best choice For simple parsing and display SAX will work great 49
Similar presentations
© 2017 SlidePlayer.com Inc. | http://slideplayer.com/slide/252471/ | CC-MAIN-2017-22 | en | refinedweb |
Every Java package (JAR, WAR, EAR, etc.) has a
MANIFEST.MF file in the
META-INF directory. The file contains a list of attributes, which describe this particular package. For example:
Manifest-Version: 1.0 Created-By: 1.7.0_06 (Oracle Corporation) Main-Class: MyPackage.MyClass
When your application has multiple JAR dependencies, you have multiple
MANIFEST.MF files in your class path. All of them have the same location:
META-INF/MANIFEST.MF. Very often it is necessary to go through all of them in runtime and find the attribute by its name.
jcabi-manifests makes it possible with a one-liner:
import com.jcabi.manifests.Manifests; String created = Manifests.read("Created-By");
Let's see why you would want to read attributes from manifest files, and how it works on a low level.
Package Versioning
When you package a library or even a web application, it is a good practice to add an attribute to its
MANIFEST.MF with the package version name and build number. In Maven,
maven-jar-plugin can help you (almost the same configuration for
maven-war-plugin):
<plugin> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifestEntries> <Foo-Version>${project.version}</Foo-Version> <Foo-Hash>${buildNumber}</Foo-Hash> </manifestEntries> </archive> </configuration> </plugin>
buildnumber-maven-plugin will help you to get
${buildNumber} from Git, SVN or Mercurial:
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>buildnumber-maven-plugin</artifactId> <executions> <execution> <goals> <goal>create</goal> </goals> </execution> </executions> </plugin>
After all these manipulations,
MANIFEST.MF, in your JAR will contain these two extra lines (on top of all others added there by Maven by default):
Foo-Version: 1.0-SNAPSHOT Foo-Hash: 7ef4ac3
In runtime, you can show these values to the user to help him understand which version of the product he is working with at any given moment.
Look at stateful.co, for example. At the bottom of its front page, you see the version number and Git hash. They are retrieved from
MANIFEST.MF of the deployed WAR package, on every page click.
Credentials
Although this may be considered as a bad practice (see Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation by Jez Humble and David Farley), sometimes it is convenient to package production credentials right into the JAR/WAR archive during the continuous integration/delivery cycle.
For example, you can encode your PostgreSQL connection details right into
MANIFEST.MF:
<plugin> <artifactId>maven-war-plugin</artifactId> <configuration> <archive> <manifestEntries> <Pgsql>jdbc:postgresql://${pg.host}:${pg.port}/${pg.db}</Pgsql> </manifestEntries> </archive> </configuration> </plugin>
Afterwards, you can retrieve them in runtime using
jcabi-manifests:
String url = Manifests.read("Pgsql");
If you know of any other useful purposes for
MANIFEST.MF, let me know :) | http://www.yegor256.com/2014/07/03/how-to-read-manifest-mf.html | CC-MAIN-2017-22 | en | refinedweb |
6 February 2014
Comparing Web API 2 and WCF for building services on HTTP and REST
On the face of it, Microsoft took WCF’s promise of “one implementation, any protocol” and shot it in the head with ASP.NET Web API. After all, the Web API seemed to emerge from an increasingly fragmented landscape where Microsoft had failed to nail HTTP service provision with WCF.
The original goal of WCF was to support SOAP and WS-*services across a number of different transports. The same contract could be applied to a different transport just by changing the binding configuration. Support for HTTP services was added in .Net 3.5 via WebHttpBinding in recognition of the need to provide non-SOAP services over HTTP.
Despite attempts to enhance HTTP service provision through successive releases of WCF, the two have always seemed slightly uncomfortable bedfellows. At the heart of this is the fact that HTTP and REST do not fit very well into the core WCF abstraction that separates the service contract from the underlying transport.
HTTP is not just another transport protocol
The problem is that HTTP is not just another type of transport. It’s an application-level protocol that provides a set of features that can be directly leveraged by RESTful APIs:
- It supports a series of verbs that define actions – e.g. GET for fetching information and DELETE for removing it.
- It contains message headers that can be used to describe messages as well as caching and securing it.
- The message body can be used for a wide range of data, not just a structured XML response.
- The system of URLs can be used to define resources and actions to provide an intuitive and navigable resource API
These features are central to the design and functionality of RESTful APIs and cannot be meaningfully separated from the underlying protocol. WCF’s core abstraction that separates the service contract from the underlying transport binding is not valid for RESTful APIs.
The cruft comes for free with WCF
Although WCF can still be used as an implementation technology for an HTTP service, a common complaint is that it tends to add a lot of Microsoft-specific cruft to messages by default. This can be an issue when taking a contract-first approach to service design where the clarity and cleanliness of the request and response messages are emphasised.
This is particularly relevant for RESTful services and WCF doesn’t give you the same level of control over messages that you get with Web API. A fair amount of detail gets added to a service response out of the box, including namespaces on the header element and a few bonus headers.
These additions are particularly unwelcome for carefully designed RESTful services that demand more direct control over payloads, headers, response codes and HTTP verbs. Having an implementation stack that inserts its own decoration to the contract will only undermine the clarity of a good REST API.
With power comes responsibility
The extra control that Web API gives you does have a downside from a governance perspective as it does not offer any facilities for controlling interface definitions. It is easy for developers to make small and unnoticed changes to service interfaces by adding an extra header or returning an unexpected status code.
WCF’s service and data contracts do provide a more explicit interface definition. This gives rise to a clearer definition that can be managed and versioned much more easily. The Web API does not let you define explicit contracts in quite the same way, so more discipline is required to avoid unplanned breaking changes.
Complimentary technologies. Really.
Since the WCF and ASP.NET teams have merged much of the fragmentation that lingered around Microsoft’s HTTP service stack has been resolved. They appear to have settled on a strategy where they direct you towards WCF to create web services that accessible over a variety of transports and ASP.NET Web API to create REST-style services
The emergence of ASP.NET Web API provided a more specific programming model for HTTP. Where WCF allows you to build services that support multiple transports and encodings for the same service, the Web API allows you to far greater control over HTTP services and different media types. Improvements in the most recent release such as attribute routing and IHttpActionResult have deepened this level of control.
SOAP and REST are completely different styles of service and cannot be compared directly. REST may be gaining ground due to its simplicity, but there are a lot of good reasons to use SOAP, particularly if you want to leverage the WS-* standards for enterprise security, ACID-compliant transactions or reliable messaging.
WCF offers more flexibility over channels where you can use faster transports such as TCP, named pipes or even UDP. If speed is of the essence and your hardware infrastructure allows it then you may be better off using WCF. It also allows you to develop more specialised services such as one-way or duplex messaging.
If you want to build fully RESTful services that leverage all the features of HTTP then the Web API is a better choice. Features such as cache control for browsers, concurrency control via ETags and using different content types are easily implemented with the Web API. It’s possible to do much of this stuff with WCF, but there’s little benefit in doing so.
Filed under Architecture, ASP.NET, Integration, Net Framework, Web services. | http://www.ben-morris.com/comparing-web-api-2-and-wcf-for-building-services-for-http-and-rest/ | CC-MAIN-2017-22 | en | refinedweb |
Chapter 4
HideShow resource information
- Created by: Lucy Uffindell-Saunderson
- Created on: 22-09-13 18:34
What is the average consumer expenditure in the UK ? [in percent]
60- 65 %
1 of 39
Define economic growth
increase in aggregate demand per year
2 of 39
Define trade deficit
import more than we export
3 of 39
Define trade surplus
import less than we export
4 of 39
What does GDP stand for?
Gross Domestic Product
5 of 39
How is economic growth measured?
GDP
6 of 39
What is consumer confidence?
how optimistic consumers are about future economic prospects
7 of 39
Define rate of interest?
the charge for borrowing money and the amount paid for lending money.
8 of 39
What is the average propensity to consume [APC] ?
the proportion of disposable income spent. It is consumer expenditure divided by disposable income.
9 of 39
Define net savers
people who save more than they borrow
10 of 39
Define wealth
a stock of assets e.g property , shares and money held in a savings account
11 of 39
What is the distribution of income?
how income is shared out between households in a country
12 of 39
Define inflation
a sustained rise in the price level
13 of 39
Define saving
real disposable income minus spending
14 of 39
What is the average propensity to save [APS]
the proportion of disposable income saved. It is saving divided by disposable income
15 of 39
Define target savers
people who save with a target figure in mind
16 of 39
Define dissave
spending more than disposable income
17 of 39
Define savings ratio
savings as a proportion of disposable income
18 of 39
Define capacity utilisation
the extent to which firms are using their capital goods
19 of 39
Define corporation tax
a tax on firms profits
20 of 39
Define retained profits
profit kept by firms to finance investment
21 of 39
Define unit cost
average cost per unit of output
22 of 39
Define real GDP
the country's output measured in constant prices and so adjusted for inflation.
23 of 39
Define Gross Domestic Product [GDP]
the total output of goods and services produced in a country
24 of 39
Define exchange rate
the price of one currency in terms of another currency
25 of 39
Define tariff
a tax on imports
26 of 39
Define government bond
a financial asset issued by the central or local government as a means of borrowing money
27 of 39
Define aggregate supply
the total amount that producers in an economy are willing and able to supply at a given price level in a given time period
28 of 39
Define productivity
output, or production of a good or service per worker per unit of a factor of production in a given time period
29 of 39
Define privatisation
transfer of assets from the public to the private sector
30 of 39
What is the macroeconomic equilibrium
a situation where aggregate demand equals aggregate supply and real GDP is not changing
31 of 39
Define circular flow of income
the movement of spending and income throughout the economy
32 of 39
Define factor services
the services provided by the factors of production
33 of 39
Define leakages
withdrawals of possible spending from the circular flow of income
34 of 39
Define injections
additions of extra spending into the circular flow of income
35 of 39
Define the multiplier effect
the process by which any change in a component of aggregate demand results in a greater final change in real GDP
36 of 39
Define overheating
the growth in aggregate demand outstripping the growth in aggregate supply, resulting in inflation
37 of 39
Output gap
the difference between an economy's actual and potential real GDP
38 of 39
Define trend growth
the expected increase in potential output over time
39 of 39
Other cards in this set
Card 2
Front
Define economic growth
Back
increase in aggregate demand per year
Card 3
Front
Define trade deficit
Back
Card 4
Front
Define trade surplus
Back
Card 5
Front
What does GDP stand for?
Back
| https://getrevising.co.uk/revision-tests/chapter_4_4 | CC-MAIN-2017-22 | en | refinedweb |
In reply to Henrik Stokseth <hstokset@...>:
>don't commit it. a cvs update -d will get the empty directories, just=20
>like a normal checkout will. as for zip tools that skips empty=20
>directories, the generated files will be present when a new WIP is=20
>released so the directories will not be empty at that time, which makes=20
>tmpfile.txt files unnecessary.
>
>i'm sorry i didn't mention this before, but i thought it were obvious.
Erm... the directories are definitely in the repository on SourceForge,
but I can't get hold of them. I am using CVS 1.10 for win32 commandline.
Looking through the help messages (--help-options, --help-commands), I
can see nothing to indicate whether or not it should get empty
directories. I don't get them when checking out a new repository or
updating one.
How do I fix it?
Bye for now,
--=20
Laurence Withers, lwithers@...
Hi,
As Andrew Durdin <andy@...> rightly pointed out, color font
output on a colored background is incorrect. I enclose a patch:
Angelo Mottola wrote:
>
> > ...has been sent to sourceforge. It adds resize hooks to Windows and
> > X-11. (X-11 untested).
>
> Humm, I got this just when I finished my own version of the thing...
I don't see why anyone would need multiple callbacks. Can you give an
example?
Other than that, I think it's ok.
My patch on the other hand makes changes to the window managers so the
hooks actually get called. This works fine in AllegroGL, howevery, my
example forgram (stretches mysha.pcx on the window) doesn't. It gets the
correct width and height, but the display is still clipped on the
original bounderies. It's prolly an issue with DirectX, but I have no
idea how to code for it, so I'm not sure I can fix it.
I modify the SCREEN_W and SCREEN_H accordingly.
I'll send my updated patch.
>.
I think we should let the closing up to the program. Perhaps call
allegro_exit() if there are no callbacks installed, that way, we don't
break things too much :)
>
> > =)
Ok, my patch now enables resizing in Windows. No luck in getting it to
work though.
Oh yeah, in Windows, Allegro creates the window inside allegro_init().
That means that the resize flag must be enabled before allegro_init,
which doesn't really make sense.
Anyway, here's the patch and example program.
--
- Robert J Ohannessian
> ...has been sent to sourceforge. It adds resize hooks to Windows and
> X-11. (X-11 untested).
Humm, I got this just when I finished my own version of the thing... =)
--
Angelo Mottola
a.mottola@...
ICQ UIN #66972680
#include <hallo.h>
Sven Sandberg wrote on Wed Dec 27, 2000 um 01:07:58PM:
> Is this really a bug? I think it makes sense to make a distinction
IMHO this is one.
> between config variables that don't exist in a .cfg file and config
> variables that exist but are initialized to the empty string: In the
Really? How do you set an empty string? There is still one or more spaces
after the =. Look, the allegro.cfg file distributed with Allegro
contains examples that are not commented out! With these defaults
Allegro use allways empty strings instead of defaults.
> some cases). If you really want an empty string to mean the default
> string, then that can easily be handled by the program. With this patch
> there is AFAICS no way to give an empty string in a config file.
IMHO it's also not possible to specify empty strings now, so what is the
problem? If you want this "feature", we could introduce something new to
specify empty strings, e.g. using "" to do so.
Gr{us,eeting}s,
Eduard.
--
=====================================================================
Eduard Bloch <eb@...>; HP:
0xEDF008C5(GnuPG): E6EB 98E2 B885 8FF0 6C04 5C1D E106 481E EDF0 08C5
**
Es ist einfacher Linux zu konfigurieren, als mit Windows zu leben.
anonymous in dcouln
I just wanted to pipe up because I think you guys are making the whole
texture coordinate thing WAY too complicated.
For one thing, whether an integer texture coordinate maps to the
upperleft, lowerright, or middle of a texel is completely arbitrary. It
is not important where it maps, it just has to be consistant and easy to
use in the context of everything else in the library. This is just like
it is arbitrary whether the library is left or right handed, its just
important to be consistent and to document it. What is important is that
we consistently apply the unit which we choose for texture coordinates.
1 unit == 1 texel, OpenGL is 1 unit = 1 texture dimension, and Glide
(which is weird) uses 256 units = 1 texture dimension.
It simply does not matter where you map the integer values. They actually
are not very special except that humans can understand 3 better than
3.1415 (and that I think Allegro only allowed u and v to be integers
IIRC).
A quad mapped from (0,0) - (0,32) - (32,32) - (32,0) is 32x32 in size.
Just imagine me drawing it with a ruler. I start at 0 cm on the ruler,
and draw a line to 32 cm. I don't get a 33 cm square rectangle.
Now, if I was to put a 32x32 cm square graph paper over the top of
it (a texture map if you will), It would not matter how I aligned it with
the square, 32x32 boxes will be 'mapped' into the square.
I think that one of you is confusing a polygonal quad with a quad drawn
with lines. But you forget that line drawing and polygon drawing are
fundamentally different. Lines are drawn through the centers of their
coordinates and they must have a thickness to be seen, so a polygon drawn
when them will always be bigger than the equivalent filled polygon. It
will even be different than a polygon drawn in line mode (which allegro
doesn't have)
So, whether we align texels in the center (I know of no library that does
this), in the upper left like DX or the lower left like openGL is just a
matter of making a decision that fits and is easiest to use all other
things considered.
For Allegro, that means that the upper left corner of a texel should map
to integer coordinates.
A good document that helps explain some of this is at:
I don't know if I did a better job of explaining it, but I tried ^_^
...has been sent to sourceforge. It adds resize hooks to Windows and
X-11. (X-11 untested).
Someone will have to take on BeOS and Mac support though (it's as simple
as adding 3 lines to the window manager code - see patch for details).
It doesn't enable resizing, just adds the hooks.
I'm working on enabling resizing windows, so I'll submit another patch
for that later today (I hope!).
And here's the link:
--
- Robert J Ohannessian
Angelo Mottola wrote:
[snip]
> Thanks to your message I've already modified the Allegro system driver
> structure to allow window closing callbacks set/remove.
Rats, I'm too late. Well, I have the resize hook for Windows if anyone's
interested :)
(I'm starting the X one too).
[snip]
>?
Yes, it will be called twice if that's the case.
Why not by default just simulate the [esc] key? If the program needs
anything more advanced, then they can use a closing hook.
AFAIK this shouldn't break anything, as closing windows with the window
button couldn't be done before.
--
- Robert J Ohannessian
Only just got George's e-mail - Outlook's forwarding isn't that reliable :-)
> > I know but what I mean is that tilling behaves in a strange way :
> > according to your convention, drawing a texture from (0,0) to (32,32) is
> > the same thing than drawing a texture from (32,32) to (64,64) so it
> > seems a texel is shared (but it is not).
>
> That's still the case with the current code. I think one
> important thing to consider is what the polygon rendering code
> does in any case -- if I tell it to draw to a screen region
> equal to the texture coordinates then I expect it to effectively
> blit the texture, with no artifacts and no missing pixel
> columns. The old code wouldn't do this, and assuming the
> rasterizers do draw the pixels you specify, the new code is
> wrong too.
I keep referring back to bmp->cr and bmp->cb. These are exclusive :-)
> To explain this better, imagine we draw a square from (0,0) to
> (32,0) to (32,32) to (0,32), using the same values as the u,v
> coordinates in our 32x32 texture. How long is each side of the
> square? If it's 32x32, then Ben's solution is fine. If it's
> 33x33 (as I expect) then the polygon drawing is inclusive of the
> endpoints, so the texturing should also be inclusive. In this
> case we need to adjust the target u for each scanline.
Exactly. I'd rather the programmer had to do this, than use -0.5 and 32.5,
or settle for half-pixel-thick edges to the polygons.
> It think it might help a lot if the u,v coordinates
> to refer to the same position in the texel as the x,y
> coordinates do in the pixel. Since line drawing generally uses
> the centres of the endpoint pixels, the old code would then be
> correct, but it depends how Allegro treats its fixed/float
> coordinates -- are whole numbers still the centres of pixels, or
> are they the top left corners?
Lines are a bit different. They sort-of have thickness 1 - the size of the
pixel. The coordinates passed to line() represent a pixel to be filled
completely at each end, rather than referring to an exact point, namely the
centre of the pixel. Edges on a texture have thickness 0, so they can't
really be compared with lines.
> I don't think it forgets a texel, I think it draws too many
> pixels and takes them all into account...
The polygon3d() functions do not draw too many pixels. You don't get pixel
overlaps.
> An important thing I'm trying to consider here is that if you
> draw two polygons which share an edge then you should be able to
> use the same vertex data for the shared vertices -- screen
> coordinates *and* u,v coordinates. It looks like Allegro was
> broken already here, but I don't think your solution is correct
> -- I think this is better:
>
> du = (right_u - left_u) / (scanline_width-1)
>
> This makes the u,v of the right hand edge be applied to the
> pixel before the last one drawn, because the last one is an
> overlap to the next tile of the polygon to the right.
Except that there is no overlap. Not convinced? Look at the file, and
explain away the hline(...,x+w-1,...) call.
> I'm not sure what to think of this extra pixel though. If
> you're tiling polygons and sharing vertex data between them,
> Allegro is (probably) drawing an extra pixel so you need this
> u,v correction to be applied. If you're just drawing single
> polygons, though, you might not think of it as drawing an extra
> pixel, though it will be making your polygons slightly fatter
> than they should be (if you specify the square I mentioned
> above, its dimensions ought to be 32 along each side). Maybe in
> fact Allegro shouldn't draw this overlap pixel -- but there's a
> risk that this will make gaps between polygons due to rounding
> errors. If we did that, though, there would be no need to tweak
> u,v coordinates or gradients at all.
Just that it doesn't exist :-)
So in conclusion, as I said before, I think whole numbers should refer to
whole texels, and half-integers should refer to half-texels. It's also quite
elegant, when you want a whole texture mapped on to a square polygon, to
specify the actual dimensions of the bitmap, eg. (32,32) rather than
(31,31).
Have I been good enough this Christmas to have my patch applied please thank
you Mrs Patterson? :-) (For those who don't know, that's a reference to
Kevin and Perry, Harry Enfield)
Ben Davis
I noticed a patch has been applied to make poly3d.c work on BeOS. It does
this by adding a for loop between two statements. My patch inserts a
condition here anyway, so if and when my patch is applied, I would like
someone to try it on BeOS without the loop to see if it works. Otherwise, by
all means, put it back in :-)
You may have to do something fiddly to make the patch fit.
Ben Davis
> I have a test program that catches request for window closing under X.
> If anyone wants to see this program, I can place source somewhere, or
> send it by e-mail (which can be faster).
Thanks to your message I've already modified the Allegro system driver
structure to allow window closing callbacks set/remove. Send the file to me
via email and I'll merge it into the patch that will follow.
Anyway do not expect this patch to be released with 3.9.34, as this is still
alpha... And we want to release 3.9.34 before 2001, don't we? =)?
--
Angelo Mottola
a.mottola@...
ICQ UIN #66972680
Eduard Bloch wrote:
> I found a potential bug in a configuration routine. The problem was:
> if a string variable is given in the configuration file, but has no
> content, the pointer to the dataset with an EMPTY string is returned
> by find_config_string. With this fix, the function returns NULL and
> allows get_config_string to return the default value instead.
Is this really a bug? I think it makes sense to make a distinction
between config variables that don't exist in a .cfg file and config
variables that exist but are initialized to the empty string: In the
first case it means you want the default behaviour and in the latter
case it means that you really want an empty string (which is useful in
some cases). If you really want an empty string to mean the default
string, then that can easily be handled by the program. With this patch
there is AFAICS no way to give an empty string in a config file.
Sven
Hello,
Here's a patch that fixes a small problem in fix*.bat. The problem was
that dos gets confused if a bat file is modified by utod while it is
running. The patch should be applied in Allegro's directory with -p1.
Merry Christmas,
Sven
Angelo Mottola <a.mottola@...> writes:
> Allegro programs still don't handle window closing! Under X when you close
> the window you get a broken pipe message, and under BeOS when you click on
> the window closing button it doesn't even work... Don't know about Windows,
> but I assume a similar behaviour.
I have a test program that catches request for window closing under X.
If anyone wants to see this program, I can place source somewhere, or
send it by e-mail (which can be faster).
--
Michael Bukin
I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details | https://sourceforge.net/p/alleg/mailman/alleg-developers/?viewmonth=200012&viewday=28 | CC-MAIN-2017-22 | en | refinedweb |
06 November 2012 20:02 [Source: ICIS news]
HOUSTON (ICIS)--Chemtura does not expect to see a noticeable recovery in industrial demand in the current fourth quarter, the CEO of the US-based specialty chemicals firm said on Tuesday.
Rather, there remain “some risks of further weakening”, Craig Rogerson told analysts during Chemtura’s third-quarter results conference call.
In the third-quarter, Chemtura saw continued demand weakness in both ?xml:namespace>
“We didn’t see any sign of an upturn, but we didn’t see any further deterioration, but clearly there is a risk for further deterioration as we get into the fourth quarter,” he added.
Chemtura is responding to weak market demand by keeping a tight control on costs and focussing on gaining revenues from new products, Rogerson said.
Chemtura’s industrial segments – industrial performance products and industrial engineered products – saw year-on-year declines in third-quarter sales, mainly because of lower volumes and unfavourable exchange rate effects.
Rogerson also said that despite increased benzene costs, Chemtura expects to maintain margins at its industrial performance products segment, in particular in petroleum additives.
“I think we have done a good job, over the last six quarters or maybe a little longer than that, to get price”, thus offsetting higher raw material costs, he added. | http://www.icis.com/Articles/2012/11/06/9611540/us-chemtura-pessimistic-on-q4-industrial-demand-in-europe-asia.html | CC-MAIN-2014-41 | en | refinedweb |
Before you start
About this series
This "Create a commercial-quality Eclipse IDE" series demonstrates what it takes to create integrated development environments (IDEs) as Eclipse plug-ins for any existing programming language or your own programming language. It walks you through the two most important parts of the IDE -- the core and the user interface (UI) -- and takes a detailed look at the problems associated with designing and implementing them.
This series uses the ANTLR Studio and Eclipse Java™ Development Tools (JDT) IDEs as case studies and examines their internals to help you understand what it takes to create a highly professional commercial-level IDE. Code samples help you follow the concepts and understand how to use them in your own IDE.
About this tutorial
Part 1 introduces the architecture of an IDE and shows how to create the IDE's core layer. Part 2 shows how to implement the UI component of your IDE. In this final installment, you discover additional UI elements Eclipse provides to enhance your editor. This tutorial also discusses the differences between a commercial-quality IDE and an amateur one. It looks at the internals of the ANTLR Studio and Eclipse JDT IDEs to show how you can provide features that will differentiate your IDE from the rest.
Prerequisites
This tutorial assumes a basic knowledge of creating plug-ins for Eclipse and using the Eclipse Plug-in Development Environment (PDE).
System requirements
To run the code samples in this tutorial, you need a copy of the Eclipse software development kit (SDK) running Java Virtual Machine (JVM) V1.4 or later.
Using code completion
No doubt, you use code completion when coding in your favorite IDEs. When you press Ctrl+Space in an editor, you expect to see a drop-down list containing the names of all the identifiers you can type in that location (see Figure 1). This functionality is no longer a feature but a standard among today's IDEs. If your IDE does nothing when a programmer presses Ctrl+Space on his or her keyboard, your IDE stands a good chance of being uninstalled.
Figure 1. Code completion in action within the Eclipse JDT
Now let's see how to actually implement this functionality in your IDE.
Implement code completion in your IDE
Eclipse developers seem to have assumed that nearly every editor of every IDE will be implementing code completion functionality. As a result, they provided classes to make adding the functionality easy. To provide code completion functionality in your editor, you must know the following two interfaces:
IContentAssistant
IContentAssistProcessor
The Content Assistant is the main facade for code completion. If your editor shows a list of completions at a specific moment (for example, when the user presses Ctrl+Space), it would call a method on an object that implements the
IContentAssistant interface. Supporting classes handle the actual graphical user interface (GUI) of the pop-up list and the completions themselves. In fact, the
IContentAssistant interface doesn't contain anything other than methods to show completions or context information and to install and uninstall itself from the editor.
The
IContentAssistProcessor interface is responsible for calculating the completion proposals at a point in the editor. It also defines the characters on which it should auto-activate, such as the period (.) character, which, when pressed in the editor, shows the list of members of a type. You can define a different
IContentAssistProcessor for each partition type of a document. For example, when you press Ctrl+Space within a Javadoc comment, you expect different completions from when you press Ctrl+Space within Java code.
Note that the
IContentAssistProcessor is not responsible for implementing the GUI portion of the completions. That portion is handled by other classes within Eclipse, and you don't really need bother with it.
IContentAssistant
The
IContentAssistant interface is relatively simple. It contains the following components:
install()/
uninstall()
- Methods for installing and uninstalling the content assistant on the source viewer
showPossibleCompletions
- Shows the drop-down list containing the completions
showContextInformation
- Shows the pop-up menu that displays the context information at a location
getContentAssistProcessor
- Used to call the content assist processor for a particular content type in the document
Many extensions to the
IContentAssistant are available for actions such as attaching listeners, repeated invocation mode, and common prefixes. However, you don't need to worry about these, either, because Eclipse provides a class that implements them all for you:
org.eclipse.jface.text.contentassist ContentAssistant. You simply use the class in your IDE.
The only time you really encounter this class is in your
SourceViewerConfiguration subclass to configure code completion. To configure code completion for your editor:
- Override the
getContentAssistant()method of
SourceViewerConfiguration.
- Create a new instance of the
ContentAssistantclass.
- Set the document partitioning in the content assistant object.
- Set the various content assist processors for the different document partition types.
- If necessary, enable auto-activation. You can also set the delay in milliseconds after auto-activation is triggered.
- If necessary, further customize the completion menu by setting elements such as the background color of the drop-down list (called the Proposal Selector in Eclipse terminology).
Listing 1 shows the code for performing these steps.
Listing 1. Enable code completion in your IDE editor
@Override public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { ContentAssistant assistant= new ContentAssistant(); assistant.setDocumentPartitioning(get\ ConfiguredDocumentPartitioning(sourceViewer)); assistant.setContentAssistProcessor(new MyContentAssistProcessor(), IDocument.DEFAULT_CONTENT_TYPE); assistant.setAutoActivationDelay(0); assistant.enableAutoActivation(true); assistant.setProposalSelectorBackground(Display.getDefault(). getSystemColor(SWT.COLOR_WHITE)); return assistant; }
IContentAssistProcessor
The only real work you must do while implementing code completion functionality is to implement the
IContentAssistProcessor interface. Methods of the
IContentAssistProcessor interface include:
computeCompletionProposals()
- Computes the set of completions based on the offset provided
computeContextInformation()
- Computes the context information based on the offset provided
getCompletionProposal/contextInformation AutoActivationCharacters()
- Returns the characters that, when a user types them in the editor, automatically trigger the completion/context information to appear
Other methods exist, but these are all you need for now. In fact, because the discussion focuses only on code completion right now, only the
computeCompletionProposals and
getCompletionProposalAutoActivationCharacters interfaces are of interest. And most of the logic behind code completion functionality lies in the
computeCompletionProposals() method. Here, you must query your parse tree to see what identifiers are valid at the location.
The
computeCompletionProposals() method returns an array of
ICompletionProposal objects. An
ICompletionProposal represents each completion listed in the auto-complete list. The array defines items such as the text to insert, how to insert it, and the image and text to display in the completion menu.
Listing 2 shows a sample class that implements these two methods.
Listing 2. Class for implementing the computeCompletionProposals() and computeContextInformation() methods
public class ASCompletionProcessor implements IContentAssistProcessor { public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) { List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>(); //compute proposals at offset return proposals.toArray(new ICompletionProposal[proposals.size()]); } public char[] getCompletionProposalAutoActivationCharacters() { return new char[] {'.'}; } }
Using hyperlink detectors
Here is a trick you may not know: If you type a URL such as within the Eclipse Java editor and hover your cursor over the URL's text while pressing and holding the Ctrl key, the text turns into a hyperlink that you can click (see Figure 2). This behavior occurs as a result of hyperlink detection functionality within the editor.
Figure 2. Hyperlink detector functionality makes text behave as links
You can use hyperlink detection functionality for tasks other than simply detecting Web-site URLs. For example, if within a Javadoc in the Java editor, you type text such as
{@link MyClass#myMethod() } and, while pressing and holding the Ctrl key, hover your cursor over the MyClass or the myMethod text, the text turns into a link that you can click. Clicking the text opens the corresponding type or method in a new editor window. The same happens when you hover over a variable or method name: Clicking the name moves the caret to its declaration.
To add hyperlink detection functionality to your IDE editor, you use two interfaces:
IHyperlinkDetector
- Use this interface to detect hyperlinks within the editor.
IHyperlink
- This interface represents the hyperlink itself and defines elements such as what should be done when the link is clicked and the text region the link occupies.
The IHyperlinkDetector and IHyperlink interfaces
The
IHyperlinkDetector interface is simple, defining a single method:
IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks);
The arguments stand for:
textViewer
- The current text viewer
region
- The region of text in which to look for hyperlinks
canShowMultipleHyperlinks
- Used to tell whether you can show multiple hyperlinks to the user at the same time (in most cases, you will ignore this value and show a single hyperlink to the user.)
The methods defined in the
IHyperlink interface are:
open()
- Opens the hyperlink
getHyperlinkRegion()
- Returns the region of text that the hyperlink occupies
getTypeLabel()
- Used to label the hyperlink with a type; used when multiple hyperlinks must be shown
getHyperlinkText
- Assigns a text to this hyperlink; used when multiple hyperlinks point to the same location
For our purposes, you implement just the
open() and
getHyperlinkRegion() methods. The bulk of the logic resides in the
open() method because that method is responsible for implementing the behavior of the hyperlink.
Eclipse provides built-in
UrlHyperlinkDetector and
URLHyperlink classes used to detect URL hyperlinks within your editor. Your editor is configured with the
UrlHyperlinkDetector by default. Of course, you can add your custom hyperlink detectors, as well. As an example, you'll create a simple hyperlink detector that detects any text inside a pair of angle brackets (<>) and considers it a link to some declaration inside your editor.
Create a simple hyperlink detector
To create a simple hyperlink detector for your editor:
- Implement the
detectHyperlinks()method of the
IHyperlinkDetectorclass, as shown in Listing 3.
Listing 3. Implement the detectHyperlinks() method
public class MyHyperlinkDetector implements IHyperlinkDetector { public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { IRegion lineInfo; String line; try { lineInfo= document.getLineInformationOfOffset(offset); line= document.get(lineInfo.getOffset(), lineInfo.getLength()); } catch (BadLocationException ex) { return null; } int begin= line.indexof("<"); int end = line.indexof(">") if(end<0 || begin<0 || end==begin+1) return null; String text = line.substring(begin+1,end+1); IRegion region = new Region(lineInfo.getOffset()+begin+1,text.length()); return new IHyperLink[] {new MyHyperLink(region,text}; } }
- Implement the
IHyperLinkclass.
For this example, implement only the
open()and
getHyperlinkRegion()methods. In the
open()method, simply query the parse tree for the declaration of the identifier and move the caret to that location in the editor, as shown in Listing 4.
Listing 4. Implement the IHyperlink class
class MyHyperlink extends IHyperlink { private String location; private IRegion region; public MyHyperlink(IRegion region, String text) { this.region= region; this.location = text; } public IRegion getHyperlinkRegion() { return region; } public void open() { if(location!=null) { int offset=MyAST.get().getOffset(location); TextEditor editor=getActiveEditor(); editor.selectAndReveal(offset,0); editor.setFocus(); } } public String getTypeLabel() { return null; } public String getHyperlinkText() { return null; } }
- Override the
getHyperlinkDetectors()method of Source Viewer Configuration, and return an array containing your hyperlink detector class and the
URLHyperlinkDetectorclass. This way, you get the functionality of both hyperlink detectors.
@Ovveride public IHyperlinkDetector[] getHyperlinkDetectors(ISourceViewer sourceViewer) { return new IHyperlinkDetector[] { new MyHyperlinkDetector(), new URLHyperlinkDetector() }; }
The double-click strategy
By double-clicking a word in the text editor, you select the entire word. You can change this default behavior and enhance it to something specific to the programming language your editor supports. For example, clicking next to a brace in the Java editor selects everything within the matching pair of braces. To customize this behavior, you must implement the
ITextDoubleClickStrategy interface.
Implement the ITextDoubleClickStrategy interface
This interface is simple and contains just one method:
void doubleClicked(ITextViewer textViewer). This method is called each time you double-click the text in the text editor. Theoretically, instead of changing the selection, you could perform some other operation on double-clicking. The only caveat here is that you are not allowed to modify the text in any way.
To see how this works, create a double-click strategy that selects all the text to the end of a line:
- Create a class that implements the
ITextDoubleClickStrategyinterface and the
doubleClicked()method such that it selects all text to the end of the line, as shown in Listing 5.
Listing 5. Implement the ITextDoubleClickStrategy interface
public class MyTextDoubleClickStrategy implements ITextDoubleClickStrategy { public void doubleClicked(ITextViewer text) { try { int startOffset = text.getSelectedRange().x; IDocument document= text.getDocument(); IRegion line= document.getLineInformationOfOffset(position); int endOffset = line.getOffset() + line.getLength() if (startOffset == endOffset) return; text.setSelectedRange(startOffset, endOffset - startOffset); } catch (BadLocationException x) { } } }
- Override the
getDoubleClickStrategy()method of
SourceViewerConfigurationand return your double-click strategy, as shown in Listing 6. Note: Using the
getDoubleClickStrategy()method, you can set different double-click strategies for different content types. Thus, you could have a different strategy for comments, code, strings, etc.
Listing 6. Override the getDoubleClickStrategy() method
@Override public ITextDoubleClickStrategy \ getDoubleClickStrategy(ISourceViewer sourceViewer, String contentType) { return new MyTextDoubleClickStrategy (); }
Adding content formatting
To provide your editor the ability to format the code, you must use the content formatting application program interfaces (APIs) Eclipse provides. Following the usual strategy pattern, two interfaces are involved:
IContentFormatter
IContentFormattingStrategy
The
IContentFormatter acts as a facade and merely chooses the formatting strategy to apply to a given region. The
IContentFormattingStrategy actually does the formatting. Different partitions can have their own formatting strategy. Eclipse provides implementations of the
IContentFormatter interface; you must simply implement the
IContentFormattingStrategy interface.
The IContentFormatter interface
Eclipse provides two implementations of the
IContentFormatter interface:
ContentFormatter
- This implementation allows for two modes of operation: partition-aware and partition-unaware. When you use partition-aware mode, it determines the partitions of the document and applies a different formatting strategy for each one. Partition-unaware mode treats the entire document as one big partition of type
IDocument.DEFAULT_CONTENT_TYPEand applies a single formatting strategy to the entire document.
MultiPassContentFormatter
- The
MultiPassContentFormatteris so named because it makes two passes of the document, taking in two kinds of formatting strategies:
- Master formatting strategy -- The first pass, used to format the default content type
- Slave formatting strategy -- Subsequent passes, used to format all the other content types
Note: This behavior is different from the
ContentFormatter class, which takes a different formatting strategy for each content type.
So, which implementation should you choose when? If you want to format every one of your partitions in a different manner, use
ContentFormatter. If you just want to format the main code and don't much care about the rest of the stuff, use
MultiPassContentFormatter. The latter is useful in languages such as
C, where you want to format the code, but not the comments, strings, etc.
Configure your editor to use MultiPassContentFormatter
To configure your editor to use a
MultiPassContentFormatter interface:
- Override the
getContentFormatter()method in your
SourceViewerConfigurationsubclass.
- Create an instance of
MultiPassContentFormatter.
- Set the document partitioning to the
MultiPassContentFormatterobject.
- Set the master and slave formatting strategies.
- Return the formatter.
Listing 7 shows this process.
Listing 7. Configure the editor for MultiPassContentFormatter
@Override public IContentFormatter getContentFormatter(ISourceViewer sourceViewer) { MultiPassContentFormatter formatter= new MultiPassContentFormatter( getConfiguredDocumentPartitioning(sourceViewer), IDocument.DEFAULT_CONTENT_TYPE); formatter.setMasterStrategy(new MasterFormattingStrategy()); formatter.setSlaveStrategy( new CommentFormattingStrategy(), IMyPartitions.COMMENTS); return formatter; }
Text hovers and tab widths
Text hovers
You've seen the yellow window that appears when you hover your mouse pointer over a method or class name describing its parameters or showing its documentation (see Figure 3). You can add them to your editor, too.
Figure 3. Text hover showing documentation for a Java interface
Add text hover functionality to your IDE editor
To add text hover functionality to your IDE editor, you must implement the
ITextHover interface. This interface contains just two methods:
getHoverRegion(ITextViewer textViewer, int offset)
- Given an offset in the editor, this method computes the region of text that will be used to compute the information for the hover window. For example, to provide a hover for each method, place the cursor inside the method, look at the offset, and return the region containing the entire method, which would then be used to compute the hover text.
getHoverInfo(ITextViewer textViewer, IRegion hoverRegion)
- Given a region to calculate the information, this method returns a string containing the information to display.
The way in which you implement this interface depends on the kind of information you want to display. Most likely, after getting a "hover region," you will need to look the region up in your Abstract Syntax Tree (AST) to determine what kind of information (if any) can be shown at that particular location.
To configure your source viewer after you have implemented the
ITextHover interface:
- Override the
getTextHover()method in your
SourceViewerConfigurationsubclass.
- Return the implementation of
ITextHover. You can return a different implementation for each partition by looking at the
contentTypestring passed to the
getTextHover()method.
The code for this process:
@Override public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) { return new MyTextHover(); }
Tab widths
This one is simple: Every time the user presses the Tab key in the editor, the caret moves ahead by a certain number of characters. The default is four characters, so when the user presses Tab, the editor leaves four spaces blank.
You can change this default by overriding the
getTabWidth() method of the
SourceViewerConfiguration subclass and returning an integer that specifies the tab width. The following code configures the editor to use a tab width of six spaces:
@Override public int getTabWidth(ISourceViewer sourceViewer) { return 6; }
From a good IDE to great IDE
So far, this series has shown the architecture and the core of an IDE. It has also provided an in-depth look at the Eclipse APIs you can use to create the UI for your IDE. Say you're about to create the next great IDE for Ruby or Python, but wait -- there's a catch. If you were to follow exactly what you've learned to this point and implement all of the UI formatting and customization, you'd end up with a good IDE. But you won't end up with a great IDE.
Now, I'll let you in on some of the biggest secrets in IDE design. I'll show you how to make your IDE great -- how to make it such that your users will turn into fans and talk about your creation in forums and newsgroups.
You might find me discussing some of the features of ANTLR Studio here and there, but I can't explain how to go about implementing the features unless I explain the features themselves. The section that follows presents features of commercial-quality IDEs and, for some features, compares the approaches that JDT and the ANTLR Studio take to implementing them.
Syntax highlighting
If you were to plainly implement syntax highlighting functionality by using the Eclipse APIs in Part 2, you'll be able to highlight the keywords, comments, and strings in your language easily. The Eclipse APIs allow you to add very basic functionality. However, you would not be able to add highlighting such as you could with JDT or ANTLR Studio.
The JDT approach
Apart from the usual Java keywords and comments, JDT can color elements such as method calls, variable names, field names, and class names (see Figure 4). It can even differentiate between method calls and method declarations, fields and static fields, etc, coloring each one differently.
Figure 4. Normal highlighting in Eclipse APIs and enhanced highlighting in JDT
Here's how JDT achieves this enhanced functionality:
- It uses the Eclipse API and its own mechanism.
- For keywords such as int and return, JDT uses the normal Eclipse APIs to color them.
- For elements such as method calls and local variables, JDT runs a background thread that after a certain interval of time, checks its AST and analyzes the modified portions of the document to find out the semantics of that portion of code. It then applies the appropriate color to it.
- This check results in the appearance of certain colorings -- like those for method calls and static fields -- after a short lag, while elements like keywords and comments are highlighted instantly.
- Because the keywords are highlighted instantly anyway and the delay for highlighting other elements is short, the user doesn't notice it.
The ANTLR Studio approach
ANTLR Studio can differentiate between the various sections of an ANTLR grammar and color each one in a different way. Thus, identifiers that are keywords in that section are painted as keywords only in that section, not in others (see Figure 5). Even comments in one section are painted differently from comments in another.
Figure 5. ANTLR Studio can color different sections of an ANTLR grammar differently
The process that ANTLR Studio uses to achieve this enhanced functionality:
- ANTLR Studio runs a proprietary analysis algorithm in the same thread as the editor. The main feature of this analysis is that there is virtually no delay in scanning the damaged portions of the document.
- Running in the same thread results in no delay in syntax coloring, and you still get all the colors you want.
Although this approach is the best from a user point of view (because everything is instantaneous), you must be wary because even the slightest delay in the UI thread can cause a significant lag between the user typing the character and the character's appearance on the screen. Even the slightest lag will make your IDE unusable. So, weigh the benefits against the danger before you put everything in a single thread.
Code completion
What can possibly be done more to code completion, you ask? Well, if you use the Eclipse APIs, you'll be able to add code completion nicely in your editor. But let's see how commercial IDEs tackle this functionality.
The JDT approach
JDT uses a unique process to implement code completion:
- Its code completion window automatically arranges the members most likely to be used on top, irrespective of their alphabetical position.
- JDT accepts camel-case input, so if you type
NPEin Eclipse JDT V3.2, then press Ctrl+Space, JDT shows a window containing
NullPointerException.
- JDT can recognize subclasses, so if you type
List a = new, then press Ctrl+Space, JDT shows
ArrayListat the top (see Figure 6).
Figure 6. JDT shows Vector and ArrayList classes as possible completions
- JDT rearranges the most frequently used subclass on the top, so that those classes are available as the first selection.
- When you're typing a new class that is not yet in the list of imports and you press Ctrl+Space, you can still see that class name available for completion. Selecting the class adds an import for it automatically.
When you're creating the code for this functionality in JDT, keep in mind that you must provide these features yourself. Eclipse won't do it for you.
The ANTLR Studio approach
Like JDT, ANTLR Studio also has a unique approach to code completion functionality:
- ANTLR Studio doesn't require you to press Ctrl+Space or any other key combination. Completions appear automatically and usually contain what's needed.
- You needn't define grammar rules before they appear in code completions. This is especially useful because in ANTLR Studio, grammar rules are used before they are defined, (see Figure 7).
Figure 7. ANTLR Studio shows completions for rules even though not declared
Note: The red squiggly line shown below the first reference to the mexpr rule shows that it is not declared.
- There is no delay in the editor, even when windows continue to appear while you're typing. Users don't notice any form of slowdown in the editor, even with the huge number of calculations performed on each keystroke.
To achieve its code completion functionality, ANTLR Studio runs the parser in the main UI thread and doesn't need to wait for a background thread to finish. It also uses a fully incremental lexer and parser, which significantly reduces the number of calculations to be performed, allowing it to run the analysis in the UI thread.
Memory requirements
As the number of files in the projects of your IDEs grows, your IDE will require more and more memory and, thus, run more slowly. You cannot keep all the files in memory at all times. You must use a lazy, delayed loading approach to load only what's needed and discard those elements as soon as they're no longer necessary.
ANTLR Studio has only one or two grammar files per project. Most of the time, they have no dependencies with each other. Although ANTLR Studio can read token definitions from external files, and for those situations, the files are loaded lazily and only when needed. They are also monitored for changes at regular intervals.
Speed
If your IDE is slow, your editor lags while you're typing, or projects take ages to load, it will never succeed in the marketplace. You cannot compromise on speed. If such delays occur, take another good look at your design. Try to use an incremental parser and lexer as well as the delta algorithms described in Part 1. Use multiple threads: If your IDE isn't fast, it should at least give the illusion of being fast.
As of this writing, Eclipse V3.2 loads a huge workspace almost instantaneously. It does this by processing files in the background and making heavy use of delayed loading. Although this behavior results in nearly instant loads, it does slow the IDE a bit.
Elements not discussed that you should implement
No matter how many installments this tutorial series could be, IDEs are such a huge topic that there will always be something left to cover. Unfortunately, to code decent IDEs, you must know most of what there is to know about them. Here's a brief summary of the elements this tutorial series didn't cover in detail, but that you should implement in your IDE to make it successful.
Debugging
This series didn't discuss debugging technology, but you definitely need a debugger in your IDE if it's to succeed (see Figure 8). The debugger APIs in Eclipse are a huge topic worthy of tutorials of their own. You must also do an immense amount of coding apart from simply using the Eclipse API to implement the debugger for the programming language your IDE supports.
Figure 8. The JDT debugger
In this regard, ANTLR Studio's Fluid Debugger integrates with the Eclipse JDT debugger and provides a seamless debugging experience with the Java code so you don't feel that you're in a separate IDE. Using Fluid Debugger, you can step over rules and Java code embedded in ANTLR grammar files (see Figure 9). It does this using the JSR 45 standard, along with proprietary debugging algorithms.
Figure 9. ANTLR Studio's Fluid Debugger
Build system
Your IDE definitely needs a build system so users can get a working executable from the source code. Both JDT and ANTLR Studio compile the code in the background whenever you save a file. Because this behavior is the de-facto standard for Eclipse IDEs and is convenient for users (because there's no extra, explicit build step), I recommend following the same model, instead of providing an explicit Build button.
Search
Implement code search in your IDE so users can search elements such as variable references and method calls. In large projects, this functionality is invaluable, as Figure 10 shows.
Figure 10. Search in Eclipse JDT
QuickFixes
QuickFixes are becoming the norm in modern IDEs (see Figure 11). Note that you must have a robust error-handling mechanism that can detect errors and provide solutions for them.
Figure 11. QuickFixes in the Java IDE
Refactorings
Refactorings ease the development load. A successful IDE must have a fair number of refactorings for programmers to fall in love with it.
Integrations
Because you're coding on top of Eclipse, make sure that you follow Eclipse conventions and provide a highly integrated experience so users don't have to learn new ways of performing certain tasks. Heavy integration is especially important if the language your IDE supports is a sort of domain-specific language (DSL) on top of existing languages, such as the Java programming language.
One of my mantras while designing ANTLR Studio was that it should not feel like ANTLR Studio at all, but rather like Eclipse JDT, so users feel that they're working in the same Java environment. The more highly integrated the experience of your IDE, the more experienced users will find it easier to switch to your product.
Diff functionality
Your IDE should provide a visual diff feature that is aware of the programming language of your IDE. For example, JDT has an excellent Java-aware diff utility that can, for example, show exactly which methods have been added, removed, or modified between two files (see Figure 12). It can also ignore irrelevant items, such as whether two methods are in a different location in two files, because in the Java programming language, the order in which methods are defined doesn't matter.
Figure 12. The JDT diff utility is Java-aware
Documentation
Finally, don't forget to provide high-quality documentation for your IDE's features. I have seen many otherwise great IDEs with little documentation, leaving users to flail about, guessing how to use the tools. The only thing worse than writing documentation is using a tool without documentation.
Conclusion
The features and techniques outline in this "Create a commercial-quality Eclipse IDE" series are designed to help Eclipse IDE developers build easy-to-use tools. Designing IDEs is major task, and there are details I haven't covered. Like a good -- or even bad -- action movie, there are opportunities for sequels.
Until then, design a great IDE, create a nice Web site documenting and touting it, and make a name for yourself.
Resources
Learn
- Learn more about the Eclipse Foundation and its many projects.
- For an excellent introduction to the Eclipse platform, see "Getting started with the Eclipse Platform."
- Expand your Eclipse skills by checking out IBM developerWorks' Eclipse project resources.
- Browse all of the Eclipse content on developerWorks.
- Visit the developerWorks Open source zone for extensive how-to information, tools, and project updates to help you develop with open source technologies and use them with IBM's products.
- developerWorks podcasts include interesting interviews and discussions for software developers.
- Stay current with developerWorks technical events and webcasts.
Get products and technologies
- Download the Eclipse PDE to try the example code shown in the tutorial.
- Download an evaluation copy of ANTLR Studio to get a feel of the advanced features discusses in this tutorial.
- Check out the latest Eclipse technology downloads at IBM alphaWorks.
- Innovate your next open source development project with IBM trial software, available for download or on DVD.
Discuss
- Read Prashant Deva's blog for tips on IDE design and information about the internals of ANTLR Studio.
- Check out the blog of Cyrus N, the designer of the Intellisense functionality in Microsoft Visual Studio, for excellent tips on designing the core of IDEs and the internals of Visual Studio.
- The Eclipse newsgroups offer. | http://www.ibm.com/developerworks/opensource/tutorials/os-ecl-commplgin3/ | CC-MAIN-2014-41 | en | refinedweb |
07 August 2008 15:55 [Source: ICIS news]
TORONTO (ICIS news)--Rentech has started producing synthetic jet and diesel fuels at a 420 gal/day demonstration plant in Commerce City, Colorado, the US fuel and energy technology firm said on Thursday.
"The initial production run of ultra clean synthetic fuels at our product demonstration unit has been very successful and demonstrates the strength of the Rentech process,” said CEO Hunt Ramsbottom.
?xml:namespace>
“Once product samples from the unit are tested and approved by our potential customers, licensees and partners, we believe we will be well positioned to enter into contracts with them."
The plant runs on proprietary technology that converts synthesis gas from carbon-bearing resources into hydrocarbons that can be processed and upgraded into ultra clean synthetic jet and diesel fuels.
It was currently producing synthetic fuels from natural gas, but once gasification was added would also be capable of producing fuels from biomass and other fossil resources, the company said.
The fuels produced were cleaner-burning and more efficient than petroleum-derived fuels, it said.
Rentech was looking into transferring the technology to commercial-scale operations, it added. | http://www.icis.com/Articles/2008/08/07/9146930/rentech-starts-synfuel-production-at-us-demo-plant.html | CC-MAIN-2014-41 | en | refinedweb |
18 June 2012 09:56 [Source: ICIS news]
SINGAPORE (ICIS)--The prices of styrene monomer (SM) in ?xml:namespace>
Offers for July parcels were at above $1,300/tonne CFR (cost & freight)
Some buying interest has emerged. “The market is generally still quiet, but bids for August cargoes have appeared at $1,290-1,300/tonne CFR China,” said a trader in
Most players in Asia are adopting a wait-and-see stance, preferring to wait for the
A numbers of traders in
“The Chinese manufacturing season in the third quarter should spur demand for resins and SM in the near term,” said a South Korean trader.
Others, however, are less sanguine and expect further volatility in the market, given the ongoing debt woes in the eurozone. The weak economic conditions in the
“The market has strengthened after the Greek election over the weekend, but risks remain as there are still a lot of uncertainties out there,” said another trader in
Some end-users of SM are emerging from the sidelines to enquire about cargoes and prices, which appeared to have bottomed out.
“If more end-users appear, that will signal that the market could continue to firm,” the South Korean trader added. (S | http://www.icis.com/Articles/2012/06/18/9570279/asias-sm-prices-rise-20tonne-over-weekend-on-buoyant-crude.html | CC-MAIN-2014-41 | en | refinedweb |
I’m currently working on a few Data Visualization projects and am using WPF most of the time. Charting controls are very useful for the one related to statistics and data handling. WPF toolkit is free and open source, however is used by few because of its limited charting support. In my opinion, it is quite useful and straightforward to use.
Here, I’m just demonstrating the basic charting controls and setting data for display. For articles related to this in future, I shall demonstrate advanced features of WPF Toolkit.
No prior knowledge of WPF is required. You just need to be aware of HTML (which I’m pretty sure everyone is, nowadays). XAML coding is pretty fun.
Firstly, I’ll mention the installation steps and then will dive into coding XAML and related C# files for visualizing static set of data.
Install WPF Toolkit from this site:
(Please check the installation and usage instructions as mentioned here.)
Add new WPF application in Visual Studio.
If you are not able to view chart controls in Toolbox, right click Toolbox and select Choose Items. Then click on WPF components and select chart controls (the ones mentioned in the title). This will add the controls to your toolbox and you should be able to drag and drop them on the XAML form.
XAML (Extensible Application Markup Language) is a markup language for declarative application programming. If you are interested in knowing more about XAML, please refer to the MSDN documentation at.
As you can see in the following MainWindow.xaml code, there are a lot of <chartingToolkit:Chart> tags, each one refers to the 5 different charting controls that we are going to use.
<chartingToolkit:Chart>
<Window x:Class="WpfToolkitChart.MainWindow"
xmlns=""
xmlns:x=""
Title="MainWindow" Height="1031" Width="855" xmlns:chartingToolkit=
"clr-namespace:System.Windows.Controls.DataVisualization.Charting;
assembly=System.Windows.Controls.DataVisualization.Toolkit">
<ScrollViewer HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto" Margin="0,-28,0,28">
<Grid Height="921">
<chartingToolkit:Chart
<chartingToolkit:ColumnSeries
</chartingToolkit:Chart>
<chartingToolkit:Chart
<chartingToolkit:PieSeries
</chartingToolkit:Chart>
<chartingToolkit:Chart
<chartingToolkit:AreaSeries
</chartingToolkit:Chart>
<chartingToolkit:Chart
<chartingToolkit:BarSeries
</chartingToolkit:Chart>
<chartingToolkit:Chart
<chartingToolkit:LineSeries
</chartingToolkit:Chart>
</Grid>
</ScrollViewer>
</Window>
Beginning with the <window> tag, you can see that there is an attribute that says xmlns:chartingToolkit which is basically a namespace referring to the added WPF Toolkit.
<window>
xmlns:chartingToolkit
I’ve used <ScrollViewer> tag in order to add horizontal and vertical scrollbars to the XAML page.
<ScrollViewer>
Now starting with first charting control, columnChart, drag and drop the column series control in toolbox on XAML page and you will see a rectangle with nothing inside. Look in the XAML window (usually below the Designer), and you will see:
columnChart
<chartingToolkit:ColumnSeries
Now all the charting controls needs to be encapsulated in <chartingToolkit:Chart> (which is a good practice). It has different attributes such as height, horizontal alignment, name, title, width, etc. which are just concerned with the way in which it appears on the page.
Our basic concern is understanding the attributes of <chartingTookit:columnSeries> here and in all other charting controls. I’m using three attributes. DependentValuePath and IndependentValuePath are related to the Axis of the Chart (i.e. X-axis, Y-axis). “Value” and “Key” as assigned to them respectively - this is because I’m using KeyValuePair<> data type in my data model (which has Key and Value). You can also use Dictionary or any other data type by just making sure that you have two parameters that are interdependent for visualization. Itemsource attribute is used for binding our data to the control.
<chartingTookit:columnSeries>
DependentValuePath
IndependentValuePath
Value
Key
KeyValuePair<>
Key
Dictionary
Itemsource
Follow the same as above for all the other controls as mentioned and now we shall assign the data model to the controls.
As you can see in the MainWindow.xaml.cs file, it is pretty straightforward with the way we are assigning data model.
namespace WpfToolkitChart
{
/// <span class="code-SummaryComment"><summary>
</span> /// Interaction logic for MainWindow.xaml
/// <span class="code-SummaryComment"></summary>
</span> public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
showColumnChart();
}
private void showColumnChart()
{
List<KeyValuePair<string, int>>
I’m using static list with 5 entries. DataContext is the property assigned to charting controls and you can assign the list directly to the controls and you are good to go.
static
DataContext
Compile and run and you should see the following:
I hope this article provides you with enough assistance to keep the work going on for visualizing information. Information Visualization is changing the way people look at data and in my view, it is going to play a key role in future.
I’ll explain advanced features related to assigning complex data model to controls in the future.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
List<List<KeyValuePair<String, int>>> list = new List<List<KeyValuePair<String, int>>>();
List<KeyValuePair<string, int>> tList1 = new List<KeyValuePair<string, int>>();
List<KeyValuePair<string, int>> tList2 = new List<KeyValuePair<string, int>>();
List<KeyValuePair<string, int>> tList3 = new List<KeyValuePair<string, int>>();
tList1.Add(new KeyValuePair<string, int>("test1", 40));
tList1.Add(new KeyValuePair<string, int>("test1", 40));
tList1.Add(new KeyValuePair<string, int>("test1", 60));
tList2.Add(new KeyValuePair<string, int>("test2", 20));
tList2.Add(new KeyValuePair<string, int>("test2", 40));
tList2.Add(new KeyValuePair<string, int>("test2", 60));
tList3.Add(new KeyValuePair<string, int>("test3", 60));
tList3.Add(new KeyValuePair<string, int>("test3", 40));
tList3.Add(new KeyValuePair<string, int>("test3", 60));
list.Add(tList1);
list.Add(tList2);
list.Add(tList3);
columnChart.DataContext = list;
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/196502/WPF-Toolkit-Charting-Controls-Line-Bar-Area-Pie-Co?msg=4336015&PageFlow=FixedWidth | CC-MAIN-2014-41 | en | refinedweb |
03 June 2009 12:48 [Source: ICIS news]
LONDON (ICIS news)--Germany-based polyester producer Trevira has filed for the start of insolvency proceedings with a restructuring plan in a local court, its Indian parent company Reliance Industries said on Wednesday.
The company said the filing followed major efforts to overcome the impact of the industrial downturn in ?xml:namespace>
“European textile manufacturers are currently facing a considerable drop in demand for their products, while the cost of production and employment is increasing and competition from Asian and Eastern European industries is stronger than ever,” Reliance said in a filing published on the Bombay stock exchange.
Last month, Trevira appointed lawyer and insolvency expert Elke Bauerle as its new managing director to restructure the company.
Earlier in the month, CEO Uwe Wohner left the company.
Trevira employs a staff of about 1,800 in Europe and has five production sites in four European countries –
Reliance Industries bought the business in 2004 from Deutsche Bank.
Trevira was previously part of Hoechst, the former German chemicals and pharmaceuticals major that later merged with French company Rhone-Poulenc to form Avent | http://www.icis.com/Articles/2009/06/03/9222042/Trevira-files-insolvency-application-with-Germany-court.html | CC-MAIN-2014-41 | en | refinedweb |
Re: Why aren't namespaces used more?
Discussion in 'C++' started by Jason, aren't these more popular (Myghty & Pylons)?Karlo Lozovina, Apr 16, 2006, in forum: Python
- Replies:
- 1
- Views:
- 311
- Jonathan Ellis
- Apr 16, 2006
Forward declarations aren't allowed any more?Adam Nielsen, Jul 29, 2008, in forum: C++
- Replies:
- 8
- Views:
- 279
- James Kanze
- Jul 30, 2008
Control Event Handlers aren't called when used in PlaceHolderCraig, Mar 29, 2006, in forum: ASP .Net Building Controls
- Replies:
- 1
- Views:
- 128
- sam
- Mar 29, 2006 | http://www.thecodingforums.com/threads/re-why-arent-namespaces-used-more.276806/ | CC-MAIN-2014-41 | en | refinedweb |
In this paper we will compare J2EE and .Net technologies. We will explore the Interoperability scenarios and available options. Also, this paper is written for .Net developers, who are at advanced level of .Net knowledge and having no or minimum knowledge of J2EE.
"Interoperability: The capability to communicate, execute programs, or transfer data among various functional units in a manner that requires the user to have little or no knowledge of the unique characteristics of those units."—ISO/IEC 2382 Information Technology Vocabulary
Many Enterprises have been building based on mixed environments i.e. J2EE and/or .Net. If company sees a need of new application to their current enterprise, first thinking is to reuse and/or integrate the new application with existing applications and systems. Integrating systems with partners and suppliers is another increasing demand by businesses/enterprises, where security, performance and scalability come as standard requirements.
Migrating, rebuilding or replicating the functionality is not possible in most of cases. Even if we decide to migrate application(s) to other platform, most of the time migration has to be phased and integrated with other platform until complete system migration.
Interoperability allows the core systems to communicate with internal and external applications including partners and suppliers. Performance overhead, security and reduction in functionalities should be considered while designing solutions for interoperability.
In coming sections we will explore following topics:
Following are the common Interoperability scenarios in an Enterprise:
Note: Above are most common scenarios but not all, for instance there is also a possibility of .Net Presentation and J2EE Presentation layer interoperability.Please See “Interoperability Technologies” section for mapping between scenarios and technologies recommendation.
Following diagrams maps the layers and shows above interoperability scenarios:
There are multiple technologies for .Net and J2EE interoperability. Each technology has pros and cons. It also depends on your functional and/or non-functional requirements i.e. performance or scalability. Following are the technologies, which we can use for interoperability between J2EE and .Net:
*Please note following is a high level overview of each technology from interoperability point of view. For more information please use appropriate resources.
XML web services have been matured by the time and are supported by both J2EE and .Net. Web services provide an interface for communicating with other applications and systems. However, web services hide the method level implementation, therefore applications can only communicate through defined interfaces and contracts. Web service is a good choice for Presentation to Business, Business to Business and Business to Data interoperability.
Using XML web services, you cannot call a class method or access J2EE classes from .Net or vice-versa. Runtime Bridges provides the ability to access classes from one platform to another. Runtime Bridges are developed by 3rd parties, JNBridgePro and Ja.Net are most prominent in the market. Runtime Bridges allows you to use .Net Remoting to handle classes at Java side.
Messaging and Share databases provide asynchronous communication mechanism. Messaging is based on MSMQ and IBM MQSeries and both supports security, message recording and transactions. Using the share database technique, one common database (SQL Server or Oracle etc.) is being accessed by .Net and J2EE applications. .Net application uses ODBC and J2EE application uses JDBC.
Integration Brokers are typically built on messaging framework that provides the integration and automation between business processes across distributed applications and Enterprise. Integration brokers are a good answer for integration of partners and suppliers. BizTalk Server, CommerceBroker and IBM MQSeries are the most well-known integration brokers in the market.
Following table shows the mapping between interpretability scenarios and technologies. These recommendations are from Microsoft and could differ to your problem and solution.
Web Services
Runtime Bridges
Messaging
Share Databases
Integration Brokers
Presentation to Presentation
X
Presentation to Business
Business to Business
Business to Data
Unlike Microsoft .NET, Java 2 Platform, Enterprise Edition or J2EE is a set of linked specification but not a product. These specifications consist of a series of downloadable .PDF files that describe application agreements and the makeup of the containers in which these applications run.
Sun Microsystems developed Java as platform and a programming language.There are currently three editions of the Java platform:
Note: The term “Java” mostly refers to functionality available within J2SE. Areas that require the Enterprise Edition include the term J2EE.
For more information about J2EE history please visit
As mentioned before J2EE is a series of specification but platform unlike .Net. There are other differences between J2EE and .Net, which should also be understood. Differences can be categorized in three main areas:
As we know, .Net can run only on Windows platform but Java was designed to run on multiple platforms i.e. Windows, UNIX, Linux, MacOS and BeOS.
We can write applications in Java using Java Programming Language only but in .Net you can write applications in any language, which is supported by .Net.
There is also a major difference between the two platforms at application run time. When you build a project based on a .NET language, the output consists of MSIL code that the JIT compiler compiles at runtime. To deploy a Java program, you compile the application to create Java bytecode. The JVM running on the target operating system then interprets this bytecode to produce the relevant instructions.
Note: There are also Java JIT compilers that work in a similar fashion to the .NET Framework component.
Some of the vendors have created their own implementations of J2EE specification, which were built by Sun Microsystems. Following vendors implemented these specifications:
J2EE also includes additional components, which were evolved over the past decade:
You can map few components in .Net e.g.,JMS is equivalent to System.Messaging namespace.
Following table helps to understand the comparison of J2EE and .Net features.
Feature
J2EE
.NET
Type of technology
Standard
Product
Middleware Vendors
30+
Microsoft
Interpreter
JRE
CLR
Dynamic Web Pages
JSP
ASP.NET
Middle-Tier/Server Side Components
EJB
.NET Managed Components
Database access
JDBC SQL/J
ADO.NET
SOAP, WSDL, UDDI
Yes
Implicit middleware(load-balancing, etc)
Web Apps Hosting
Multiple (depends on vendor implementation)
Internet Information Server
Directory Access
Java Naming and Directory Service (JNDI) through LDAP
Active Directory Services Interface (ADSI) through LDAP
Remote Invocation
RMI-IIOP
.NET Remoting
JMS
Microsoft Message Queuing
Transactional Support
JTA
COM+/Distributed Transaction Controller (DTC)
It is not possible or appropriate for Enterprises to build systems based on only J2EE or .Net technologies. Some organizations have already built their core systems using J2EE or .Net platform and interoperability is an ongoing requirement for enterprises. There are different types of Interoperability i.e. Presentation to Business or Business to Business layers and there are multiple recommended technologies to these interoperability types. In past decade SOA and Enterprise Service Bus have become prominent and mature in Enterprises .These techniques will provide more scalable and extendable architectures, which makes interoperability much easy and seamless.. | http://www.codeproject.com/Articles/22560/NET-and-J2EE-interoperability-for-Net-Developers?fid=958401&df=90&mpp=10&sort=Position&spc=None&tid=2378250 | CC-MAIN-2014-41 | en | refinedweb |
04 March 2008 22:33 [Source: ICIS news]
HOUSTON (ICIS news)--The ICIS Petrochemical Index (IPEX) for March rose to 306.97, an increase of 0.7% from February’s reading of 304.72.
The index has now risen for five consecutive months, but the rate of increase in March slowed sharply from February’s 3.4% climb.
The IPEX is now 20% higher than in March 2007.
Among the 12 products within the index, eight rose and four declined. But across most of the petrochemicals, changes were small.
The most dramatic decline was in methanol, which on a global basis dropped by 6.7%. Although prices rose marginally in Europe and fell by 2.7% in ?xml:namespace>
Despite some gains in Europe, ethylene and propylene also declined, with flat-to-lower pricing in the
Benzene was the most significant gainer, up 9.2% globally.
That advance was led by the
US March benzene contracts rose amid elevated spot prices and stronger energy values., styrene, methanol, butadiene, polyvinyl chloride (PVC), polyethylene (PE), polypropylene (PP), and polystyrene | http://www.icis.com/Articles/2008/03/04/9105815/march-icis-petrochemical-index-ipex-rises-0.7.html | CC-MAIN-2014-41 | en | refinedweb |
01 February 2012 07:39 [Source: ICIS news]
SINGAPORE (ICIS)--Jiangsu Wuxi Dongwo Huaneng Corp has restarted its 200,000 tonne/year sulphuric acid plant in eastern ?xml:namespace>
The company had conducted maintenance at the plant that was shut on 15 January, mainly because of soft market conditions ahead of the Lunar New Year holiday in
China celebrated the Lunar New Year on 22-28 | http://www.icis.com/Articles/2012/02/01/9528270/chinas-jiangsu-wuxi-dongwo-huaneng-restarts-sulphuric-acid-plant.html | CC-MAIN-2014-41 | en | refinedweb |
CS::Animation::iSkeletonRandomNode Struct Reference
[Mesh plugins]
An animation node that selects randomly the sub-nodes to be played. More...
#include <imesh/animnode/skeleton2anim.h>
Inheritance diagram for CS::Animation::iSkeletonRandomNode:
Detailed Description
An animation node that selects randomly the sub-nodes to be played.
It is defined by a CS::Animation::iSkeletonRandomNodeFactory.
Main creators of instances implementing this interface:
Main ways to get pointers to this interface:
Main users of this interface:
Definition at line 961 of file skeleton2anim.h.
The documentation for this struct was generated from the following file:
- imesh/animnode/skeleton2anim.h
Generated for Crystal Space 2.0 by doxygen 1.6.1 | http://www.crystalspace3d.org/docs/online/new0/structCS_1_1Animation_1_1iSkeletonRandomNode.html | CC-MAIN-2014-41 | en | refinedweb |
12 September 2013 20:49 [Source: ICIS news]
HOUSTON (ICIS)--In an attempt to mitigate harmful impacts to bees that pollinate a vast array of food crops across North America, DuPont Pioneer has begun selling neonicotinoid-free hybrid corn and soybean seeds in ?xml:namespace>
Recently, the health of bees have come under more intense scrutiny as growing numbers of researchers and scientists have proposed that the use of neonicotinoid insecticides are a likely cause of bee colony collapse disorder.
It is suspected these chemicals have the ability to damage the brains of the bees, resulting in negative repercussions including making them lose the ability to recognise floral scents.
Colony collapse disorder is a situation where a colony’s bees disappear and never return. First noted in 2006, scientists said in the
The products are only being sold in
DuPont Technical Services Manager Dave Harwood said the new varieties will still offer a fungicide-based seed treatment, and that it was good option for agricultural producers who want to be good stewards of the environment without compromising yield potentials.
He said there have been company discussions about these products being offered to US farmers, but that no decision has been made.
“The situation that has developed here has been an association made with these neonicotinoids, either acute injury to bees, or there has been speculation, that there’s been more of a chronic effect,” said | http://www.icis.com/Articles/2013/09/12/9705569/dupont-pioneer-selling-neonicotinoid-free-seed-in-canada.html | CC-MAIN-2014-41 | en | refinedweb |
Using ETags to Reduce Bandwith & Workload with Spring & Hibernate
IntroductionThe recent groundswell of interest in the REST style of application architecture has highlighted the elegant design of the web. We are now beginning to understand the inherent scalability and resilience behind the "Architecture of the World Wide Web", and are exploring ways to further embrace it's paradigms. In this article, we will explore one of the lessor known facilities available to web application developers, the humble "ETag Response Header", and how to integrate its use in a Spring Framework dynamic web application to improve application performance and scalability.
The Spring Framework application we will be using is based on the "petclinic" application. The download includes instructions on how to add the necessary configuration and source code so that you can try it out on your own.
What is an "ETag"?The HTTP protocol specification defines an ETag as the "entity value for the requested variant" (see - Section 14.19.) Another way of saying this is that the ETag is a token that can be associated with web resource. The web resource is typically a web page, but could also be a JSON or XML document. The server is solely responsible for figuring out what the token is and means, and transfers it to the client in the HTTP Response Header.
How can ETags help improve performance?
ETags are used in conjunction with the "If-None-Match" header on a GET request by savvy server developers to take advantage of the client's (e.g. browser) cache. Because the server generated the ETag in the first place, it can use it later to determine if the page has changed. Essentially, the client asks the server to validate it's cache by passing the token back to the server.
The process looks like this:
- Client requests a page (A).
- Server sends back page A, plus an ETag for A.
- Client renders the page then caches it, along with the ETag.
- Client requests page A again, passing along the ETag it got back from the server the last time it made the request.
- Server examines the ETag and determines that the page hasn't changed since last time the client requested it, so sends back a response of 304 (Not Modified) with an empty body.
The remainder of the article will present two approaches that take advantage of ETags in a web application built on the Spring Framework using Spring MVC. First we will use a Servlet 2.3 Filter to apply an ETag generated using an MD5 checksum of the rendered view (a "shallow" ETag implementation). The second approach uses a more sophisticated method to track changes in the model used by the view to determine ETag validity (a "deep ETag" implementation). Although we are using Spring MVC, the techniques apply to any MVC style web framework.
Before we go on, it is important to note here that the techniques being presented here are intended to improve the performance of dynamically generated pages. Existing optimization techniques should also be considered as part of a holistic optimization and tuning analysis of your application's performance profile (see sidebar).
Web caching top to bottom
This article deals primarily with using HTTP caching technology for dynamically generated pages. When looking at improving the performance of a web application, a holistic, top-to-bottom approach should be taken. To this end, it is important to understand the layers that a HTTP request goes through, and apply the appropriate technology depending on where you see hot spots. For example:
- Apache can be used in front of your servlet container to handle static files such as images and javascript, and can also create ETag response headers using the FileETag directive.
- Use optimization techniques for javascript files, such as combining the files into one file and compressing whitespace.
- Utilize GZip and Cache-Control headers.
- To help determine where your pain points are in your Spring Framework application, consider using the JamonPerformanceMonitorInterceptor.
- Make sure you fully take advantage of the ORM tool's caching mechanism so that objects are not continually being re-constituted from the database. It is worth the time to figure out how to get query caching working for you.
- Ensure that you minimize the amount of data retrieved from the database, especially with large lists. Large lists should be traversed a page at a time, with each page requesting a small subset of the larger list.
- Minimize what goes into the HTTP session. This frees up memory, and will help when the time comes to cluster the application tier.
- Use a database profiling tool to see what indexes are being used when querying, and that entire tables are not being locked when doing updates.
Of course, the golden adage of performance optimization applies: measure twice, cut once. Oh wait, that is for carpentry, but nonetheless it works here as well!
A Content Body ETag Filter
The first approach we will look at is to create a Servlet Filter that will generate its ETag token based on the content of the page - the "View" in MVC. At first glance, any performance gains using this approach may seem counter-intuitive. We still have to generate the page, and have added computation cycles to generate the token. However, the idea here is to reduce bandwidth utilization. This is particularly beneficial in large latency situations such as when your host and client are on separate sides of the planet. I have seen latency of up to 350 ms with a server in NYC hosting an application used by the Tokyo office. Depending on the number of concurrent users, this can become a significant bottleneck.
The Code
The technique we use to generate the token is based on computing an MD5 hash from the content of the page. This is done by creating a wrapper around the response. The wrapper uses a byte array to hold the generated content and after the filter chain processing completes we compute the token using an MD5 hash of the array.
The implementation of the doFilter method is shown below.
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,Listing 1: ETagContentFilter.doFilter
ServletException {
HttpServletRequest servletRequest = (HttpServletRequest) req;
HttpServletResponse servletResponse = (HttpServletResponse) res;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ETagResponseWrapper wrappedResponse = new ETagResponseWrapper(servletResponse, baos);
chain.doFilter(servletRequest, wrappedResponse);
byte[] bytes = baos.toByteArray();
String token = '"' + ETagComputeUtils.getMd5Digest(bytes) + '"';
servletResponse.setHeader("ETag", token); // always store the ETag in the header
String previousToken = servletRequest.getHeader("If-None-Match");
if (previousToken != null && previousToken.equals(token)) { // compare previous token with current one
logger.debug("ETag match: returning 304 Not Modified");
servletResponse.sendError(HttpServletResponse.SC_NOT_MODIFIED);
// use the same date we sent when we created the ETag the first time through
servletResponse.setHeader("Last-Modified", servletRequest.getHeader("If-Modified-Since"));
} else { // first time through - set last modified time to now
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MILLISECOND, 0);
Date lastModified = cal.getTime();
servletResponse.setDateHeader("Last-Modified", lastModified.getTime());
logger.debug("Writing body content");
servletResponse.setContentLength(bytes.length);
ServletOutputStream sos = servletResponse.getOutputStream();
sos.write(bytes);
sos.flush();
sos.close();
}
}
You will notice that we also set the Last-Modified header. This is considered good form for server generated content as it caters for clients that don't understand ETag headers.
The sample code uses a utility class EtagComputeUtils to generate a byte array representation of an object and to handle the MD 5 digest logic. I have used a javax.security MessageDigest to compute the MD 5 hash code.
public static byte[] serialize(Object obj) throws IOException {Listing 2: ETagComputeUtils
byte[] byteArray = null;
ByteArrayOutputStream baos = null;
ObjectOutputStream out = null;
try {
// These objects are closed in the finally.
baos = new ByteArrayOutputStream();
out = new ObjectOutputStream(baos);
out.writeObject(obj);
byteArray = baos.toByteArray();
} finally {
if (out != null) {
out.close();
}
}
return byteArray;
}
public static String getMd5Digest(byte[] bytes) {
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("MD5 cryptographic algorithm is not available.", e);
}
byte[] messageDigest = md.digest(bytes);
BigInteger number = new BigInteger(1, messageDigest);
// prepend a zero to get a "proper" MD5 hash value
StringBuffer sb = new StringBuffer('0');
sb.append(number.toString(16));
return sb.toString();
}
Installing the filter in web.xml is straightforward.
<filter>Listing 3: Configuration of the filter in web.xml.
<filter-name>ETag Content Filter</filter-name>
<filter-class>org.springframework.samples.petclinic.web.ETagContentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ETag Content Filter</filter-name>
<url-pattern>/*.htm</url-pattern>
</filter-mapping>
Every .htm file will be filtered using the EtagContentFilter, which will return an empty body HTTP response if the page has not changed since the client last requested it.
The approach we have shown here is useful for certain types of pages. However, there are a couple of disadvantages:
- We are computing the ETag value after the page has been rendered on the server, but before sending it back to the client. If there is a ETag match, there really is no need to pull in the data for the model as the rendered page will not be sent to the client.
- For pages that do things like render the date and time in a footer, each page will be different, even if the content hasn't actually changed.
In the next section, we will look at an alternative approach to the problem that overcomes some of these limitations by understanding more about the underlying data used to build the page.
An ETag Interceptor
The Spring MVC HTTP Request processing pipeline includes the ability to plug in an Interceptor before a controller has the chance to process the request. This is an ideal place to apply our ETag comparison logic so that if we find the data that is used to build a page hasn't changed we can avoid further processing.
The trick here is how do you know if the data that makes up the page has changed? For the purposes of this article, I created a simple ModifiedObjectTracker that keeps track of insert, update and delete operations via Hibernate event listeners. The tracker keeps a unique number for each view in the application, and a map of what Hibernate entities impact each view. Whenever a POJO is changed a counter is incremented for the views that the entity is used in. We use the count as the ETag, so when the client sends it back we know if one of the objects behind the page has been modified.
The Code
We will start with ModifiedObjectTracker:
public interface ModifiedObjectTracker {
void notifyModified(> String entity);
}
Simple enough right? The implementation is a bit more interesting. Any time an entity is changed, we update a counter for each view that is affected by the change:
public void notifyModified(String entity) {
// entityViewMap is a map of entity -> list of view names
List
views = getEntityViewMap().get(entity);views = getEntityViewMap().get(entity);
if (views == null) {
return; // no views are configured for this entity
}
synchronized (counts) {
for (String view : views) {
Integer count = counts.get(view);
counts.put(view, ++count);
}
}
}
A "change" is an insert, update or delete. Here is the listing of the handler for delete operations (configured as an event listener on the Hibernate 3 LocalSessionFactoryBean):
public class DeleteHandler extends DefaultDeleteEventListener {
private ModifiedObjectTracker tracker;
public void onDelete(DeleteEvent event) throws HibernateException {
getModifiedObjectTracker().notifyModified(event.getEntityName());
}
public ModifiedObjectTracker getModifiedObjectTracker() {
return tracker;
}
public void setModifiedObjectTracker(ModifiedObjectTracker tracker) {
this.tracker = tracker;
}
}
The ModifiedObjectTracker is injected into the DeleteHandler via Spring Configuration. There is also a SaveOrUpdateHandler that deals with new and updated POJOs.
If the client sends back a currently valid Etag (meaning our content hasn't changed since the last request), we will want to prevent further processing in order to realize our performance gain. In Spring MVC, we can use a HandlerInterceptorAdaptor and override the preHandle method:
public final boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws
ServletException, IOException {
String method = request.getMethod();
if (!"GET".equals(method))
return true;
String previousToken = request.getHeader("If-None-Match");
String token = getTokenFactory().getToken(request);
// compare previous token with current one
if ((token != null) && (previousToken != null && previousToken.equals('"' + token + '"'))) {
response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
// re-use original last modified timestamp
response.setHeader("Last-Modified", request.getHeader("If-Modified-Since"))
return false; // no further processing required
}
// set header for the next time the client calls
if (token != null) {
response.setHeader("ETag", '"' + token + '"');
// first time through - set last modified time to now
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MILLISECOND, 0);
Date lastModified = cal.getTime();
response.setDateHeader("Last-Modified", lastModified.getTime());
}
return true;
}
We first make sure we are dealing with a GET request (ETag in conjunction with PUT can be used to detect conflicting updates, but that is beyond the scope of this article.) . If the token matches the last one we sent back, we return a 304 Not Modified and bypass the rest of the request processing chain. Otherwise, we set the ETag response header in preparation for the next client request.
You will notice I have abstracted the logic for generating the token to an interface so that different implementations can be plugged in. The interface has one method:
public interface ETagTokenFactory {
String getToken(HttpServletRequest request);
}
To minimize code listings, my simple implementation of SampleTokenFactory also plays the role of ETagTokenFactory. In this case, we generate the token by simply returning the modified count for the request URI:
public String getToken(HttpServletRequest request) {
String view = request.getRequestURI();
Integer count = counts.get(view);
if (count == null) {
return null;
}
return count.toString();
}
That is it!
The Conversation
At this point, our interceptor will prevent any cycles being spent on gathering data or rendering a view if nothing has changed. Now, let's take a look at the HTTP headers (courtesy of LiveHTTPHeaders) and see what is happening under the covers. The download includes instructions for configuring the interceptor so that owner.htm is "ETag enabled".
The first request we make shows that this user has already looked at this page:
----------------------------------------------------------348062
If-Modified-Since: Wed, 20 Jun 2007 18:29:03 GMT
If-None-Match: "-1"
HTTP/1.x 304 Not Modified
Server: Apache-Coyote/1.1
Date: Wed, 20 Jun 2007 18:32:30 GMT
We should now make a change and see if the ETag changes. We add a pet to this owner:
----------------------------------------------------------
GET 356265
HTTP/1.x 200 OK
Server: Apache-Coyote/1.1
Pragma: No-cache
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Cache-Control: no-cache, no-store
Content-Type: text/html;charset=ISO-8859-1
Content-Language: en-US
Content-Length: 2174
Date: Wed, 20 Jun 2007 18:32:57 GMT
----------------------------------------------------------
POST 402968
Content-Type: application/x-www-form-urlencoded
Content-Length: 40
name=Noddy&birthDate=1000-11-11&typeId=5
HTTP/1.x 302 Moved Temporarily
Server: Apache-Coyote/1.1
Pragma: No-cache
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Cache-Control: no-cache, no-store
Location:
Content-Language: en-US
Content-Length: 0
Date: Wed, 20 Jun 2007 18:33:23 GMT
Because we did not configure any ETag awareness to addPet.htm, no headers are set. Now, we ask for owner 10 again. Notice the ETag is now 1:
----------------------------------------------------------403109
If-Modified-Since: Wed, 20 Jun 2007 18:29:03 GMT
If-None-Match: "-1"
HTTP/1.x 200 OK
Server: Apache-Coyote/1.1
Etag: "1"
Last-Modified: Wed, 20 Jun 2007 18:33:36 GMT
Content-Type: text/html;charset=ISO-8859-1
Content-Language: en-US
Content-Length: 4317
Date: Wed, 20 Jun 2007 18:33:45 GMT
Finally, we ask for owner 10 again. This time our ETag kicks in and we get a 304 Not Modified:
----------------------------------------------------------493500
If-Modified-Since: Wed, 20 Jun 2007 18:33:36 GMT
If-None-Match: "1"
HTTP/1.x 304 Not Modified
Server: Apache-Coyote/1.1
Date: Wed, 20 Jun 2007 18:34:55 GMT
We have saved bandwidth and computation cycles by taking advantage of HTTP caching!
The Fine Print: In practice, we can achieve greater efficiencies by tracking object changes at a more granular level, using the object id for example. However, the idea of correlating modified objects to views is highly dependent on the overall design of the data model used in the application. This implementation (of ModifiedObjectTracker) is illustrative and is intended to provide ideas for further exploration. It is not intended to be used in a production environments (it would not be suitable to use in a cluster for example). One option for further consideration would tracking modifications using database triggers, and having the interceptor access the table the triggers write to.
Conclusion
We have looked at two approaches to reducing bandwidth and computation using ETags. My hope is that this article has provided you with food for thought for your current and future web based projects, and an appreciation for the under utilized ETag response header.
As Isaac Newton famously said: "If I have seen further, it is by standing on the shoulders of giants." At its core, REST style applications are about simplicity, good software design, and not reinventing the wheel. I believe the growing use and awareness of REST style architectural principals for web based applications is a good move for mainstream application development, and I am looking forward to leveraging it further in my future projects.
About the Author
Gavin Terrill is Chief Technology Officer at BPS Inc. Gavin has been developing software for over 20 years specializing in Enterprise Java applications, yet still refuses to throw out his TRS-80. In his spare time Gavin enjoys sailing, fishing, playing guitar and quaffing quality red wine (not necessarily in that order).
Thanks
I would like to thank my colleagues Patrick Bourke and Erick Dovale for their help in providing feedback for this article.
The code and the instructions can be downloaded HERE.
cool, this should be put into a framework
by
Floyd Marinescu
Why not use version fields?
by
Jason Carreira
I'm not clear, though, on what benefit this gives over just using the If-Modified-Since field?
Questionable Design
by
Subbu Allamaraju
Re: Why not use version fields?
by
Gavin Terrill
Thanks for your comments. I'll check the synchronized performance issue.
Re using a version column: Yes, that would be a fine approach. I chose to use a count per view in the example because I have found that the view often uses multiple domain objects (meaning you need to take into account multiple version numbers). I suspect that in a full blown implementation this would be a good place to apply the Strategy pattern so that the the most appropriate mechanism is used depending on the data in the model.
Re If-Modified-Since: My concern here would be around problems in a clustered environment - you would need to ensure the time is synchronized accurately.
Re: cool, this should be put into a framework
by
Jerome Louvel
Restlet already has an advanced support for E-Tags. You just need to expose the tag of your representations/variants and the Restlet engine will take care of setting the status with conditional requests.
See the Variant and Tag classes:......
Restlet home:
Re: Why not use version fields?
by
Jason Carreira
Re: cool, this should be put into a framework
by
Kishore Senji
Why cannot we have the same approach as the ETagInterceptor done in ETagFilter though as a Filter is nothing but an Interceptor. The Filter should be a OncePerRequestFilter though as you would not want the filter to be processed for all includes (in Servlet spec 2.3 as there are no <dispatcher> rules, containers apply filters differently). And if we use OncePerRequestFilter, the shouldNotFilter is exactly similar to your preHandle method and so, we can do the second approach with the Filter as well without even computing a MD5 hash on the content.
Please note that /*.htm is not a valid url-pattern. (Some containers might accept this, WebSphere I know does not accept that pattern). Either /* (a path mapped) or *.htm (extension mapped) is supported and not both.
This approach is not only good for serving html content but often used for images, js, css and rss content.
There is a bug in Internet Explorer which does not send ETag headers (atleast 6.0) for gzipped content. So, using If-Modified-Since may be a better approach for serving gzipped html/js/css/rss etc. However you raised a concern about synchronizing it across clusters. But I would think it would be the same issue with a ETag number as well - probably using a distributed cache like ehcache.
Re: cool, this should be put into a framework
by
Kishore Senji
Re: Questionable Design
by
Gavin Terrill
If you look at this (the interceptor approach) from the perspective of a single request there is definitely overhead, and you are right - if it takes longer to validate the ETag than regenerating the content it would be simpler to not bother with ETags in the first place. You also need to consider the nature of the application. I think the sweet spot for this approach is applications where the typical user usage is 80/20 reading versus writing, with users returning to the same pages. Rather than speculate though, the key is to measure before and after you implement. I'm planning on posting some numbers over the weekend that show the impact of adding these filters and interceptors to petclinic.
Thanks for commenting!
Re: cool, this should be put into a framework
by
Gavin Terrill
I considered using a filter, but didn't understand what the benefits would be over an interceptor. OTOH, I can inject beans into the interceptor.
Thanks for the tip on the url-pattern.
Gavin.
Re: cool, this should be put into a framework
by
hank jmatt
If-Modified-Since and If-None-Match are overlapping
by
Carl-Erik Kops | http://www.infoq.com/articles/etags/ | CC-MAIN-2014-41 | en | refinedweb |
OpenGL Discussion and Help Forums
>
DEVELOPERS
>
OpenGL coding: beginners
> VC++ newbie Q
PDA
View Full Version :
VC++ newbie Q
02-07-2000, 08:42 AM
I'm just getting started in OpenGl, and I want to write in VC++ can anyone tell me what enviroment variables I need to set or do I only need to put the proper include statements in my programs?
Gorg
02-07-2000, 09:06 AM
You need to link your project with those libraries :
opengl32.lib, glu32.lib, glaux.dll.
for the include statement :
windows.h, gl.h, glu.h, glaux.h
MikeC
02-07-2000, 09:38 AM
Um... Gorg's info is fine, but glaux is generally considered obsolete these days. Most people use GLUT instead, which has the added benefit of being cross-platform. It also comes with LOTS of examples.
To get started with OpenGL/GLUT in MSVC:
1. Create a project for a console app.
2. Link with glut32.lib, glu32.lib, opengl32.lib
3. Include "glut.h" - this includes gl.h and glu.h, and should be enough to get you started. You DON'T need "windows.h"
You should be able to find links to GLUT on the main OpenGL site; if you have problems just drop me a line.
gvili r
02-08-2000, 02:40 AM
The most important thing : The windows.h include must come before all *gl include
MikeC
02-08-2000, 04:04 AM
The most important thing : The windows.h include must come before all *gl include
No, not with GLUT. GLUT (at least the current version, 3.7) defines all Windows-specific macros used by gl.h/glu.h
There are only 2 or 3 of these macros, so including the whole of windows.h is massive overkill, and the other 58 billion symbols it defines will just clutter up your namespace.
Powered by vBulletin® Version 4.2.2 Copyright © 2014 vBulletin Solutions, Inc. All rights reserved. | http://www.opengl.org/discussion_boards/archive/index.php/t-141588.html | CC-MAIN-2014-41 | en | refinedweb |
in reply to
Repeating Code - there has GOT to be a better way!
Is the code in the pm files fixed? Or generated by some other script? Or handwritten? If it is fixed I don't see anything better than to use symbolic references (or use eval which is not that different from using a symbolic ref in this case). But you could at least confine it to a small part of your code and put warning signs around it (this is totally untested code and sure to contain bugs) :
my $Cmdref;
#----------
# Using symbolic references to get code files into name space
no strict refs;
eval "our %${name}Cmd; do 'db/${name}Cmd.pm'; $Cmdref= \%${name}Cmd;";
use strict refs;
#-----------
...
foreach $cmd (keys %$Cmdref) {
...
$opcode = sprintf("0%x",$Cmdref->{$cmd}{fixed_pattern});
[download]
But if the data in those files could look different you have a lot more options. You could change it to look like a real module and use the core-module Exporter to get the hashes into your namespace. Or simply have some code that adds a reference to each hash into a global array:
my %ThingyCmd= ...
push @main::allCmd,\%ThingyCmd;
[download]
Or you could create files that conform to Storable, JSON or to the Data::Dumper file format and use the corresponding CPAN modules to read them in. I believe Data::Dumper calls that "thaw"
Perl Cookbook
How to Cook Everything
The Anarchist Cookbook
Creative Accounting Exposed
To Serve Man
Cooking for Geeks
Star Trek Cooking Manual
Manifold Destiny
Other
Results (146 votes),
past polls | http://www.perlmonks.org/?node_id=832100 | CC-MAIN-2014-41 | en | refinedweb |
Combining LESS with ASP.NET
Everyone knows how cool LESS is. If you’re not, then here’s the elevator speech. LESS extends CSS with dynamic behavious such as variables, mixins, namespaces and functions, it makes CSS easy to work with. Now, it’s important to remember it doesn’t code your CSS for you – it isn’t a magic CSS editor. You still need to know how to work with CSS. It allows you to write CSS once and use it in multiple places. This is something I’ve wanted for a long time and now it’s here.
There are other libraries which perform similar functions, such as SASS, but I’ll focus on LESS as that’s what I’m familiar with. I’m going to be concentrating on how to use this with ASP.NET.
I’m going to be using Visual Studio 2010 for this demonstration, as I had a few issues using LESS with Visual Studio 11.
Running LESS On the Client
LESS can be run purely on the client or from the server. To run it on the client is a simple three step process.
- Add a reference to the LESS JavaScript file
- Update the rel value in the LINK tag to rel=”stylesheet/less”
- Add a new .less file to your project and reference that in your LINK tag
Updating the rel value to stylesheet/less is necessary because the LESS library looks for this value. Once it’s found it processes that file. Your page should look like this now.
<link href="styles/my.less" rel="stylesheet/less" /> <script src=""></script>
I’m referencing a file called my.less, so let’s define some LESS code to ensure this is working.
@back-color: #000; @font-color: #fff; body { background-color: @back-color; font-size: .85em; font-family: "Trebuchet MS", Verdana, Helvetica, Sans-Serif; margin: 0; padding: 0; color: @font-color; }
I’ll skip over the syntax for now, but if you run the website and look in the developer tools, you’ll see that LESS code is being served as valid CSS.
Running LESS On the Server
There are several ways to install LESS on the server. The easiest approach is via NuGet. There’s a package called dotless. Install it with the following command inside Visual Studio.
Once installed, you can remove the JavaScript reference from your page. Also make sure you update the LINK tag and remove the /less from the rel attribute.
<link href="styles/my.less" rel="stylesheet" />
The package has also added some entries to your web.config file. There’s a new configSection defined.
<configSections> <section name="dotless" type="dotless.Core.configuration.DotlessConfigurationSectionHandler, dotless.Core" /> </configSections/> <dotless minifyCss="false" cache="true" web="false" />
And a new HTTP handler has been added to cater for .less requests.
<system.webServer> <handlers> <add name="dotless" path="*.less" verb="GET" type="dotless.Core.LessCssHttpHandler,dotless.Core" resourceType="File" preCondition="" /> </handlers> </system.webServer>
The nice feature about dotless is that it can automatically minify the CSS for you via the minifyCss attribute. If you update that to true and run the website now, you’ll see the minified CSS.
That’s it. LESS is now running on the server.
When To Use It?
I think LESS is great for development, but when you need your site to run as fast as possible, you don’t want to transform each .less request on the fly. This is why I’d recommend using this only during development. The good news is when you install dotless, it installs the dotless compiler. This can be in the packagesdotless1.3.0.0Tool folder in your website folder.
You can add this to your pre-build event from the build properties tab.
“$(SolutionDir)packagesdotless.1.3.0.0tooldotless.Compiler.exe” “$(ProjectDir)contentmy.less” “$(ProjectDir)contentmy.css”
This way you get the best of both worlds.
Before moving away from Visual Studio, there are extensions you can install that gives you the familiar syntax highlighting. LessExtension seems like one of the better ones.
LESS Syntax
I haven’t covered any of the syntax in this article. I wanted to focus on LESS with ASP.NET. Ivaylo Gerchev has a good article on the syntax and that can be found here.
I think LESS is a must tool to have during development. It will make your life easier when coding CSS.
- Ediz
- USPaperchaser
- Wyatt Barnett
- Nick G
- Brian | http://www.sitepoint.com/combining-less-with-asp-net/ | CC-MAIN-2014-41 | en | refinedweb |
One of the things I do not believe one should do is passing WPF/Silverlight enumerations (i.e., Visibility) directly from the ViewModel to
the View. All bindings to a ViewModel that are two values should be defined as a Boolean in the ViewModel even if the View requires some other value to reduce
coupling. One of the reasons is that at times properties in the ViewModel are used in ways that were not originally intended, and using Boolean initially
the ViewModel can save making changes in the ViewModel or the creation of a value converter to convert from two values to another two values. The preferred
way should always be to use a value converter to convert the value (Boolean, or something else) to WPF. Creating a generic value converter to convert a
Boolean from the ViewModel to the enumeration (or some other value) needed by the View is actually quite easy. This can then be a value converter and can then be
customized in XAML in the View or can be defined in a resource dictionary. Such a converter can also provide additional features to aid the programmer in finding bugs.
Amazingly, I was on a Silverlight project for Microsoft where Visibility was being set in the ViewModel and I actually had to convert this
Visibility to a Boolean for some other purpose using a value converter (I believe it was a Boolean). Due to administrative constraints in changes I could
make, I could not make the changes to the ViewModel (I understand that they were probably going to fix this problem, but I left the project before the fix was implemented).
I probably started directly passing WPF enumerations from the ViewModel to the View, but I was pretty quick in creating custom value
converters to do the work. It seemed wrong to have WPF enumerations in the ViewModel, and there was the IValueConverter
interface that provides the customization needed. In creating this code, I was simultaneously cursing Microsoft for not providing a simple logic within XAML
to allow for simple conversions or simple equations.
IValueConverter
I did not like creating a custom converter for each conversion of a Boolean to some value needed in the View, and wrote a simple
value converter that could be customized for the values associated with true and false in the View’s XAML:
public class IfTrueValueConverter : IValueConverter
{
public object TrueValue { get; set; }
public object FalseValue { get; set; }
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if (TrueValue == null)
{
TrueValue = true;
FalseValue = false;
}
return (bool)value ? TrueValue : FalseValue;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if (TrueValue == null)
{
TrueValue = true;
FalseValue = false;
}
return (value.ToString() == TrueValue.ToString());
}
}
The XAML to use this converter is very similar to using a simple converter except that true and false values are defined as part of the defining of the converter in the resources:
<Window x:Class="GenericValueConverter.MainWindow"
xmlns=""
xmlns:x=""
xmlns:
<Window.Resources>
<local:IfTrueValueConverter x:
</Window.Resources>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBox Name="TestControl" Text="Test Message" Margin="5"
Visibility="{Binding IsVisible,
Converter={StaticResource VisibilityConverter}}"/>
</StackPanel>
</Window>
As can be seen, first we need to define the value converter in the Window.Resources element of the XAML. This is just defining any value converter for use except there
are two additional arguments: TrueValue and FalseValue. All that is needed is to put in the string value for the enumeration desired for when the ViewModel’s value
is true and false. The conversion capability of WPF is such that it can convert these string values into the enumeration, so the converter works. The converter
can also be used to set colors, so string values of “Red” and “Black” can be assigned to TrueValue and FalseValue, and then the converter can be used
to set the Foreground Brush.
Window.Resources
TrueValue
FalseValue
Using the converter is now just like using any converter as can be seen in the XAML for the
TextBox.
TextBox
I have used this value converter extensively in my coding, and have considered writing an article on the idea for quite a while, but I
knew I could do better. First of all, I could convert the string to the actual type so that string conversion would not be required except the first time, which
should increase performance at a small cost during initialization. Second, I could do some error checking. The main purpose of the error checking would be
to help the programmer find errors; there have been quite a few times I have spent too much time finding a problem in binding that was actually very simple,
just that WPF/Silverlight does a very poor job of helping the developer with binding problems. The two objectives actually go hand in hand since converting
a string to the required value and giving the developer feedback both require the conversion of the string to the type expected by WPF.
The important aspect of creating an implementation is converting between a string and the value, and vice versa.
I have often worked with enumerations in WPF, so was quite familiar converting strings to the enumerations and enumerations to string
values. Also, I have used the above value converter mostly for enumerations, particularly Visibility, so was only initially thinking about doing the
checking and conversion only for enumerations. When I started to implement my improved value converter, I did the enumeration part, and then thought that
it should also be able to convert strings to other object types since WPF and Silverlight do this conversion. Figuring out how to do it was a bit trickier.
I initially attempted to use the System.Convert.ChangeType method, which did not work (did not surprise me). Research found the TypeConverter
class. This class can be associated with the associated class it translates for by using an attribute:
System.Convert.ChangeType
TypeConverter
[TypeConverter(typeof(MyClassTypeConverter))]
public class MyClass
{
//Class implementation here
}
public class MyClassTypeConverter : TypeConverter
{
public override object ConvertTo(ITypeDescriptorContext context,
System.Globalization.CultureInfo culture,
object value,
Type destinationType)
{
//Conversion code here, returning object;
}
}
Microsoft has type converters for many of the standard classes. All that is required is to use the static TypeDescriptor.GetConverter method,
and then the ConvertFrom method of the returned class:
TypeDescriptor.GetConverter
ConvertFrom
TypeConverter converter = TypeDescriptor.GetConverter(targetType);
return converter.ConvertFrom(value);
I originally had a different code for conversion of the enumeration since I could use the Enum.Parse method, but the TypeConverter works
for both, and using only the TypeConverter eliminated code.
Enum.Parse
The code for the converter is as follows:
public class IfTrueValueConverter : IValueConverter
{
public object TrueValue { get; set; }
public object FalseValue { get; set; }
private bool _checkValues;
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if (!_checkValues)
Initialize(targetType);
return (bool)value ? TrueValue : FalseValue;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if (!_checkValues)
Initialize(value.GetType());
return (value.ToString() == TrueValue.ToString());
}
private void Initialize(Type targetType)
{
_checkValues = true;
if (TrueValue == null)
{
TrueValue = true;
FalseValue = false;
}
else
{
TrueValue = FixValue(targetType, TrueValue);
FalseValue = FixValue(targetType, FalseValue);
}
}
private static object FixValue(Type targetType, object value)
{
if (value.GetType() == targetType)
return value;
try
{
TypeConverter converter = TypeDescriptor.GetConverter(targetType);
return converter.ConvertFrom(value);
}
catch
{
DisplayIssue(targetType, value);
return value;
}
}
[ConditionalAttribute("DEBUG")]
private static void DisplayIssue(Type targetType, object invalidValue)
{
if (targetType.IsEnum)
{
var enumNames = string.Join(", ", Enum.GetNames(targetType));
MessageBox.Show(string.Format(
"Enumeration value '{0}' not recognized for enumeration type '{1}'. " +
“Valid values are {2}.",
invalidValue, targetType, enumNames));
}
else
MessageBox.Show(string.Format(
"The value '{0}' not recognized for target type '{1}'.",
invalidValue, targetType));
}
}
The public methods are almost identical to the code above, except the creation of a private Initialize method to remove the checking out of the public methods.
The _checkValues variable allows the initializing code to be skipped once initialization has occurred. The Initialize method checks if the TrueValue
has been assigned (just like in the simpler implementation above), and makes it a Boolean if it has not. Next, the private static FixValue function
is called for each of the TrueValue and FalseValue variables. The FixValue method first checks to make sure that conversion is required: if conversion
is not required, just return the same value (if an attempt is made to convert twice, an exception will probably be raised). Otherwise, the code obtains the
TypeConverter for the targetType, and does the conversion. If there is an exception (it is not possible to convert to a value of the right
type), the code catches the exception and the original value is returned (probably this will not work, but WPF will let the code work). I have programmed
the converter so that if the environment is in debug mode, then a message box will inform the developer of the reason for the exception. This is true because the
method containing the MessageBox.Show method is decorated with “ConditionalAttribute("DEBUG")”. In this conditional method,
the target type is checked for being an enumeration so that the message box content for an enumeration can include additional information about the acceptable enumeration values.
Initialize
_checkValues
FixValue
targetType
MessageBox.Show
ConditionalAttribute("DEBUG")
The example included shows this converter being used for a number of different properties on a TextBox. These properties are changed by
checking CheckBoxes. One of the checkboxes controls the visibility, and this one needs to be checked to be able to see any of the other changes. Among the
properties that are bound are double (FontSize), Brush (BorderBrush), Visibility, reversed Boolean (IsReadOnly), and
Thickness (BorderThickness). This should be a pretty good variety of properties and types to show the flexibility of the value converter.
CheckBox
FontSize
BorderBrush
IsReadOnly
Thickness
BorderThickness
The XAML for this is as follows:
<Window x:Class="GenericValueConverter.MainWindow"
xmlns=""
xmlns:x=""
xmlns:
<Window.Resources>
<local:IfTrueValueConverter x:
<local:IfTrueValueConverter x:
<local:IfTrueValueConverter x:
<local:IfTrueValueConverter x:
<local:IfTrueValueConverter x:
</Window.Resources>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<CheckBox Content="checked for visible, unchecked for invisible"
IsChecked="{Binding IsVisible,FallbackValue=true}"/>
<CheckBox Content="checked for Red border color, unchecked for Blue border color"
IsChecked="{Binding BorderColor,FallbackValue=true}"/>
<CheckBox Content="checked to enable editing (IsReadOnly = false)"
IsChecked="{Binding CanEdit,FallbackValue=true}"/>
<CheckBox Content="checked for thick border thickness, unchecked for thinner"
IsChecked="{Binding ThinBorderThickness,FallbackValue=true}"/>
<CheckBox Content="checked for font size 10, unchecked for font size 12.5"
IsChecked="{Binding FontSize,FallbackValue=true}"/>
<TextBlock Text="TestControl:" Margin="0,5,0,0" Foreground="DarkBlue"/>
<TextBox Name="TestControl" Text="Test Message" Margin="5" Height="30"
Visibility="{Binding IsVisible,
Converter={StaticResource VisibilityConverter}}"
BorderBrush="{Binding BorderColor,
Converter={StaticResource BorderColorConverter}}"
BorderThickness="{Binding ThinBorderThickness,
Converter={StaticResource BorderThicknessConverter}}"
FontSize="{Binding FontSize,
Converter={StaticResource FontSizeConverter}}"
IsReadOnly="{Binding CanEdit,Converter={StaticResource
ReverseBoolConverter}}"/>
</StackPanel>
</Window>
As can be seen, using the converter is just like using the simpler one I showed above.
You will have to modify the XAML to show the debugging assistance that this code provides. All that is required is that either TrueValue or
FalseValue be assigned an invalid value when the converter is defined in the XAML. If TrueValue for Visibility is changed
to something like “illegal”, then the following MessageBox would appear:
Visibility
This information should provide a lot of help in fixing binding issues for enumerations. For non-enumerations, the MessageBox is slightly simpler without the
list of valid enumeration values:
One of the nice things is that the dialog is only displayed the first time the converter is run.
There are other ways to provide feedback on translation issues, including writing to the Output window, but I prefer displaying a message to the developer.
One of the ideas I have had is to extend the converter to be three-state where the third state is null. Personally, I have not seen any need for this third value in my code, but I can
see cases where a third value is desirable.
Another idea is to add properties that allow the value to be compared to something other than true and false. This would be pretty
straightforward, and could be very useful if binding to properties of a control defined in the XAML.
An extension of this would be support for more than two or three values. This could be done by defining all the items in a delimited list
in the XAML that is entered as a property in the converter. The converter would then parse the list to get the conversions.
This generic Boolean value converter is flexible enough to handle all Boolean conversions required by a View. It can also be used in
certain circumstances to do other binding where the value being bound to is a Boolean.. | http://www.codeproject.com/Articles/289495/Generic-WPF-Silverlight-Value-Converter?fid=1667588&df=90&mpp=10&sort=Position&spc=None&tid=4118533 | CC-MAIN-2014-41 | en | refinedweb |
#include <refinement_selector.h>
RefinementSelector ()
virtual ~RefinementSelector ()
virtual void select_refinement (const System &system)
std::vector< float > component_scale
This abstract class provides an interface to methods for selecting the type of refinement to be used on each element in a given mesh. Currently we assume that a set of elements has already been flagged for h refinement, and the only concrete subclass will change some of those elements to be flagged for p refinement. Future subclasses may handle anisotropic refinement instead.
Author:
Definition at line 46 of file refinement_selector.h.
Definition at line 53 of file refinement_selector.h.
{}
Definition at line 58 of file refinement_selector.h.
{}
Definition at line 75 of file refinement_selector.h.
Generated automatically by Doxygen for libMesh from the source code. | http://www.makelinux.net/man/3/R/RefinementSelector | CC-MAIN-2014-41 | en | refinedweb |
VM_PAGE_INSERT(9) MidnightBSD Kernel Developer’s Manual VM_PAGE_INSERT(9)
NAME
vm_page_insert, vm_page_remove — add/remove page from an object
SYNOPSIS
#include <sys/param.h>
#include <vm/vm.h>
#include <vm/vm_page.h>
void
vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex);
void
vm_page_remove(vm_page_t m);
DESCRIPTION
The vm_page_insert() function adds a page to the given object at the given index. The page is added to both the VM page hash table and to the object’s list of pages, but the hardware page tables are not updated. In the case of a user page, it will be faulted in when it is accessed. If the page is a kernel page, the caller is expected to handle adding the page to the kernel’s pmap.
If PG_WRITEABLE is set in the page’s flags, OBJ_WRITEABLE and OBJ_MIGHTBEDIRTY are set in the object’s flags.
The vm_page_remove() function removes the given page from its object, and from the VM page hash table. The page must be busy prior to this call, or the system will panic. The pmap entry for the page is not removed by this function.
The arguments to vm_page_insert() are:
m
The page to add to the object.
object
The object the page should be added to.
pindex
The index into the object the page should be at.
The arguments to vm_page_remove() are:
m
The page to remove.
IMPLEMENTATION NOTES
The index of a page in a VM object is the byte index into the same object truncated to a page boundary. For example, if the page size is 4096 bytes, and the address in the object is 81944, the page index is 20.
AUTHORS
This manual page was written by Chad David 〈davidc@acns.ab.ca〉.
MidnightBSD 0.3 July 17, 2001 MidnightBSD 0.3 | http://www.midnightbsd.org/documentation/man/vm_page_insert.9.html | CC-MAIN-2014-41 | en | refinedweb |
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Alternatives to Using Repositories12:49 with James Churchill
Now that we've gone through the process of adding repositories to our web app, let's talk about the pros and cons of the repository design pattern and look at an alternative approach that utilizes query and command classes.3.8 -b alternatives-to-using-repositories
Are Repositories Necessary?
Over the years, some developers have begun to question the value of using repositories. For more information about this discussion, see the following blog posts.
- Favor Query Objects Over Repositories
- Wither the Repository
- Limiting Your Abstractions
- Repositories On Top UnitOfWork Are Not a Good Idea
Organizing Projects By Feature Instead of Class Type
Instead of organizing projects by class type, it's possible to organize your projects by feature. For more information on what this is and how to do it, see this blog post from Tim G. Thomas.
Feature Folders in ASP.NET MVC
YAGNI - You Aren't Going to Need It
YAGNI, or You Aren't Going to Need It, is the idea that you shouldn't add something to your application until you actually have a need for it. Sounds like a simple idea, but you'd be surprised how often as programmers we feel the urge to add stuff that we don't actually need.
For more information see this article on Wikipedia:
Code
You can download the code for the ComicBookArtistsController_QueriesAndCommands class from this GitHub Gist.
Now that we've gone through the process of adding repositories to our web app, 0:00 let's talk about the pros and cons of the repository design pattern. 0:04 Moving all of our data retrieval and persistence code into a repository. 0:08 Or in our case, a collection of repositories helps to simplify and 0:12 keep our controllers as lean as possible. 0:16 It also helps us to adhere to the dry or don't repeat yourself design principle. 0:19 Instead of duplicating EF queries or commands across controller action methods, 0:24 we can place that code in a repository method and 0:29 call that method from our action methods instead. 0:32 But adding repositories to an application adds an additional layer of abstraction 0:35 between your controller action methods and the database context. 0:39 And in some cases this layer of abstraction can 0:43 feel like you're adding complexity without enough of a clear benefit. 0:46 As an alternative to using repositories, we can use Query and Command classes. 0:51 Query and Command classes encapsulate data persistence code much in 0:56 the same way that repositories do. 1:00 But when you selectively on an as needed basis they can provide the same benefits 1:02 repositories without adding as much complexity. 1:07 Let's look at a couple of examples. 1:11 Before we add our first class let's add two folders to the shared class library 1:14 data folder one named queries and another named commands. 1:19 As the folder name suggests we'll add all of our query classes to the queries folder 1:24 and all of our command classes to the commands folder. 1:29 To make it easier to compare using repositories to using queries and commands 1:32 I added another copy of the comic book artist controller class to our project. 1:37 And reverted the code back to what it was 1:41 before we added our comic book artist repository. 1:44 If you're following along you can find a copy of this code in the teacher's notes. 1:47 Let's start with the Add.getAction() method. 1:51 At the beginning of the method we have a query to retrieve the comic book 1:54 that the user is adding an artist to. 1:58 When using query in command classes you don't automatically 2:00 move every query in command into it's class, 2:04 instead you evaluate it's relative complexity and usage. 2:07 And make a determination if your code and 2:11 overall design will benefit from moving the query or command to it's own class. 2:13 This query isn't overly complex but it's used at least twice. 2:18 Once here in the ad get action method and once in the ad post action method. 2:24 Since it's duplicated and it's what I'd call moderately complex, 2:30 let's move it to a query class. 2:34 Add a class named get comic book query to the queries folder. 2:39 To start, we need a private field for the context. 2:48 And a constructor that accepts a context instance and sets the private field. 2:51 Private Context _context = null. 2:59 Public GetComicBookQuery then a parameter up type Context 3:05 named context and set the private field to that parameter value. 3:13 Then let's add a method name execute that returns a comic book instance. 3:20 And accepts an integer ID value, public. 3:25 ComicBook Execute, int id. 3:31 For the implementation we can switch back to the ControllerAction method. 3:37 And copy the query to the clipboard. 3:44 Add return and then paste the query from the clipboard. 3:50 We've got some things to fix up here. 3:56 Change context to, _context. 3:59 ComicBookId to just id. 4:06 And we need to add using directive for the system data 4:13 entity namespace, using System.Data Entity. 4:18 Now we're ready to update the action method to use our new query class. 4:25 Remove the existing query, instantiate an instance of the GetComicBookQuery class, 4:29 new GetComicBookQuery. 4:35 Add a using directive for the ComicBookSharedDataQueries 4:39 namespace passing the context property from the base controller class. 4:43 And call the execute method, passing in the comicBookId parameter value. 4:47 Then in the add post action method we can replace the query to set the view 4:58 viewModel's ComicBook property with another instance of our query class. 5:02 Now let's review the remaining EF queries in commands that are being used in this 5:13 controller. 5:17 And determine if any of them would be good candidates for 5:17 moving to their own query or command classes. 5:20 Remember we only want to create query or 5:23 command classes to encapsulate complex or duplicated code. 5:26 In the add post action method we've got some code related to add in 5:32 a comic book artist. 5:35 This code isn't repeated anywhere else and its relatively simple. 5:37 So let's go ahead and just leave it as it is. 5:42 In the delete get action method we've got a query to retrieve a comic book artist. 5:46 This query is about the same level of complexity as the query that we 5:50 just moved to a query class. 5:54 But for now it's only used in this one location. 5:56 Again for simplicity's sake let's leave it as it is. 6:00 In the delete post action method we've got 6:05 code related to deleting a comic book artist. 6:07 But again it's relatively simple and it's not repeated anywhere else. 6:10 So let's leave it alone. 6:15 In the validate ComicBookArtists method we've got a query that checks if 6:18 the provided artist and 6:22 role combination has already been added to the comic book or not. 6:23 Again, just like the other queries or commands that we just looked at 6:28 it's only moderately complex, and it only appears in this one location. 6:32 So let's just leave it alone. 6:36 Because it's query or command, it's its own class. 6:39 You might expect that you'd end up with a lot more classes in your project, 6:42 than if you had used repositories. 6:46 But as you just saw the number of classes that you'll end up with 6:48 really depends on the complexity of your apps queries and commands. 6:52 And whether or not they're used for more than one location. 6:55 Even if you end up with more classes in your project than if you had used 6:59 repositories, using query and command classes often make it a little easier 7:03 to find a query or command that you're looking for. 7:07 Since each class contains a single query or command. 7:10 You don't have to determine which repository you're looking for 7:14 then find the specific method within that repository. 7:18 You just find the query command that you're looking for and 7:21 directly open that file. 7:24 Let's go ahead and 7:26 convert the command to add a ComicBooks artist to use the command class. 7:27 So we can look at an example. 7:30 At a class named AddComicBookArtistCommand to the Commands folder. 7:33 As we've see before we need a private field for the context and 7:50 a constructor that accepts a context instance, and sets the private field. 7:53 Private Context_context = null; public 8:00 AddComicBookArtistCommand then a parameter of type context named context. 8:04 And set the private field o the parameter value. 8:15 Then add a method named execute that returns void. 8:20 And accepts three integer values 8:24 comicBookId, artistsId and roleId. 8:28 For the implementation we can grab a copy of the code in the controller action 8:33 method. 8:37 And copy the code to add a comic book artist to the clipboard. 8:47 Paste the code from the clipboard. 8:51 And probably to no one's surprise got some things to fix up again. 8:54 Add a using directive for 8:58 the comic book shared model's name space. Remove the bad references to view model 9:00 and lower case these identifiers ComicBookID, 9:04 ArtistId and roleId. 9:13 Whoops, looks like I have misspelled this parameter. 9:17 ArtistId not artistsId, then replace Context with _context. 9:21 Now we're ready to update the action method to use our new command class. 9:32 Remove the existing code. 9:36 Instantiate an instance of the AddComicBookArtistCommand class. 9:40 Add a using directive for the missing name space; ComicBookShared.Data.Commands. 9:49 Pass in the context property from the base controller class and 9:55 call the execute method. 9:59 Passing in the viewModel.ComicBookId, artistId. 10:03 Enroll Id property values. 10:11 Now we're ready to test our changes. 10:16 To do that we need to comment out the ComicBooks artist controller class. 10:19 And rename the copy of the controller that we've been modifying to the correct name. 10:24 So that ASP.NET MVC's routing engine will find the query and 10:29 command version of the controller. 10:32 Change the name of the class is good enough. 10:36 We can leave the file name alone. 10:39 Let's separate points in the two methods that we updated to use query and 10:41 command classes just to make sure that our testing exercises, those code pass. 10:46 And run the WebApp. 11:02 View the details for Bone #3, and add a new artist. 11:06 And we've hit our first break point. 11:14 Press F5 to continue execution. 11:17 Select Jeff Smith for the artist. 11:24 Pencils. 11:29 Oop, that artist is already in use. 11:30 So choose Archie Goodwin Pencils and save. 11:33 And we're at our second breakpoint. 11:38 Looks like we're good to go. 11:40 Determining how best to organize your data access code can be a challenging exercise. 11:42 That being said there's no need to agonize too much about it. 11:47 Consider the requirements of your app, weigh the pros and cons of each approach. 11:51 And choose the one you and your team thinks will be the best fit. 11:55 Just remember to not overbuild your solution, 11:59 only build the features that you actually need. 12:02 You could always refactor later on. 12:05 Let's do a quick review of the section. 12:08 We created a base controller class in order to eliminate code duplication in our 12:10 controllers. 12:14 We also reviewed the repository design pattern. 12:16 And implemented a new repository for our web app. 12:18 And we saw how to break apart that repository 12:22 into entity type focused repositories and 12:25 created a generic base repository class to further reduce code duplication. 12:28 Then we finished up with a look at how query and 12:34 command classes could be used as an alternative to repositories. 12:36 Next up, we'll finish the Comic Book Library Manager Web App by updating 12:41 the series and artists sections to use EF. 12:45 See you after the break. 12:47 | https://teamtreehouse.com/library/alternatives-to-using-repositories | CC-MAIN-2020-45 | en | refinedweb |
ConcertoConcerto
Concerto is a lightweight 100% JavaScript schema language and runtime. It works in both a Node.js process and in your browser. The browserified version of Concerto is ±280KB. We are working on making it even smaller..
- Optionall:
InstallationInstallation
npm install @accordproject/concerto --save
Create a Concerto FileCreate a Concerto File
namespace org.acme.address /** * This is a concept */ concept PostalAddress { o String streetAddress optional o String postalCode optional o String postOfficeBoxNumber optional o String addressRegion optional o String addressLocality optional o String addressCountry optional }
Create a Model ManagerCreate a Model Manager
const ModelManager = require('@accordproject/concerto').ModelManager; const modelManager = new ModelManager(); modelManager.addModelFile( concertoFileText, 'filename.cto');
Create an InstanceCreate an Instance
const Factory = require('@accordproject/concerto').Factory; const factory = new Factory(modelManager); const postalAddress = factory.newConcept('org.acme.address', 'PostalAddress'); postalAddress.streetAddress = '1 Maine Street';
Serialize an Instance to JSONSerialize an Instance to JSON
const Serializer = require('@accordproject/concerto').Serializer; const serializer = new Serializer(factory, modelManager); const plainJsObject = serializer.toJSON(postalAddress); // instance will be validated console.log(JSON.stringify(plainJsObject, null, 4);
Deserialize an Instance from JSONDeserialize an Instance from JSON
const postalAddress = serializer.fromJSON(plainJsObject); // JSON will be validated console.log(postalAddress.streetAddress);
MetamodelMetamodel
The Concerto metamodel contains:
- Namespaces
- Imports
- Concepts
- Assets
- Participants
- Transactions
- Enumerations & Enumeration Values
- Properties & Meta Properties
- Relationships
- Decorators
NamespacesNamespaces
namespace foo
Every Concerto file starts with the name of a single namespace. All the definitions within a single file therefore belong to the same namespace. The
ModelManager will refuse to load two model files that have the same namespace.
ImportsImports
To reference types defined in one namespace in another namespace the types must be imported.
Imports can either be qualified, or can use wildcards.
import org.accordproject.address.PostalAddress
import org.accordproject.address.*
Imports can also use the optional
from declaration to import a model files that has been deployed to a URL.
import org.accordproject.address.PostalAddress from
Imports that use a
from declaration can be downloaded into the model manager by calling
modelManager.updateExternalModels.
The Model Manager will resolve all imports to ensure that the set of declarations that have been loaded are globally consistent.
ConceptsConcepts
Concepts are similar to class declarations in most object-oriented languages, in that they may have a super-type and a set of typed properties:
abstract concept Animal { o DateTime dob } concept Dog extends Animal { o String breed }
A concept can be declared
abstract is it should not be instantiated (must be subclassed).
AssetsAssets
An asset is a class declaration that has a single
String property that acts as an identifier.
An participant is a class declaration that has a single
String property that acts as an identifier. Use the
modelManager.getParticipantDeclarations API to look up all participants.
participant Customer identified by email { o String email }
Participants are typically used in your models for the identifiable people or organizations in the model: person, customer, company, business, auditor etc.
TransactionsTransactions
An transaction is a class declaration that has a single
String property that acts as an identifier. Use the
modelManager.getTransactionDeclarations API to look up all transactions.
transaction Order identified by orderId { o String orderId }
Transactions are typically used in your models for the identifiable business events or messages that are submitted by Participants to change the state of Assets: cart check out, change of address, identity verification, place order etc.
Enumerations & Enumeration ValuesEnumerations & Enumeration Values
Use enumerations to capture lists of domain values.
enum Gender { o MALE o FEMALE o OTHER o UNKNOWN }
Properties and Meta PropertiesProperties and Meta Properties
Class declarations contain properties. Each property has a type which can either be a type defined in the same namespace, an imported type or a primitive type.
Primitive typesPrimitive types
Concerto supports.
Meta PropertiesMeta Properties
- [] : declares that the property is an array
- optional : declares that the property is not required for the instance to be valid
- default : declares a default value for the property, if not value is specified
- range : declares a valid range for numeric properties
- regex : declares a validation regex for string properties
String fields may include an optional regular expression, which is used to validate the contents of the field. Careful use of field validators allows Concerto to perform rich data validation, leading to fewer errors and less boilerplate application }
RelationshipsRelationships
A property of a class may be declared as a relationship using the
--> syntax instead of the
o syntax. The
o syntax declares that the class contains (has-a) property of that type, whereas the
--> syntax declares a typed pointer to an external identifiable instance.
This model declares that an
Order has-an array of
OrderLine concepts. When the
Order is deleted all the
OrderLines will also be deleted.
concept OrderLine { o String sku } asset Order identified by orderId { o String orderId o OrderLine[] orderlines }
Whereas }
A relationship the Model Manager.
Decorators];. | https://www.npmjs.com/package/@accordproject/concerto/v/0.80.4-20190927165630 | CC-MAIN-2020-45 | en | refinedweb |
Important: Please read the Qt Code of Conduct -
ListView - OverBounds is freezing at bottom when content is full
Hello,
I'm using Qt v5.7.0
I have an issue with ListView, when its height content is bigger than its own height, the move is freezing when you scroll over the bottom of the list.
There is an example :
import QtQuick 2.7 import QtQuick.Controls 2.0 /// [...] ListView { id: myList width: parent.width height: parent.height boundsBehavior: Flickable.DragOverBounds flickableDirection: Flickable.VerticalFlick ScrollBar.vertical: ScrollBar {} verticalLayoutDirection: ListView.BottomToTop spacing: 20 cacheBuffer: 0 model: 20 delegate: ItemDelegate { width: myList.width height: 30 Rectangle { width: parent.width height: parent.height color: "red" } } }
Is it a bug ? Or something may depend on hightlight item ?
Thanks | https://forum.qt.io/topic/70927/listview-overbounds-is-freezing-at-bottom-when-content-is-full | CC-MAIN-2020-45 | en | refinedweb |
Software Development Kit (SDK) and API Discussions
Hi all,
I'm trying to pull snapmirror lag info from 400 individual volumes in our cluster, which is running release 8.2.1. I can successfully get the data, but it's taking about 10 seconds per call for the API to return data from each volume. This is way too slow.
Here's an example of how I'm doing it with python:
filer = NaServer(filer_name, 1, 6)
filer.set_admin_user('admin', password)
cmd = NaElement("snapmirror-get-iter")
options = NaElement("desired-attributes")
max_records = 400
# add options
cmd.child_add(options)
cmd.child_add_string("max-records", max_records)
ret = filer.invoke_elem(cmd)
# slap all returned attributes gathered by the iterator into a dict
snaplist = dict()
snaplist = ret.child_get('attributes-list')
# grab 'lag-time' from specified volume
def lag(item):
for mirror in snaplist.children_get():
if mirror.child_get_string('destination-volume') == item:
lag = mirror.child_get_string('lag-time')
print lag
This function iterates over a list of 400 volumes.
The cluster is performing well, without errors. There is no general slowness. The speed of getting data out of the API is consistent, whether the query is coming from inside the same datacenter or remotely.
Is the API supposed to be this slow? Is there a faster way to do this?
Thanks,
Jason
Jason,
That 10 seconds sounds a little high from previous experience, but might not be out of the realm of possibility depending on how much data is being pulled back.
In the python snippit you pasted below - is this the function that is being repeated once for each of the 400 volumes? Or are you pulling the results of 'snapmirror-get-iter' one time and then iterating through the resulting returned data? | https://community.netapp.com/t5/Software-Development-Kit-SDK-and-API-Discussions/Slow-ONTAP-API-response/td-p/106828 | CC-MAIN-2020-45 | en | refinedweb |
scanf, fscanf, sscanf, scanf_s, fscanf_s, sscanf_s
From cppreference.com
Reads data from the a variety of sources, interprets it according to
format and stores the results into given locations.,
scanf_s,
fscanf_s, and
s (which may be zero in case a matching failure occurred before the first receiving argument was assigned), or EOF if input failure occurs before the first receiving argument was assigned.
[edit] Notes
Because most conversion specifiers first consume all consecutive whitespace, code such as
scanf("%d", &a);:
scanf("%d", &a); scanf(" %c", &c); // consume all consecutive whitespace after %d, then read a char
[edit] Example
Run this code
#define __STDC_WANT_LIB_EXT1__ 1 #include <stdio.h> #include <stddef.h> #include <locale.h> int main(void) { int i, j; float x, y; char str1[10], str2[4]; wchar_t warr[2]; setlocale(LC_ALL, "en_US.utf8"); char input[] = decimal digits (digits 5 and 6) %2lc: two wide characters, using multibyte to wide conversion */ int ret = sscanf(input, "%d%f%9s%2d%f%*d %3[0-9]%2lc", &i, &x, str1, &j, &y, str2, warr); printf("Converted %d fields:\ni = %d\nx = %f\nstr1 = %s\n" "j = %d\ny = %f\nstr2 = %s\n" "warr[0] = U+%x warr[1] = U+%x\n", ret, i, x, str1, j, y, str2, warr[0], warr[1]); #ifdef __STDC_LIB_EXT1__ int n = sscanf_s(input, "%d%f%s", &i, &x, str1, (rsize_t)sizeof str1); // writes 25 to i, 5.432 to x, the 9 bytes "thompson\0" to str1, and 3 to n. #endif }
Output:
Converted 7 fields: i = 25 x = 5.432000 str1 = Thompson j = 56 y = 789.000000 str2 = 56 warr[0] = U+df warr[1] = U+6c34
[edit] References
- C11 standard (ISO/IEC 9899:2011):
- 7.21.6.2 The fscanf function (p: 317-324)
- 7.21.6.4 The scanf function (p: 325)
- 7.21.6.7 The sscanf function (p: 326)
- K.3.5.3.2 The fscanf_s function (p: 592-593)
- K.3.5.3.4 The scanf_s function (p: 594)
- K.3.5.3.7 The sscanf_s function (p: 596) | https://en.cppreference.com/w/c/io/fscanf | CC-MAIN-2020-45 | en | refinedweb |
The following python code snippet creates a segmentation fault (making the ipython kernel crashes).
Code: Select all
from neuron import nrn, h def section_print(): """Print the different sections in the NEURON namespace""" for sec in h.allsec(): print sec.name() class Segfault(nrn.Section): """ Should wrap a NEURON section """ def __init__(self, name="fault"): """Initialize the section """ #Create a section within h h("create {}".format("fault")) #Address this section to the object self = getattr(h, "fault") #Set an attribut self.L = 10 seg = Segfault() section_print() seg.L
The section_print shows that it works well at the beginning (there is a "fault" section created within h), but trying to get the attribut "L" makes the kernel crash. I found solutions (/dirty tricks) to avoid this problem but I do not understand why it is happening. I already came across segmentation faults, e.g. trying to change a cell model on the fly.
So I have three questions:
What is happening here?
How come neuron is capable of producing segmentation faults?
Are there simple rules of thumb to avoid segmentation fault using neuron?
Best,
Romain | https://www.neuron.yale.edu/phpBB/viewtopic.php?p=12380 | CC-MAIN-2020-45 | en | refinedweb |
sgr eval
sgr eval [OPTIONS] COMMAND
Evaluate a Python snippet using the Splitgraph API.
This is for advanced users only and should be only used if you know what you are doing.
Normal Python statements are supported and the command is evaluated in a namespace where the following is already imported and available:
Repository: class that instantiates a Splitgraph repository and makes API functions like .commit(), .checkout() etc available.
engine: Current local engine
object_manager: an instance of ObjectManager that allows to get information about objects and manage the object cache.
Example:
sgr eval 'import json; print(json.dumps(Repository .from_schema(repo_name) .images["latest"] .get_table(table_name) .table_schema))' -a repo_name my_repo -a table_name my_table
Will dump the schema of table my_table in the most recent image in my_repo in JSON format.
For more information, see the Splitgraph API reference.
Options
--i-know-what-im-doing: Pass this if you're sure that the code you're running is safe and don't want to be prompted.
-a, --arg <TEXT TEXT>...: Make extra variables available in the command's namespace | https://www.splitgraph.com/docs/sgr/versions/v0.1.2/miscellaneous/eval | CC-MAIN-2020-45 | en | refinedweb |
In-Depth
Visual Studio 2013 came with a new version of Web API. The Web API 2.1 update includes a host of new features, including support for Binary JSON. Learn how to leverage BSON by building a Web API 2.1 service.
The Web API framework allows developers to quickly create services using MVC-like conventions. It offers the flexibility of creating REST style services, and serving up data in a variety of formats, including the newly supported Binary JSON (BSON) format. This article will focus on building a Web API 2.1 service utilizing the new BSON Media-Type Formatter.
ASP.Net Web API is a relatively new technology from Microsoft, released initially with the Microsoft .NET Framework 4.5. It allows a single Web service to communicate with various clients in various formats such as XML, JSON and OData. (I discussed the introduction of ASP.NET Web API is in a previous article). With Visual Studio 2013, Microsoft released ASP.NET Web API 2 in October 2013, followed by an update to Web API 2.1 in January 2014. Some of the new features in 2.1 include:
BSON is a binary-encoded serialization of JSON-like objects (also known as documents) representing data structures and arrays. BSON objects consist of an ordered list of elements. Each element contains Field Name, Type and Value.
Field names are strings. Types can be any of the following:
The primary advantages of BSON are that it's lightweight with minimal spatial overhead, easy to parse, and efficient for encoding and decoding.
To demonstrate, I'll create a sample ASP.NET Web API 2.1 application in ASP.NET MVC 5, using Visual Studio 2013. This solution will be very similar to the one I discussed in my previous article (following the premise of building an inventory app for a used car lot), which will allow for comparison and contrast of old features to new features. I'll call it CarInventory21, to reflect version 2.1 of the ASP.NET Web API.
First, I create an ASP.NET Web Application, choosing an Empty template with MVC folders and core references, as seen in Figure 1 and Figure 2.
Next, I add a class to the Model folder, calling it Car.cs, shown in Figure 3 and Figure 4.
This class contains the following structure, representing each car in inventory (it's been slightly modified from its counterpart in the previous article):
public class Car
{
public Int32 Id { get; set; }
public Int32 Year { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public string Color { get; set; }
}
Next, I add an Empty Web controller by right-clicking the Controllers folder | Add | Controller, as shown in Figure 5.
Afterward, when prompted for the type of controller to scaffold, I chose an Empty controller (see Figures 6-8) for the sake of keeping the sample project thin and clutter-free.
Like other ASP.NET MVC projects, the controller isn't required to be in the Controllers folder, but it's a good practice and is highly recommended. Unlike typical ASP.NET MVC projects that inherit from the Controller class, the ASP.NET Web API controller inherits the ApiController class.
Following the implementation from the previous article, I won't use a database but instead instantiate the records in code. I will also create two action methods within the controller: one to retrieve all car records, and the other to retrieve only a specific record using the ID field. The complete listing of Controllers\CarController.cs is shown in Listing 1.
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using CarInventory21.Models; //Added manually
namespace CarInventory21.Controllers
{
public class CarController : ApiController
{
Car[] cars = new Car[]
{
new Car { Id = 1, Year = 2012, Make = "Cheverolet", Model = "Corvette", Color = "Red" },
new Car { Id = 2, Year = 2011, Make = "Ford", Model = "Mustang GT", Color = "Silver" },
new Car { Id = 3, Year = 2008, Make = "Mercedes-Benz", Model = "C300", Color = "Black" }
};
public IEnumerable<Car> GetAllCars()
{
return cars;
}
public IHttpActionResult GetCar(int id)
{
var car = cars.FirstOrDefault((c) => c.Id == id);
if (car == null)
{
return NotFound();
}
return Ok(car);
}
}
}
Looking at other portions of the project, a WebApiConfig.cs is created in the App_Start folder of the solution by default. As the name suggests, this file is for globally configuring the ASP.NET Web API. Before configuring the solution for BSON, I first need the references for the BSON library. This is done automatically by installing the NuGet package Microsoft ASP.NET Web API 2.1 Client Library, as seen in Figure 8.
Installing the NuGet package will also require accepting the license agreement (see Figure 9).
Because I want to display only BSON, I will add the following lines at the bottom of the Register method in the App_Start\WebApiConfig.cs file:
config.Formatters.Clear(); // Remove all other formatters
config.Formatters.Add(new BsonMediaTypeFormatter()); // Enable BSON in the Web service
These calls will first clear and remove all other formatters the ASP.NET Web API will use for responding to requests. Then it will add a new instance of the BSON formatter to the empty list, effectively making BSON the only response type available. The complete listing can be seen
}
}
}
So far I've built the model and the controller. The only remaining item is a view. For a view, I'll create a simple HTML page. This will serve as a test page and also allow IIS Express to host the ASP.NET Web API. To add a Web page, I right-click on the project and select Add | HTML Page, calling it Index.html.
By default, the links to access this new ASP.NET Web API are:
Routing is a detailed topic not addressed in this article. However, you can learn more about it here.
To help facilitate testing, I modify the newly-created page to include all links. The full listing can be found in Listing 3.
<!DOCTYPE html>
<html xmlns="">
<head>
<title>Test Page</title>
</head>
<body>
<br />
To retrieve all car: <a href="/api/car"> /api/car </a> <br />
<br />
To retrieve car #1: <a href="/api/car/1"> /api/car/1 </a> <br />
To retrieve car #2: <a href="/api/car/2"> /api/car/2 </a> <br />
To retrieve car #3: <a href="/api/car/3"> /api/car/3 </a> <br />
<br />
</body>
</html>
At this point, the project is ready to run, resulting in the output seen in Figure 11.
Clicking on the first link to retrieve all cars will download all cars to the browser in BSON format. Currently there's no code to display the retrieved records, so the browser will simply prompt to save the records to a file. Opening the file in Visual Studio will yield the records in Binary format, as seen in Figure 12.
Reading through the file, you'll see the various hex characters decorating the ASCII characters. These are characteristics of the BSON format. At this stage the ASP.NET Web API is ready to be consumed by clients.
(I'll discuss the various ways an ASP.NET Web API can be consumed by a client process in upcoming articles.)
Lightweight, Flexible Data
ASP.NET Web API 2.1 is currently the latest release from Microsoft. It offers a variety of new features, including the new BSON format. It can be utilized like other formats, but offers a lightweight representation of binary data in a format similar to JSON, which gives Web API 2.1 more flexibility while still remaining simple and easy to configure. | https://visualstudiomagazine.com/articles/2014/05/01/implementing-binary-json-in-aspnet-web-api-2_1.aspx?admgarea=features | CC-MAIN-2020-45 | en | refinedweb |
Writing custom mount handlers
To mount a custom database into your Splitgraph engine, you have to do three things:
- Install the foreign data wrapper into the engine (either using PGXN or compiling the wrapper by yourself)
- Write a Python function that, when invoked, will create the required mountpoint on the engine and initialize the remote foreign data wrapper. For an example, see
mount_postgresin
splitgraph.hooks.mount_handlers.
- Register the handler in your
.sgconfigfile:
[mount_handlers] handler_name=your.handler.module.handler_function
Registering the handler in such a way will also parse its function signature and docstring, adding the handler automatically to the
sgr client as a subcommand, as well as making it available to be used in Splitfiles.
For example, the
mount_postgres function:
def mount_postgres(mountpoint, server, port, username, password, dbname, remote_schema, tables=[]): """ Mount a Postgres database. Mounts a schema on a remote Postgres database as a set of foreign tables locally. :param mountpoint: Schema to mount the remote into. :param server: Database hostname. :param port: Port the Postgres server is running on. :param username: A read-only user that the database will be accessed as. :param password: Password for the read-only user. :param dbname: Remote database name. :param remote_schema: Remote schema name. :param tables: Tables to mount (default all). """ engine = get_engine() logging.info("Importing foreign Postgres schema...") # Name foreign servers based on their targets so that we can reuse them. server_id = '%s_%s_%s_server' % (server, str(port), dbname) init_fdw(engine, server_id, "postgres_fdw", {'host': server, 'port': str(port), 'dbname': dbname}, {'user': username, 'password': password}, overwrite=False) engine.run_sql(SQL("CREATE SCHEMA {}").format(Identifier(mountpoint))) # Construct a query: import schema limit to (%s, %s, ...) from server mountpoint_server into mountpoint query = "IMPORT FOREIGN SCHEMA {} " if tables: query += "LIMIT TO (" + ",".join("%s" for _ in tables) + ") " query += "FROM SERVER {} INTO {}" engine.run_sql(SQL(query).format(Identifier(remote_schema), Identifier(server_id), Identifier(mountpoint)), tables)
gets made available in the
sgr client with this help message:
$ sgr mount postgres_fdw --help Usage: sgr mount postgres_fdw [OPTIONS] SCHEMA Mount a Postgres database. Mounts a schema on a remote Postgres database as a set of foreign tables locally. Options: -c, --connection TEXT Connection string in the form username:password@server:port -o, --handler-options TEXT JSON-encoded dictionary of handler options: dbname: Remote database name. remote_schema: Remote schema name. tables: Tables to mount (default all). --help Show this message and exit.
The connection string gets parsed and passed to the mount handler as
server,
port,
username and
password parameters. The remaining options are converted from a JSON dictionary and passed to the handler as extra kwargs. | https://www.splitgraph.com/docs/ingesting-data/foreign-data-wrappers/load-mount-handlers | CC-MAIN-2020-45 | en | refinedweb |
Call a .Net WebAPI Service from Salesforce
- Posted in:
- .net
- integration
- salesforce
(Puedes ver este artículo en español aquí)
In a previous article, Call a .Net WCF Service from Salesforce, I explained how to make an external call in a Salesforce trigger to get data from a third party system by using a custom web service created in .Net WCF. This approach was using SOAP as the messaging protocol between Salesforce and our web service. We all know the advantages and disadvantages of SOAP compared to REST, but the truth is that REST is the preferred choice when it comes to creating web services. So, in this article I will modify the example presented in the previous post to use REST instead.
Allow me to refresh the problem we were trying to solve: our client wants to create sales quotes in Salesforce, but wants the price of products to come from the ERP. Our solution was to create a web service (a SOAP web service) in .Net WCF that given a product identifier returned the price of the product, we then called this service from a trigger defined in the QuoteLineItem object in Salesforce. We will keep the same architecture to the solution (the trigger and the web service) but this time we will use REST. I suggest you read the previous article to get a better understanding of what we would like to accomplish.
The WebAPI Service
Let’s start by creating our REST service. We will use an MVC WebAPI project in Visual Studio for this. I will use Visual Studio Community Edition to do this. Open Visual Studio and create a new “ASP.Net Web Application” name ErpApiService. Select “Web API” as the template and make sure you select “No Authentication” from the “Change Authentication” button (for simplicity we will not deal with security in this article).
Visual Studio will create a sample Web API project with a sample controller. Go to the Controllers folder and rename the file ValuesController.cs to ProductController.cs. If Visual Studio asks you to apply the rename to all references in code select yes. Replace the contents of the ProductController.cs file with the following:
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace ErpApiService.Controllers { public class ProductController : ApiController { // GET api/product/getPriceForCustomer?id={id} public decimal GetPriceForCustomer(string id) { try { ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings["ERP"]; using (SqlConnection cn = new SqlConnection(connectionString.ConnectionString)) { using (SqlCommand command = new SqlCommand("salesforce_getProductPrice", cn)) { command.CommandType = CommandType.StoredProcedure; command.Parameters.Add("@productId", SqlDbType.VarChar).Value = (object)id ?? DBNull.Value; SqlParameter priceParameter = command.Parameters.Add("@price", SqlDbType.Money); priceParameter.Direction = ParameterDirection.Output; cn.Open(); command.ExecuteNonQuery(); return (decimal)command.Parameters["@price"].Value; } } } catch (Exception e) { Trace.WriteLine(e.Message); return 0; } } } }
The highlighted line is the most important in this example, it defines the signature of the REST resource. By convention, if a method starts with Get (as in our example) the WebAPI engine will use the HTTP GET method to call it. The rest of the code is just ADO.Net boilerplate code to call a stored procedure in a database (in this case a SQLServer database).
Publish this web service to a public URL. In my case I published it to an IIS server in the DMZ and the URL is the following:{id} (don’t try it, it won’t work). Now, we are ready to consume this REST service from Salesforce.
Calling the REST Service from Salesforce
Go to Salesforce and using the Developer Console let’s create an anonymous code to test our service. Type the following APEX code:
String url = ''; Http h = new Http(); HttpRequest req = new HttpRequest(); req.setEndpoint(url); req.setMethod('GET'); HttpResponse res = h.send(req); system.debug('Price: ' + res.getBody());
You should be able to see the price sent from the ERP in the log.
Now let’s change the class we had from our previous article to do the REST call instead of SOAP. On the Developer Console, open the class QuoteLineItemProcesses class and replace the code with the following:
global with sharing class QuoteLineItemProcesses { @future (callout = true) public static void updateLinePrice(List<Id> lineItemIds) { Boolean changed = false; QuoteLineItem[] lineItems = [select QuoteId,Product2Id,UnitPrice from QuoteLineItem where Id in :lineItemIds]; for(QuoteLineItem lineItem : lineItems) { Quote quote = [select q.AccountId from Quote q where Id = :lineItem.QuoteId]; Product2 product = [select External_Id__c from Product2 where Id = :lineItem.Product2Id]; String productCode = product.External_Id__c; Decimal price = GetPrice(productCode); if(price > 0) { lineItem.UnitPrice = price; changed = true; } } if(changed) update lineItems; } private static Decimal GetPrice(String productCode) { String url = '' + productCode; Http h = new Http(); HttpRequest req = new HttpRequest(); req.setEndpoint(url); req.setMethod('GET'); HttpResponse res = h.send(req); return Decimal.valueOf(res.getBody()); } }
The callout to a REST service from a trigger follows the same principles we outlined in our previous article: it needs to be called from a class marked with the @future tag (for asynchronous call), it needs to be a static void method, and the trigger needs to be a after insert trigger.
You can now test the call by adding a new line item to an existing quote, Salesforce should call the REST service and assign the product price from the ERP to the line item.
You can get the sample code from here: | http://bloggiovannimodica.azurewebsites.net/post/call-a-net-webapi-service-from-salesforce | CC-MAIN-2020-45 | en | refinedweb |
Created on 2008-08-16 15:41 by cananian, last changed 2015-04-09 01:58 by martin.panter. This issue is now closed..
Not that we've removed the try one more time branch of the code,
because it was causing other problems.
Jeremy
On Sun, Aug 16, 2009 at 6:24 PM, Gregory P. Smith<report@bugs.python.org> wrote:
>
> Gregory P. Smith <greg@krypto.org> added the comment:
>
>.
>
> ----------
> priority: -> normal
>
> _______________________________________
> Python tracker <report@bugs.python.org>
> <>
> _______________________________________
> _______________________________________________
> Python-bugs-list mailing list
> Unsubscribe:
>
>
unassigning, i don't had time to look at this one.
Seems to affect 2.7 too.
I.
Trying to reproduce this on my own in 3.5, 2.7 and 2.5 yields a ConnectionResetError (ECONNRESET), which seems to be correct. That said, this could be due to varying TCP implementations on the server so might still be valid. It could also be due to an older kernel which has been fixed since this was originally reported. Is this still reproducible? If so, can an example be provided?
If the error as written is reproducible, I think that the error message should be fixed, but I'm not so sure that any more than that should be done.
As far as the RFC goes, I think the MUST clause pointed out can be left to the interpretation of the reader. You /could/ consider http.client as the client, but you could also consider the application that a user is interacting with as the client.
Offhand, I think that the library as it is does the right thing in allowing the application code to handle the exceptions as it sees fit. Because http.client in its current state doesn't allow for request pipelining, retries from calling code should be trivial, if that is what the caller intends to do.
I believe the BadStatusLine can still happen, depending on the circumstances. When I get a chance I will see if I can make a demonstration. In the meantime these comments from my persistent connection handler <> might be useful:
# If the server closed the connection,
# by calling close() or shutdown(SHUT_WR),
# before receiving a short request (<= 1 MB),
# the "http.client" module raises a BadStatusLine exception.
#
# To produce EPIPE:
# 1. server: close() or shutdown(SHUT_RDWR)
# 2. client: send(large request >> 1 MB)
#
# ENOTCONN probably not possible with current Python,
# but could be generated on Linux by:
# 1. server: close() or shutdown(SHUT_RDWR)
# 2. client: send(finite data)
# 3. client: shutdown()
# ENOTCONN not covered by ConnectionError even in Python 3.3.
#
# To produce ECONNRESET:
# 1. client: send(finite data)
# 2. server: close() without reading all data
# 3. client: send()
I think these behaviours were from experimenting on Linux with Python 3 sockets, and reading the man pages.
I think there should be a new documented exception, a subclass of BadStatusLine for backwards compatibility. Then user code could catch the new exception, and true bad status lines that do not conform to the specification or whatever won’t be caught. I agree that the library shouldn’t be doing any special retrying of its own, but should make it easy for the caller to do so.
Okay here is a demonstration script, which does two tests: a short basic GET request, and a 2 MB POST request. Output for me is usually:
Platform: Linux-3.15.5-2-ARCH-x86_64-with-arch
Normal request: getresponse() raised BadStatusLine("''",)
2 MB request: request() raised BrokenPipeError(32, 'Broken pipe'); errno=EPIPE
Sometimes I get a BadStatusLine even for the second request:
Platform: Linux-3.15.5-2-ARCH-x86_64-with-arch
Normal request: getresponse() raised BadStatusLine("''",)
2 MB request: getresponse() raised BadStatusLine("''",)
Spotted code in Python’s own library that maintains a persistent connection and works around this issue:
Lib/xmlrpc/client.py:1142
Hi Martin,
Thanks for the example code..
The reason that you're seeing different responses sometimes (varying between BadStatusLine and BrokenPipeError) is because of an understandable race condition between the client sending the requests and the server fully shutting down the socket and the client receiving FIN.
After digging into this, I'm not sure that there is a better way of handling this case. This exception can occur whether the client has issued a request prior to cleaning up and is expecting a response, or the server is simply misbehaving and sends an invalid status line (i.e. change your response code to an empty string to see what I mean).
I'll do some further digging, but I don't believe that there's really a good way to determine whether the BadStatusLine is due to a misbehaving server (sending a non-conforming response) or a closed socket. Considering that the client potentially has no way of knowing whether or not a server socket has been closed (in the case of TCPServer, it does a SHUT_WR), I think that BadStatusLine may be the appropriate exception to use here and the resulting action would have to be left up to the client implementation, such as in xmlrpc.client.
>.
Sorry, I mis-worded that. I'm /assuming/ that the misbehaving client is what you were intending on demonstrating as it shows the server closing the connection before the client expects it to do so.
Hi Demian, my intention is to demonstrate normal usage of Python’s HTTP client, whether or not its implementation misbehaves. I am trying to demonstrate a valid persistent server that happens to decide to close the connection after the first request but before reading a second request. Quoting the original post: “Servers may close a persistent connection after a request due to a timeout or other reason.” I am attaching a second demo script which includes short sleep() calls to emulate a period of time elapsing and the server timing out the connection, which is common for real-world servers.
The new script also avoids the EPIPE race by waiting until the server has definitely shut down the socket, and also demonstrates ECONNRESET. However this synchronization is artificial: in the real world the particular failure mode (BadStatusLine/EPIPE/ECONNRESET) may be uncertain.
If you are worried about detecting a misbehaving server that closes the connection before even responding to the first request, perhaps the HTTPConnection class could maintain a flag and handle the closed connection differently if it has not already seen a complete response.
If you are worried about detecting a misbehaving server that sends an empty status line without closing the connection, there will still be a newline code received. This is already handled separately by existing code: Lib/http/client.py:210 versus Lib/http/client.py:223.
I think there should be a separate exception, say called ConnectionClosed, for when the “status line” is an empty string (""), which is caused by reading the end of the stream. This is valid HTTP behaviour for the second and subsequent requests, so the HTTP library should understand it. BadStatusLine is documented for “status codes we don’t understand”. The new ConnectionClosed exception should probably be a subclass of BadStatusLine for backwards compatibility.
A further enhancement could be to wrap any ConnectionError during the request() stage, or first part of the getresponse() stage, in the same ConnectionClosed exception. Alternatively, the new ConnectionClosed exception could subclass both BadStatusLine and ConnectionError. Either way, code like the XML-RPC client could be simplified to:
try:
return self.single_request(...)
except http.client.ConnectionClosed:
#except ConnectionError: # Alternative
#retry request once if cached connection has gone cold
return self.single_request(...)
FWIW, I agree with the analysis here, its standard HTTP behaviour in the real world, and we should indeed handle it.
Sorry Martin, I should really not dig into issues like this first thing in the morning ;)
My concern about the proposed change isn't whether or not it isn't valid HTTP behaviour, it is. My concern (albeit a small one) is that the change implies an assumption that may not necessarily be true. No matter how valid based on the HTTP spec, it's still an assumption that /can/ potentially lead to confusion. I do agree that a change /should/ be made, I just want to make sure that all potential cases are considered before implementing one.
For example, applying the following patch to the first attachment:
52,57c52,53
< self.wfile.write(
< b"HTTP/1.1 200 Dropping connection\r\n"
< b"Content-Length: 0\r\n"
< b"\r\n"
< )
<
---
> self.wfile.write(b'')
>
Should the proposed change be made, the above would error out with a ConnectionClosed exception, which is invalid because the connection has not actually been closed and BadStatusLine is actually closer to being correct. Admittedly, this is a little contrived, doesn't adhere to the HTTP spec and is much less likely to happen in the real world than a connection unexpectedly closed by the server, but I don't think it's an unreasonable assumption for lesser used servers or proxies or those in development. In those cases, the proposed change would result in just as much confusion as the current behaviour with connections that are intended to be persistent.
In my mind, the one constant through both of these cases is that the response that the client has read is unexpected. In light of that, rather than a ConnectionClosed error, what about UnexpectedResponse, inheriting from BadStatusLine for backwards compatibility and documented as possibly being raised as a result of either case? I think this would cover both cases where a socket has been closed as well as an altogether invalid response.
Calling self.wfile.write(b"") should be equivalent to not calling write() at all, as far as I understand. Using strace, it does not seem to invoke send() at all. So the result will depend on what is written next. In the case of my code, nothing is written next; the connection is shut down instead. So I don’t believe this case is any different from “a connection unexpectedly closed by the server”. To be clear, I think the situation we are talking about is:
1. Client connects to server and sends short request; server accepts connection and possibly reads request
2. Server does not write any response, or just calls write(b""), which is equivalent
3. Server shuts down connection
4. Client reads end of stream (b"") instead of proper status line
But to address your concern in any case, see the third paragram in <>. I propose some internal flag like HTTPConnection._initial_response, that gets set to False after the first proper response is received. Then the code could be changed to something like:
if not line:
# Presumably, the server closed the connection before
# sending a valid response.
if self._initial_response:
raise BadStatusLine(line)
else:
raise ConnectionClosed("Stream ended before receiving response")
> Calling self.wfile.write(b"") should be equivalent to not calling write() at all, as far as I understand.
Right (or at least, as I understand it as well).
Really, this boils down to a philosophical debate: Should the standard library account for unexpected conditions where possible (within reason of course), or should it only account for conditions as described by specifications?
> 1. Client connects to server and sends short request; server accepts connection and possibly reads request
> [snip]
This flow makes sense and is well accounted for with your proposed change. However, misbehaving cases such as:
Granted, the result is unexpected and doesn't comply with HTTP RFCs. However, leading the user to believe that the connection has been closed when it actually hasn't is misleading. I've spent many an hour trying to hunt down root causes of issues like this and bashed my head against a keyboard in disbelief when I found out what the cause /really/ was. Because of those headaches, I still think that the introduction of an UnexpectedResponse, if well documented, covers both cases nicely, but won't heatedly argue it further :) If others (namely core devs) think that the introduction of ConnectionClosed exception is a better way to go, then I'll bow out. It would maybe be nice to have Senthil chime in on this.
> But to address your concern in any case, see the third paragram in <>.
I don't think that should be added at all as the issue that I'm describing can occur at any point, not only the first request.
On another note, were you interested in submitting a patch for this?
Yeah I’m happy to put a patch together, once I have an idea of the details.
I’d also like to understand your scenario that would mislead the user to believe that the connection has been closed when it actually hasn’t. Can you give a concrete example or demonstration?
Given your misbehaving flow:
I would expect the client would still be waiting to read the status line of the response that was never sent in step 2. Eventually the server _would_ probably drop the connection (so ConnectionClosed would not be misleading), or the client would time it out (a different error would be raised).
I think that in other stdlib networking modules, a connection closed error is raised when an operation is attempted on a closed connection. For example, in smtplib, the server may return an error code and then (contrary to the RFC) close the connection. We fixed a bug in smtplib where this was mishandled (the error code was lost and SMTPServerDisconnected was raised instead). Now we return the error code, and the *next* operation on the connection gets the connection closed error.
I think this is a good model, but I'm not sure if/how it can be applied here.).
I think the remote server writing a blank line to the socket is a very different thing from the remote server closing the connection without writing anything, so I may be misunderstanding something here. Note that handling this is potentially more complicated with https, since in that case we have a wrapper around the socket communication that has some buffering involved.
But also note that if a new exception is introduced this becomes a feature and by our normal policies can only go into 3.5.
TL;DR: Because HTTP is an application-level protocol, it's nearly impossible to gauge how a server will behave given a set of conditions. Because of that, any time that assumptions can be avoided, they should be.
@R. David Murray:
>).
In the typical case, this is exactly what happens. This issue is around a race condition that can occur between the client issuing a request prior to terminating the connection with the server, but the server terminating it prior to processing the request. In these cases, the client is left in a state where as far as it's concerned, it's in a valid state waiting for a response which the server will not issue as it has closed the socket on its side. In this case, the client reading an empty string from the receive buffer implies a closed socket. Unfortunately, it's not entirely uncommon when using persistent connections, as Martin's examples demonstrate.
> I think the remote server writing a blank line to the socket is a very different thing from the remote server closing the connection without writing anything, so I may be misunderstanding something here.
+1. What Martin is arguing here (Martin, please correct me if I'm wrong) is that a decently behaved server should not, at /any/ time write a blank line to (or effectively no-op) the socket, other than in the case where the socket connection has been closed. While I agree in the typical case, a blend of Postel and Murphy's laws leads me to believe it would be better to expect, accept and handle the unexpected.
@Martin:
Here's a concrete example of the unexpected behaviour. It's not specific to persistent connections and would be caught by the proposed "first request" solution, but ultimately, similar behaviour may be seen at any time from other servers/sources:.
Googling for "http empty response" and similar search strings should also provide a number of examples where unexpected behaviour is encountered and in which case raising an explicit "ConnectionClosed" error would add to the confusion.
Other examples are really hypotheticals and I don't think it's worth digging into them too deeply here. Unexpected behaviour (regardless of whether it's on the first or Nth request) should be captured well enough by now.
> Eventually the server _would_ probably drop the connection (so ConnectionClosed would not be misleading)
Sure, but you're raising an exception based on future /expected/ behaviour. That's my issue with the proposed solution in general. ConnectionClosed assumes specific behaviour, where literally /anything/ can happen server side.
Now I think I'd like to take my foot out of my mouth.
Previous quick experiments that I had done were at the socket level, circumventing some of the logic in the HTTPResponse, mainly the calls to readline() rather than simple socket.recv(<N>).
I've confirmed that the /only/ way that the HTTPConnection object can possibly get a 0-length read is, in fact, if the remote host has closed the connection.
In light of that, I have no objection at all to the suggested addition of ConnectionClosed exception and my apologies for the added confusion and dragging this issue on much longer than it should have been.
I've also attached my proof of concept code for posterity.
(Admittedly, I may also have been doing something entirely invalid in previous experiments as well)
Here is a patch, including tests and documentation. It ended up a bit more complicated than I anticipated, so I’m interested in hearing other ideas or options.
* Added http.client.ConnectionClosed exception
* HTTPConnection.close() is implicitly called for a persistent connection closure
* BadStatusLine or ConnectionError (rather than new exception) is still raised on first getresponse()
* request() raising a ConnectionError does not necessarily mean the server did not send a response, so ConnectionClosed is only raised by getresponse()
* ConnectionClosed wraps ECONNRESET from the first recv() of the status line, but not after part of the status line has already been received
With this I hope code for making idempotent requests on a persistent connection would look a bit like this:
def idempotent_request(connection)
try:
attempt_request(connection, ...)
response = connection.get_response()
if response.status == HTTPStatus.REQUEST_TIMEOUT:
raise ConnectionClosed(response.reason)
except ConnectionClosed:
attempt_request(connection, ...)
response = connection.get_response()
return response
def attempt_request(connection):
try:
connection.request(...)
except ConnectionError:
pass # Ignore and read server response
Updated v2 patch. This version avoids intruding into the HTTPConnection.connect() implementation, so that users, tests, etc may still set the undocumented “sock” attribute without calling the base connect() method. Also code style changes based on feedback to another of my patches.
Thanks for the patch Martin (as well as catching a couple issues that I'd run into recently as well). I've left a couple comments up on Rietveld.
Thanks for the reviews.
I agree about the new HTTPResponse flag being a bit awkward; the HTTPResponse class should probably raise the ConnectionClosed exception in all cases. I was wondering if the the HTTPConnection class should wrap this in a PersistentConnectionClosed exception or something if it wasn’t for the first connection, now I’m thinking that should be up to the higher level user, in case they are doing something like HTTP preconnection.
> now I’m thinking that should be up to the higher level user
+1. A closed connection is a closed connection, whether it's persistent or not. The higher level code should be responsible for the context, not the connection level.
I have changed my opinion of the “peek hack” from <>. It would be useful when doing non-idempotent requests like POST, to avoid sending a request when we know it is going to fail. I looked into how to implement it so that it works for SSL (which does not support MSG_PEEK), and the neatest solution I could think of would require changing the non-blocking behaviour of BufferedReader.peek(), as described in Issue 13322. So I will leave that for later.
Adding ConnectionClosed.v3.patch; main changes:
* Removed the connection_reused flag to HTTPResponse
* ConnectionClosed raised even for the first request of a connection
* Added HTTPConnection.closed flag, which the user may check before a request to see if a fresh connection will be made, or an existing connection will be reused
* ConnectionClosed now subclasses both BadStatusLine and ConnectionError
* Fixed http.client.__all__ and added a somewhat automated test for it
BTW these patches kind of depend on Issue 5811 to confirm that BufferedReader.peek() will definitely return at least one byte unless at EOF.
If it would help the review process, I could simplify my patch by dropping the addition of the HTTPConnection.closed flag, so that it just adds the ConnectionClosed exception. Looking forwards, I’m wondering if it might be better to add something like a HTTPConnection.check_remote_closed() method instead of that flag anyway.
My apologies for the delay, but I've now reviewed the proposed patch. With a fresh outlook after taking a bit of time off, I'm not sure anymore that this is the best way of going about solving this problem. The main reason being that we now have two errors that effectively mean the same thing: The remote socket has encountered some error condition.
I understand that ConnectionClosed was added to maintain backwards compatibility with the BadStatusLine error, but I'm beginning to think that what really should be done is that backwards compatibility /should/ be broken as (in my mind) it's one of those cases where the backwards compatible solution may introduce just as many issues as it solves.
The root issue here (or at least what it has turned into) is that BadStatusLine is incorrectly raised when EOF is encountered when reading the status line. In light of that, I think that simply raising a ConnectionError in _read_status where line is None is the right way to fix this issue. Not only is it consistent with other cases where the remote socket is closed (i.e. when reading the response body), but it's removing the need for the addition of a potentially confusing exception.
I'm not 100% what the policy is around backwards introducing backwards incompatible changes is, but I really think that this is one of those few cases where it really should be broken.
Thanks for helping with this Demian. The idea of raising the same exception in all cases is new to me. Initially I was opposed, but it is starting to make sense. Let me consider it some more. Here are some cases that could trigger this exception:
1. EOF before receiving any status line. This is the most common case. Currently triggers BadStatusLine.
2. EOF in the middle of the status line. Triggers BadStatusLine, or is treated as an empty set of header fields.
3. EOF in the middle of a header line, or before the terminating blank line. Ignored, possibly with HTTPMessage.defects set.
4. EOF after receiving 100 Continue response, but before the final response. Currently triggers the same BadStatusLine.
5. ConnectionReset anywhere before the blank line terminating the header section.
In all those cases it should be okay to automatically retry an idempotent request. With non-idempotent requests, retrying in these cases seems about equally dangerous.
For contrast, some related cases that can still be handled differently:
6. Connection reset or broken pipe in the request() method, since the server can still send a response
7. Unexpected EOF or connection reset when reading the response body. Perhaps this could also be handled with a similar ConnectionError exception. Currently IncompleteRead is raised for EOF, at least in most cases. IncompleteRead has also been suggested as an alternative to BadStatusLine in the past.
> Thanks for helping with this Demian.
No worries. This textual white boarding exercise has also been greatly
valuable in getting my own head wrapped around various low frequency
socket level errors that can be encountered when using the client. The
downside is that this issue is now quite likely very difficult for new
readers to follow :/
> The idea of raising the same exception in all cases is new to me.
This initially puzzled me. I then re-read my response and realized that
I was thinking one thing and wrote another. The exception that I was
intending to suggest using here is ConnectionResetError, rather than the
ConnectionError base class. To elaborate a little further, as I
understand it, the /only/ case where the empty read happens is when the
remote connection has been closed but where the TCP still allows for EOS
to be read. In this case, the higher level implementation (in this case
the client) /knows/ that the empty line is signifying that the
connection has been closed by the remote host.
To be clear, a rough example of what I'm proposing is this:
diff -r e548ab4ce71d Lib/http/client.py
--- a/Lib/http/client.py Mon Feb 09 19:49:00 2015 +0000
+++ b/Lib/http/client.py Wed Feb 11 06:04:08 2015 -0800
@@ -210,7 +210,7 @@
if not line:
# Presumably, the server closed the connection before
# sending a valid response.
- raise BadStatusLine(line)
+ raise ConnectionResetError
try:
version, status, reason = line.split(None, 2)
except ValueError:
Your example of the XML-RPC client would then use the alternative approach:
try:
return self.single_request(...)
except ConnectionError:
#retry request once if cached connection has gone cold
return self.single_request(...)
That all said, I'm also not tremendously opposed to the introduction of
the ConnectionClosed exception. I simply wanted to explore this thought
before the addition is made, although the comments in my patch review
would still hold true.
It is possible to break backward compatibility in a feature release if the break is fixing a bug. In this case I think it is in fact doing so, and that in fact in the majority of cases the change would either not break existing code or would even improve it (by making debugging easier). However, I have no way to prove that.
Often in the cases of compatibility breaks we will do a deprecation of the old behavior in a given release and make the change in the next release. I'm not convinced that is necessary (or even possible) here. It would be nice if we could get some data on what the actual impact would be on existing code. For example: how, if at all, would this affect the requests package? I *can* give one data point: in an application I wrote recently the affect would be zero, since every place in my application that I catch BadStatusLine I also catch ConnectionError.
I would want at least one other committer to sign off on a compatibility break before anything got committed.
Posting RemoteDisconnected.v4.patch with these changes:
* Renamed ConnectionClosed → RemoteDisconnected. Hopefully avoids confusion with shutting down the local end of a connection, or closing a socket’s file descriptor.
* Dropped the HTTPConnection.closed attribute
* Dropped special distinction of ECONNRESET at start versus in middle of response. It certainly makes the code and tests simpler again, and I realize that distinction is not the most important problem to solve right now, if ever. Also avoids relying on the poorly defined BufferedReader.peek() method.
I would like to retain the backwards compatibility with BadStatusLine if that is okay though.
Requests and “urllib3”: I’m not overly familiar with the internals of these packages (Requests uses “urllib3”). I cannot find any reference to BadStatusLine handling in “urllib3”, and I suspect it might just rely on detecting a dropped connection before sending a request; see <>. In my opinion this is a race condition, but it is helpful and works most of the time. So I suspect “urllib3” would not be affected by any changes made relating to BadStatusLine.
Left a few minor comments in Rietveld.
My only opposition to the RemoteDisconnected error is now we have two exceptions that effectively mean the same thing. It looks like asyncio.streams has similar behaviour:. I think that if it's acceptable to break backwards compatibility here, we should.
Browsing through some Github repos, it seems like this change /could/ potentially impact a few smaller projects. I can confirm, however, that neither urllib3 nor requests are dependent on BadStatusLine.
I guess you saying RemoteDisconnected effectively means the same thing as ConnectionResetError. Would it help if it was derived from ConnectionResetError, instead of the ConnectionError base class? Or are you also worried about the multiple inheritance or clutter of yet another type of exception?
I’m not really familiar with the “asyncio” streams/protocols/transports/thingies, but it looks like the code you pointed to is actually called when writing, via drain(), fails. Maybe the equivalent code for when reading hits EOF is <>.
> On Feb 19, 2015, at 8:08 PM, Martin Panter <report@bugs.python.org> wrote:
> I guess you saying RemoteDisconnected effectively means the same thing as ConnectionResetError.
Exactly.
> Would it help if it was derived from ConnectionResetError, instead of the ConnectionError base class? Or are you also worried about the multiple inheritance or clutter of yet another type of exception?
My concern is more about consistency of exceptions and exception handling when using the client. Thinking about it from a user’s standpoint, when I issue a request and the remote socket closes, I would hope to get consistent exceptions for all remote resets. If I’m handling the lowest level errors independently of one another rather than catch-all ConnectionError, I don’t want to do something like this:
except (RemoteDisconnected, ConnectionResetError)
I /should/ be able to simply use ConnectionResetError. Reading the docs, the only real reason for this exception at all is for backwards compatibility. If we have a case to break backwards compatibility here, then that eliminates the need for the new exception and potential (minor) confusion.
In this special case, the behaviour that we see at the client socket level indicates a remote reset, but it’s only artificially known immediately due to the empty read. In my mind, because the client /knows/ that this is an early indicator of a ConnectionResetError, that is exactly the exception that should be used.
Hope that makes sense.
Posting RemoteDisconnected.v5.patch:
* Rebased and fixed minor merge conflict
* Change RemoteDisconnected base class from ConnectionError to ConnectionResetError
* Minor tweaks to tests
It seems that having a separate RemoteDisconnected exception (as in this patch) has at least two benefits:
1. It would allow the user to distinguish between a true ConnectionResetError (due to TCP reset or whatever) from a clean TCP shutdown
2. Backwards compatibility with user code that only handles BadStatusLine
The only disadvantage seems to be the bloat of adding a new exception type. But if some other comitter agrees that merging them is better and dropping backwards compatibility is okay I am happy to adjust the patch to go along with that.
Pending review of the exceptions from another core dev, the patch looks good to me. Thanks for sticking with it :)
New changeset eba80326ba53 by R David Murray in branch 'default':
#3566: Clean up handling of remote server disconnects.
Thanks, Martin and Demian. I tweaked the patch slightly before commit, so I've uploaded the diff. After thinking about it I decided that it does indeed make sense that the new exception subclass both ConnectionResetError and BadStatusLine, exactly because it *isn't* a pure ConnectionError, it is a synthetic one based on getting a '' response when we are expecting a status line. So I tweaked the language to not mention backward compatibility. I also tweaked the language of the docs, comments and error message to make it clear that the issue is that the server closed the connection (I understand why you changed it to 'shut down', but I think 'the server closed the connection' is both precise enough and more intuitive).
If you have any issues with the changes I made, let me know.
Your tweaks look fine. Thanks everyone for working through this one. | https://bugs.python.org/issue3566 | CC-MAIN-2020-45 | en | refinedweb |
!- Search Loader --> <!- /Search Loader -->
I have Intel C++ 14.0.2 installed on Windows 7 with Visual Studio 2008. I need to use some C++11 features, such as:
[cpp]
#include <memory>
int main(int argc, char** argv){
std::unique_ptr<int> ptr;
return 1;
}
[/cpp]
Trying to compile this manually on the Intel Parallel Studio cmd window using: "icl /Qstd=c++11 main.cpp"
results in the error message: 'error: namespace "std" has no member "unique_ptr"'
Is this intended to work? Does Intel Parallel Studio contain its own complete C++ headers, or does it rely on Visual Studio to provide them?
If the latter, what is the purpose of std=c++11? I recall seeing documentation about this topic somewhere in the past, but did not find anything obvious, e.g., in the /Qstd manual entry.
I realize that VS2008 is rather old and hope to upgrade in the near future. However I really have no use for anything but icl/ifort at the moment.
Thank you,
Matt
Hi,
ICC on Windows rely on MSVC headers and CRT library, on Linux on gcc and glibc library. This is for providing maximum compatibility with native environment. MSVC 2008 is very old, you should be fine with 2012 or even better, MSVC 2013.
So this means that Intel C++ on Windows only has the C++11 support that Microsoft provides? Then what is the meaning of the manual description for /Qstd:
DEFAULTS /Qstd=OFF. Note that a subset of C++11 features is enabled by default for compatibility with a particular version of Microsoft Visual Studio* C++, so you only need to specify /Qstd=c++0x if you want additional C++11 functionality beyond what Microsoft provides.
How does Intel "add additional C++11 functionality beyond what Microsoft provides" if it relies on the MS headers and library?! I can understand using these headers and libraries by default (for compatibility), but wouldn't Intel need to provide updated headers for their C++11 improvements?
Thank you,
- Matt
Hi Matt
Remember C++0x and 11 is not only about STL headers, but also the syntax has been improved, like r-value references, variadic template arguments, strongly-typed enums, lambda functions and many more.
Btw, MSVC 2008 reached end-of-life and many projects dropped support for this archaic compiler. When you are speaking about C++11, you are definitely speaking of MSVC 2013. On Linux, the same situation is there.
Yes /Qstd=c++11 provides lots of additional c++11 compiler support (i.e. language features), but does not provide any additional c++11 library support. | https://community.intel.com/t5/Intel-C-Compiler/Requirements-for-C-11-Support-on-Windows/m-p/920621/highlight/true | CC-MAIN-2020-45 | en | refinedweb |
32136/sending-keys-in-windows-10-iot
So, I developed a capacitive I2C keyboard for a Raspberry Pi 2 with Windows 10 IoT, so when my I2C controller detects a keystroke I need to send a key to the current page.
In windows forms I have used:
SendKeys.Send("{ENTER}");
How can I send keys?
Sorry, but it is not allowed in UWP due to some APIs restriction to be called only by user interaction.
Instead, you can programmatically write text to the textboxes like:
// To simulate key 'A' and 'B'
Textbox1.Text += 'A';
Textbox1.Text += 'B';
// To simulate backspace if Textbox contains any character
if (Textbox1.Text.Length > 0)
{
Textbox1.Text = Textbox1.Text.Remove(Textbox1.Text.Length - 1);
}
Problem with this snippet is, you can't simulate special key like ALT, CTRL, F1-F12, Shift and WinKey.
On Windows IoT you have to use Windows.Devices.SerialCommunication namespace ...READ MORE
It is possible, but you should understand ...READ MORE
Of course, you, can! That is, in ...READ MORE
You can take a look at this ...READ MORE
Since it uses SPI, there shouldn't be ...READ MORE
I was looking for a solution too, ...READ MORE
It can be done by making changes ...READ MORE
You'll be glad to know that C# ...READ MORE
You could follow this link here to ...READ MORE
All you have to do is stop and ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/32136/sending-keys-in-windows-10-iot?show=32138 | CC-MAIN-2020-45 | en | refinedweb |
)
The naive approach for this general tree LCA calculation will be the same as the naive approach for the LCA calculation of Binary Tree (this naive approach is already well described here.
The C++ implementation for the naive approach is given below :-
/* Program to find LCA of n1 and n2 using one DFS on the Tree */ #include "iostream" #include "vector" using namespace std; // Maximum number of nodes is 100000 and nodes are // numbered from 1 to 100000 #define MAXN 100001 vector < int > tree[MAXN]; int path[3][MAXN]; // storing root to node path // storing the path from root to node void dfs(int cur, int prev, int pathNumber, int ptr, int node, bool &flag) { for (int i=0; i<tree[cur].size(); i++) { if (tree[cur][i] != prev and !flag) { // pushing current node into the path path[pathNumber][ptr] = tree[cur][i]; if (tree[cur][i] == node) { // node found flag = true; // terminating the path path[pathNumber][ptr+1] = -1; return; } dfs(tree[cur][i], cur, pathNumber, ptr+1, node, flag); } } } // This Function compares the path from root to 'a' & root // to 'b' and returns LCA of a and b. Time Complexity : O(n) int LCA(int a, int b) { // trivial case if (a == b) return a; // setting root to be first element in path path[1][0] = path[2][0] = 1; // calculating path from root to a bool flag = false; dfs(1, 0, 1, 1, a, flag); // calculating path from root to b flag = false; dfs(1, 0, 2, 1, b, flag); // runs till path 1 & path 2 mathches int i = 0; while (path[1][i] == path[2][i]) i++; // returns the last matching node in the paths return path[1][i-1]; } void addEdge(int a,int b) { tree[a].push_back(b); tree[b].push_back(a); } // Driver code int main() { int n = 8; // Number of nodes addEdge(1,2); addEdge(1,3); addEdge(2,4); addEdge(2,5); addEdge(2,6); addEdge(3,7); addEdge(3,8); cout << "LCA(4, 7) = " << LCA(4,7) << endl; cout << "LCA(4, 6) = " << LCA(4,6) << endl; return 0; }
Output:
LCA(4, 7) = 1 LCA(4, 6) = 2]
C++ implementation of the above algorithm is given below:
// Sparse Matrix DP approach to find LCA of two nodes #include <bits/stdc++.h> using namespace std; #define MAXN 100000 #define level 18 vector <int> tree[MAXN]; int depth[MAXN]; int parent[MAXN][level]; // pre-compute the depth for each node and their // first parent(2^0th parent) // time complexity : O(n) void dfs(int cur, int prev) { depth[cur] = depth[prev] + 1; parent[cur][0] = prev; for (int i=0; i<tree[cur].size(); i++) { if (tree[cur][i] != prev) dfs(tree[cur][i], cur); } } // Dynamic Programming Sparse Matrix Approach // populating 2^i parent for each node // Time complexity : O(nlogn) void precomputeSparseMatrix(int n) { for (int i=1; i<level; i++) { for (int node = 1; node <= n; node++) { if (parent[node][i-1] != -1) parent[node][i] = parent[parent[node][i-1]][i-1]; } } } // Returning the LCA of u and v // Time complexity : O(log n) int lca(int u, int v) { if (depth[v] < depth[u]) swap(u, v); int diff = depth[v] - depth[u]; // Step 1 of the pseudocode for (int i=0; i<level; i++) if ((diff>>i)&1) v = parent[v][i]; // now depth[u] == depth[v] if (u == v) return u; // Step 2 of the pseudocode for (int i=level-1; i>=0; i--) if (parent[u][i] != parent[v][i]) { u = parent[u][i]; v = parent[v][i]; } return parent[u][0]; } void addEdge(int u,int v) { tree[u].push_back(v); tree[v].push_back(u); } // driver function int main() { memset(parent,-1,sizeof(parent)); int n = 8; addEdge(1,2); addEdge(1,3); addEdge(2,4); addEdge(2,5); addEdge(2,6); addEdge(3,7); addEdge(3,8); depth[0] = 0; // running dfs and precalculating depth // of each node. dfs(1,0); // Precomputing the 2^i th ancestor for evey node precomputeSparseMatrix(n); // calling the LCA function cout << "LCA(4, 7) = " << lca(4,7) << endl; cout << "LCA(4, 6) = " << lca(4,6) << endl; return 0; }.. | https://www.geeksforgeeks.org/lca-for-general-or-n-ary-trees-sparse-matrix-dp-approach-onlogn-ologn/ | CC-MAIN-2018-09 | en | refinedweb |
As we mentioned early in chapter 4, JLayeredPane can sometimes come in handy when we want to manually position and size components. Because it's layout is null, it is not prone to the effects of resizing. Thus, when its parent is resized, a layered pane's children will stay in the same position and maintain the same size. (We saw a simple example of this in the beginning of chapter 6.) However, there are other ways to use JLayeredPane in typical interfaces. For instance, we can easily place a nice background image behind all of our components, giving life to an otherwise dull-looking panel.
Figure 15.3. The JLayeredPane standard layers
<<file figure15-3.gif>>
The Code: TestFrame.java
see \Chapter15\1
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TestFrame extends JFrame
{
public TestFrame() {
super("JLayeredPane Demo");
setSize(256,256);
JPanel content = new JPanel();
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.setOpaque(false);
JLabel label1 = new JLabel("Username:");
label1.setForeground(Color.white);
content.add(label1);
JTextField field = new JTextField(15);
content.add(field);
JLabel label2 = new JLabel("Password:");
label2.setForeground(Color.white);
content.add(label2);
JPasswordField fieldPass = new JPasswordField(15);
content.add(fieldPass);
getContentPane().setLayout(new FlowLayout());
getContentPane().add(content);
((JPanel)getContentPane()).setOpaque(false);
ImageIcon earth = new ImageIcon("earth.jpg");
JLabel backlabel = new JLabel(earth);
getLayeredPane().add(backlabel,
new Integer(Integer.MIN_VALUE));
backlabel.setBounds(0,0,earth.getIconWidth(),
earth.getIconHeight());
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(l);
setVisible(true);
}
public static void main(String[] args) {
new TestFrame();
}
Most of this code should look familiar. We extend JFrame and create a new JPanel with a y-oriented BoxLayout. We make this panel non-opaque so our background image will show through, then we add four simple components: two JLabels, a JTextField, and a JPasswordField. We then set the layout of the contentPane to FlowLayout (remember that the contentPane has a BorderLayout by default), and add our panel to it. We also set the contentPane's opaque property to false ensuring that our background will show through this panel as well. Finally we create a JLabel containing our background image, add it to our JFrame's layeredPane, and set its bounds based on the background image's size. | http://javafaq.nu/java-bookpage-26-2.html | CC-MAIN-2018-09 | en | refinedweb |
Building EJB Based JAX-WS Web Services
In this section, we will explain how we can build and consume JAX-WS Web service. The web service will be based on EJB class.
This is a simple Service with one method called sayHello. The method takes one parameter and returns the string “Hello {parameter}!”
From the file menu in eclipse, select to create a new EJB project.
Name the EJB project as HelloEJBWebServices and select to add the project to EAR called HelloEJBWebServicesEAR, then click Next
Select the check box to create and JB client JAR module.--.
Do not select ‘Generate ejb-jar.xml--.
Right click on the EJB project in the project explorer window and select to create a Session Bean class.
Give the bean name “HelloWorldJAXWS” and set to package “com.ejb3.webservice”, click finish, the following code will be generated:
package com.ejb3.webservice; import javax.ejb.LocalBean; import javax.ejb.Stateless; /** * Session Bean implementation class HelloWorldJAXWS */ @Stateless @LocalBean public class HelloWorldJAXWS { /** * Default constructor. */ public HelloWorldJAXWS() { // TODO Auto-generated constructor stub } }
Till now we have an EJB project called HelloEJBWebServices added to EAR HelloEJBWebServicesEAR, and the EJB project has one EJB class called HelloWorldJAXWS.
To expose an EJB class to a web service, all you have to do is to annotate the EJB class with the annotation javax.jws.WebService, the web services will be exposed automatically with all the public methods declared in the class.
Add a new method to the class called sayHello like the below:
package com.ejb3.webservice; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.jws.WebService; /** * Session Bean implementation class HelloWorldJAXWS */ @WebService @Stateless @LocalBean public class HelloWorldJAXWS { /** * Default constructor. */ public HelloWorldJAXWS() { // TODO Auto-generated constructor stub } public String sayHello(String name) { return "Hello " + name + "!"; } }
Notice that we added the @WebService annotation to our EJB class. Let’s test our code till now, using eclipse export the EAR and deploy it to JBOSS.
Start JBOSS and take a look at the Console output, look at the following lines:
These lines indicate that JBOSS detected the EJB class and also that the EJB class annotated with @WebSerivce annotation. It should be exposed as web service, and JBOSS handled that and provides you with the URL that can be used to access the web service
We can use the URL to test the web service directly in the browser, copy the URL to the browser and append ?WSDL to the end of it (i.e.)
Now if everything worked fine with you till now, let us move to the next step, testing the web service using Java console application.
Create a new console application in eclipse called HelloJAXWSTestClient, right click on the project icon in the package viewer and select to “Other” from the “New” menu item.
From the New wizard, type in the top text area “web service” then select to create new “Web Service Client”, click next button.
In the service definition text area, type the URL of the web service that was printed by JBOSS server appended by ?WSDL (i.e.) and click finish button. This will create a client that can be used to access our HelloJAXWS web service.
This is what you should have in your package explore windows.
Now in the client project, create a new Java class called Main, with the following code inside.
package com.ejb3.webservice; import java.rmi.RemoteException; import javax.xml.rpc.ServiceException; public class Main { public static void main(String[] args) throws ServiceException, RemoteException { HelloWorldJAXWSServiceLocator l = new HelloWorldJAXWSServiceLocator(); HelloWorldJAXWS port = (HelloWorldJAXWS)l.getPort(HelloWorldJAXWS.class); String res = port.sayHello("Jon"); System.out.println(res); } }
Now run the class as a Java Application, the following output should be displayed in the console windows:
If this is the output you got, then everything is working fine in your environment.
Now if you noticed, when you tried to call the method sayHello, eclipse couldn’t recognized the web service method parameter names, you got only arg0.
If you displayed the WSDL file again () in your browser, you will notice the following lines:
<xs:complexType <xs:sequence> <xs:element </xs:sequence> </xs:complexType>
These lines describe the sayHello method, and as noted the parameter name wasn’t exposed by JBOSS, only arg0 was found, and that’s why eclipse couldn’t detect the correct names for the method parameters.
To fix that, modify the web service code with the following:
package com.ejb3.webservice; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; /** * Session Bean implementation class HelloWorldJAXWS */ @WebService @Stateless @LocalBean public class HelloWorldJAXWS { /** * Default constructor. */ public HelloWorldJAXWS() { // TODO Auto-generated constructor stub } @WebMethod public String sayHello(@WebParam(name = "name") String name) { return "Hello " + name + "!"; } }
Notice that we annotated the method with @WebMethod annotation and also the parameter name was annotated with the @WebParam annotation and the annotation attribute name is declared with the value “name”.
Now, redeploy the web service again to JBOSS and check the WSDL file from the browser window, you will get the following lines:
<xs:complexType <xs:sequence> <xs:element </xs:sequence> </xs:complexType>
As noted, the WSDL file now has the correct name of the parameter. Now as the WSDL changed, our generated client must be rebuilt again. Follow the previous steps to generate the client and check the sayHello method in eclipse, you will get the following:
Now eclipse can detect the correct parameter name. | http://www.wideskills.com/ejb/building-ejb-based-jax-ws-web-services | CC-MAIN-2018-09 | en | refinedweb |
ASP.NET # MVC # 15 – Html Helper Class , Html Helper Method , Strongly Typed HTML Helpers.
Hi Geeks,
Today we will see very important and interesting feature provided by Microsoft for asp.net MVC called HTML Helper class,HTML Helper methods.
I) HtmlHelper Class represents support for rendering HTML controls in a view.
The ViewPage class has an HtmlHelper property named Html like follow
When you look at the methods of HtmlHelper, you’ll notice that it’s pretty sparse. This property is really an anchor point for attaching extension methods. When you import the System.Web.Mvc.Html namespace (imported by default in the default template), the Html property suddenly lights up with a bunch of helper methods.
In following screen shot u can observe it
II) HtmlHelper Methods
ASP.NET MVC 2 includes support for strongly typed HTML helpers, which allow you to specify
Model properties using a Lambda expression rather than as strings.
For example, where you would have previously used <%: Html.TextBox(“PropertyName”) %> in ASP.NET MVC 1, you can now use <%: Html.TextBoxFor(m => m.PropertyName) %>.
Replacing strings with expressions provides a number of benefits, including type checking, IntelliSense, and simpler refactoring.
We have following important strongly typed Html Helper Methods :-
- Html.Encode
- Html.TextBox
- Html.ActionLink and Html.RouteLink
- Html.BeginForm
- Html.Hidden
- Html.DropDownList and Html.ListBox
- Html.Password
- Html.RadioButton
- Html.Partial and Html.RenderPartial
- Html.Action and Html.RenderAction
- Html.TextArea
- Html.ValidationMessage
- Html.ValidationSummary
For More on ASP.NET MVC visit LEARN ASP.NET MVC IN DETAIL
Thank You. | https://microsoftmentalist.wordpress.com/2011/09/19/asp-net-mvc-15-html-helper-class-html-helper-method-strongly-typed-html-helpers/ | CC-MAIN-2018-09 | en | refinedweb |
unique (<algorithm>)
Removes duplicate elements that are adjacent to each other in a specified range.
Both forms of the algorithm remove the second duplicate of a consecutive pair of equal elements.
The operation of the algorithm is stable so that the relative order of the undeleted elements is not changed.
The range referenced must be valid; all pointers must be dereferenceable and within the sequence the last position is reachable from the first by incrementation. he number of elements in the sequence is not changed by the algorithm unique and the elements beyond the end of the modified sequence are dereferenceable but not specified.
The complexity is linear, requiring (_Last – _First) – 1 comparisons.
List provides a more efficient member function unique, which may perform better.
These algorithms cannot be used on an associative container.
// alg_unique.cpp // compile with: /EHsc #include <vector> #include <algorithm> #include <functional> #include <iostream> #include <ostream> using namespace std; // Return whether modulus of elem1 is equal to modulus of elem2 bool mod_equal ( int elem1, int elem2 ) { if ( elem1 < 0 ) elem1 = - elem1; if ( elem2 < 0 ) elem2 = - elem2; return elem1 == elem2; }; int main( ) { vector <int> v1; vector <int>::iterator v1_Iter1, v1_Iter2, v1_Iter3, v1_NewEnd1, v1_NewEnd2, v1_NewEnd3; int i; for ( i = 0 ; i <= 3 ; i++ ) { v1.push_back( 5 ); v1.push_back( -5 ); } int ii; for ( ii = 0 ; ii <= 3 ; ii++ ) { v1.push_back( 4 ); } v1.push_back( 7 ); cout << "Vector v1 is ( " ; for ( v1_Iter1 = v1.begin( ) ; v1_Iter1 != v1.end( ) ; v1_Iter1++ ) cout << *v1_Iter1 << " "; cout << ")." << endl; // Remove consecutive duplicates v1_NewEnd1 = unique ( v1.begin ( ) , v1.end ( ) ); cout << "Removing adjacent duplicates from vector v1 gives\n ( " ; for ( v1_Iter1 = v1.begin( ) ; v1_Iter1 != v1_NewEnd1 ; v1_Iter1++ ) cout << *v1_Iter1 << " "; cout << ")." << endl; // Remove consecutive duplicates under the binary prediate mod_equals v1_NewEnd2 = unique ( v1.begin ( ) , v1_NewEnd1 , mod_equal ); cout << "Removing adjacent duplicates from vector v1 under the\n " << " binary predicate mod_equal gives\n ( " ; for ( v1_Iter2 = v1.begin( ) ; v1_Iter2 != v1_NewEnd2 ; v1_Iter2++ ) cout << *v1_Iter2 << " "; cout << ")." << endl; // Remove elements if preceded by an element that was greater v1_NewEnd3 = unique ( v1.begin ( ) , v1_NewEnd2, greater<int>( ) ); cout << "Removing adjacent elements satisfying the binary\n " << " predicate mod_equal from vector v1 gives ( " ; for ( v1_Iter3 = v1.begin( ) ; v1_Iter3 != v1_NewEnd3 ; v1_Iter3++ ) cout << *v1_Iter3 << " "; cout << ")." << endl; } | https://msdn.microsoft.com/en-us/library/9f5eztca(v=vs.90).aspx | CC-MAIN-2018-09 | en | refinedweb |
public class WorkspaceModifyDelegatingOperation extends WorkspaceModifyOperation
This class may be instantiated; it is not intended to be subclassed.
getRule, run, threadChange
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
public WorkspaceModifyDelegatingOperation(IRunnableWithProgress content, ISchedulingRule rule)
content- the runnable to delegate to when this operation is executed
rule- The ISchedulingRule to use or
null.
public WorkspaceModifyDelegatingOperation(IRunnableWithProgress content)
content- the runnable to delegate to when this operation is executed
protected void execute(IProgressMonitor monitor) throws CoreException, InterruptedException
WorkspaceModifyOperation
Subclasses must implement this method.
executein class
WorkspaceModifyOperation
monitor- the progress monitor to use to display progress and field user requests to cancel
CoreException- if the operation fails due to a.
Copyright (c) 2000, 2017 Eclipse Contributors and others. All rights reserved.Guidelines for using Eclipse APIs. | http://help.eclipse.org/oxygen/nftopic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/ui/actions/WorkspaceModifyDelegatingOperation.html | CC-MAIN-2018-09 | en | refinedweb |
With just a few lines of code, your Python application can make and receive phone calls with Twilio Programmable Voice.
This Python quickstart will teach you how to do this using our REST API, the Twilio Python helper library, and Python’s Flask microframework to ease development.
In this quickstart, you will learn how to:
Prefer to get started by watching a video? Check out our video on how to place and receive phone calls with Python on Youtube.
If you already have a Twilio account and a voice-enabled Twilio phone number you’re all set here! Log in then feel free to jump to the next step.
Before you can make a phone call from Python, click "Search."
You’ll then see a list of available phone numbers and their capabilities. Find a number that suits your fancy and click "Buy" to add it to your account.
Now that you have a Twilio account and a programmable phone number, you have the basic tools you need to make a phone call.
You could use Twilio's HTTP API to make your phone calls, but we'll make things even more simple by using Twilio's official Python helper library. Let's install that next.
If you’ve gone through one of our Python quickstarts already and have Python and the Twilio Python helper library installed, you can skip this step and get straight to making your first phone call.
To make your first phone call with Twilio, you’ll need to have Python and the Twilio Python helper library installed..
Twilio’s Python SDK supports both Python 2 and Python 3. You can use either version for your projects, but we recommend using Python 3 for this quickstart and future projects with Twilio unless there are specific libraries your project needs which are only compatible with Python 2.
The easiest way to install the library is using pip. Just run this in the terminal:
pip install twilio
If you get the error
pip: command not found, you can use
easy_install to install the Twilio helper library by running this in your terminal:
easy_install twilio
For a manual installation, you can download the source code (ZIP) for twilio-python and then install the library by running:
python setup.py install
in the folder containing the twilio-python library.
And with that, it's time to write some code.
Now that we have Python and
twilio-python installed, we can make an outgoing phone call with a single API request from the Twilio phone number we just purchased. Create a new file called
make_call.py.
Swap the placeholder values for
account_sid and
auth_token eyeball icon:
Open
make_call.py and replace the values for
account_sid and
auth_token with your unique values.
Please note: it's okay to hardcode your credentials when getting started, but you should use environment variables to keep them secret before deploying to production. Check out how to set environment variables for more information.:
python make_call.py Flask server up and running.
To handle incoming phone calls we'll need a lightweight web application to accept incoming HTTP requests from Twilio. We’ll use Flask for this quickstart, but you can use your choice of web framework to make and receive phone calls from your applications.
For instructions on setting up Flask on Windows, check out this guide.
To install Flask and set up our development environment, we’ll need two tools: pip to install Flask and virtualenv to create a unique sandbox for this project. If you already have these tools installed, you can skip to the next section.
Pip comes pre-packaged with Python 3.4+, so if you’re on a recent version of Python, you don’t need to install anything new. If you’re on an earlier version, never fear: pip is included in virtualenv. So let’s install virtualenv!
If you’re using Python 2.4, run the following command in your terminal:
easy_install virtualenv
If you’re using Python 2.5-2.7, run the following command in your terminal, specifying your version number:
easy_install-2.7 virtualenv
Replace the 2.7 with 2.5 or 2.6 if you have that version installed.
To install virtualenv with Python 3.4+:
# If you get 'permission denied' errors try running "sudo python" instead of "python" pip install virtualenv
If you get any errors in this step, check out these tips for debugging.
Once you have virtualenv installed, use your terminal to navigate to the directory you’re using for this quickstart and create a virtual environment:
cd Documents/my_quickstart_folder virtualenv --no-site-packages .
Now, activate the virtual environment:
source bin/activate
You can verify that your virtualenv is running by looking at your terminal: you should see the name of your enclosing directory. It will look something like this:
(my_quickstart_folder)USER:~ user$
To learn more about virtualenv or create a custom environment path, see this thorough guide.
Now we’re ready to install Flask. Create a file called
requirements.txt and add the following lines to it:
Flask>=0.12 twilio~=6.0.0
Then install both of these packages with pip in your terminal:
pip install -r requirements.txt
First, make sure your virtualenv is activated:
cd Documents/my_quickstart_folder source bin/activate # On Windows, use .\bin\activate.bat
Then, create and open a file called
answer_phone.py and add these lines:
from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run()
$ python app.py * Running on (Press CTRL+C to quit)
Now it's time to try running it. In your terminal, type:
python answer_phone.py
You should see:
$ python answer_phone.py * Running on
Navigate to in your browser. You should see a "Hello World!" message. You’re ready to create your first Twilio messaging app!
If you encountered any issues or want instructions on setting up your environment with an older Python version (<3.4), check out our full guide to setting up a local Python dev environment.
We're about to enhance our small Flask application to accept incoming phone calls. But before we do that, we need to make sure Twilio can talk to our local development environment.
Most Twilio services use webhooks to communicate with your application. When Twilio receives a phone call, for example, it reaches out to a URL in your application for instructions on how to handle the call.
When you’re working on your Flask application in your development environment, your app is only reachable by other programs on your computer and Twilio won’t be able to talk to it. We need to solve this problem by making your application accessible over the internet.
While there are a lot of ways to do this, like deploying your application to Heroku or AWS, you'll probably want a less laborious way to test your Twilio application. For a lightweight way to make your app available on the internet, we recommend a tool called ngrok. Once started, ngrok provides a unique URL on the ngrok.io domain which forwards incoming requests to your local development environment. downloaded, start that Hello World application we made previously:
python answer_phone.py
Your local application must be running locally for ngrok to do its magic.
Then open a new terminal tab or window and start ngrok with this command:
./ngrok http 5000
If your local server is running on a different port, replace 5000 with the correct port number.
You should see output similar to this:
Copy your public URL from this output and paste it into your browser. You should see your Flask application's "Hello World!" message. Flask app reply to answer the phone call and say a short message to the caller. Open up
answer_phone.py again and update the code to look like this code sample:)
Save the file and restart your app with
python answer_phone.py
You should now be able to open a web browser to. If you view the page source code, you should see the following text:
<?xml version="1.0" encoding="UTF-8"?> <Response> <Say voice="alice".
For Twilio to know where to look, you need to configure your Twilio phone number to call your webhook URL whenever a new message comes in.
Save your changes - you're ready!
As long as your localhost and the ngrok servers are up and running, we’re ready for the fun part - testing our new Flask application!
Make a phone call from your mobile phone to your Twilio phone number. You should see an HTTP request in your ngrok console. Your Flask app will process the incoming request and respond with your TwiML. Then you'll hear your message once the call connects.
Now you know the basics of making and responding to phone calls with Python.
Our Flask app here only used the <Say> TwiML verb to read a message to the caller using text to speech, but you can do much more with different TwiML verbs like <Record>, <Gather>, and <Conference>.
We can't wait to see what you build!
We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.
#)
from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run()
$ python app.py * Running on (Press CTRL+C to quit)) | https://www.twilio.com/docs/quickstart/python/programmable-voice | CC-MAIN-2018-09 | en | refinedweb |
With drawing to an end.
This Article Covers
Jobs
I don't know about you, but my Visual Basic experience starts with VB 3.0. I'd used some older "non-visual" BASIC dialects before that, so it wasn't a huge leap for me to this new world of GUI programming. With a few months of study time, it was literally possible to know everything that there was to know about VB at that point. All that "keeping up" required was tracking the third-party custom controls market to watch for new and innovative chunks of functionality that could be slapped into VB, alas, was over a decade ago. In the interim, Microsoft has hired more developers than you can shake a good-sized stick of RAM at, and they've all been programming away on increasingly complex iterations of VB (and, of course, other things). Every year, there are more fabulous products, more things added to VB's core syntax, more add-on libraries, more programmable extensions...more, more, more. Meanwhile, there's still only one of me. Something has got to give.
And if I'm having a hard time keeping up, I can only imagine what it's like for someone who hasn't been following along for over a decade. Not only is it no longer possible for any one developer to know everything about VB and related development topics, it's difficult to even get a clear enough picture to know where to start.
One reason Microsoft throws the annual Professional Developers Conference is to try to hand out a roadmap of important technologies for the years to come, but this year that may have backfired. A lot of us are just starting to feel recovered from the long Visual Studio 2005 beta cycle, ready to catch our breaths and actually do something with released software for a change - only to be hit with a fire hose of new projects and announcements at this year's PDC. Atlas, LINQ, Sparkle, Office 12...the list goes on from there.
That's not to mention new details on things we already knew about, from Avalon and Indigo (sorry, Windows Presentation Foundation and Windows Communications Foundation) to Team Foundation Server and Windows Vista.
I am becoming increasingly convinced that the age when anyone could seriously say "I am a VB developer" and convincingly present themselves as a generalist, able to work in any corner of the VB technology universe, is drawing to an end. We're now at a point where there's a core of essential VB knowledge - the basic syntax of VB .NET, together with a knowledge of the core .NET Framework namespaces - and beyond that, one simply must specialize. You can either specialize accidentally, by working on a particular project and so honing your skills in whatever area that project happens to call for, or by design, by picking what you hope will be a hot area and really learning the technology. But one way or another, you'll have to choose some subset of the VB world to have a deep knowledge of. You can't, in 2005, have it all.
The question, of course, is what to specialize in. To a certain extent, you can just pick what most interests you and drill into it, because nearly any corner of the VB world these days offers enough depth for you to be an expert. For example, there's plenty of room to specialize in using VB with Visio - knowing the ins and outs of the Visio object model and being able to customize Visio for client needs would be a very hot ticket in some quarters. On a more general level, though, I think if I were looking for a near-term specialty, I'd look in one of four areas:
Had I the luxury of thinking in the longer term, I'd probably look at how to hook my VB skills in with Office 12, or with the whole new world of visual design coming for Windows Vista. But those areas are still pretty darned fuzzy as far as action items go, even if the hype machine is already in motion. Of course, I could be wildly misreading the markets, which is why you need to keep an eye on the general trends. Even specialists need to keep a fallback position handy.
Mike Gunderloy is an independent developer and author working in eastern Washington state. His recent books include Painless Project Management with FogBugz (Apress) andCoder to Developer(Sybex). You can read more of Mike's work at his Larkware Web site, or contact him at MikeG1@larkfarm.com.
Start the conversation | http://searchwindevelopment.techtarget.com/news/1128395/With-VB-growing-its-time-to-specialize | CC-MAIN-2018-09 | en | refinedweb |
Synchronize filesystem updates
#include <unistd.h> void sync( void );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The sync() function queues all the modified block buffers for writing, and returns; it doesn't wait for the actual I/O to take place. Use this function—or fsync() for a single file—to ensure consistency of the entire on-disk filesystem with the contents of the in-memory buffer cache. | http://www.qnx.com/developers/docs/6.6.0_anm11_wf10/com.qnx.doc.neutrino.lib_ref/topic/s/sync.html | CC-MAIN-2018-09 | en | refinedweb |
Hello, all.
What is the purpose of using the @Exact annotation like below (MyBean being an interface and SpecifcMyBean one implementation of it):
public class ToBeInjected { @Inject @Exact(SpecificMyBean.class) private MyBean myBean; }
instead of using the type to define the bean?
public class ToBeInjected { @Inject private SpecificMyBean myBean; }
I see the point and it makes sense. Thank you for your answer! | https://developer.jboss.org/thread/178760 | CC-MAIN-2018-09 | en | refinedweb |
C++ Programming/STL
Contents
- 1 Standard Template Library (STL)
- 1.1 History
- 1.2 Containers
- 1.3 Iterators
- 1.4 Functors
- 1.5 Algorithms
- 1.6 Allocators
Standard Template Library (STL)[edit]
The Standard Template Library (STL), part of the C++ Standard Library, offers collections of algorithms, containers, iterators, and other fundamental components, implemented as templates, classes, and functions essential to extend functionality and standardization to C++. STL main focus is to provide improvements implementation standardization with emphasis in performance and correctness.
Instead of wondering if your array would ever need to hold 257 records or having nightmares of string buffer overflows, you can enjoy vector and string that automatically extend to contain more records or characters. For example, vector is just like an array, except that vector's size can expand to hold more cells or shrink when fewer will suffice. One must keep in mind that the STL does not conflict with OOP but in itself is not object oriented; In particular it makes no use of runtime polymorphism (i.e., has no virtual functions).
The true power of the STL lies not in its container classes, but in the fact that it is a framework, combining algorithms with data structures using indirection through iterators to allow generic implementations of higher order algorithms to work efficiently on varied forms of data. To give a simple example, the same std::copy function can be used to copy elements from one array to another, or to copy the bytes of a file, or to copy the whitespace-separated words in "text like this" into a container such as std::vector<std::string>.
// std::copy from array a to array b int a[10] = { 3,1,4,1,5,9,2,6,5,4 }; int b[10]; std::copy(&a[0], &a[9], b); // std::copy from input stream a to an arbitrary OutputIterator template <typename OutputIterator> void f(std::istream &a, OutputIterator destination) { std::copy(std::istreambuf_iterator<char>(a), std::istreambuf_iterator<char>(), destination); } // std::copy from a buffer containing text, inserting items in // order at the back of the container called words. std::istringstream buffer("text like this"); std::vector<std::string> words; std::copy(std::istream_iterator<std::string>(buffer), std::istream_iterator<std::string>(), std::back_inserter(words)); assert(words[0] == "text"); assert(words[1] == "like"); assert(words[2] == "this");
History[edit]
The C++ Standard Library incorporated part of the STL (published as a software library by SGI/Hewlett-Packard Company). The primary implementer of the C++ Standard Template Library was Alexander Stepanov.
Today we call STL to what was adopted into the C++ Standard. The ISO C++ does not specify header content, and allows implementation of the STL either in the headers, or in a true library.
Compilers will already have one implementation included as part of the C++ Standard (i.e., MS Visual Studio uses the Dinkum STL). All implementations will have to comply to the standard's requirements regarding functionality and behavior, but consistency of programs across all major hardware implementations, operating systems, and compilers will also depends on the portability of the STL implementation. They may also offer extended features or be optimized to distinct setups.
There are many different implementations of the STL, all based on the language standard but nevertheless differing from each other, making it transparent for the programmer, enabling specialization and rapid evolution of the code base. Several open source implementations are available, which can be useful to consult.
- List of STL implementations.
- libstdc++ from gnu (was part of libg++)
- SGI STL library () free STL implementation.
- Rogue Wave standard library (HP, SGI, SunSoft, Siemens-Nixdorf) / Apache C++ Standard Library (STDCXX)
- Dinkum STL library by P.J. Plauger () commercial STL implementation widely used, since it was licensed in is co-maintained by Microsoft and it is the STL implementation that ships with Visual Studio.
- Apache C++ Standard Library ( ) (open source)
- STLport STL library () open source and highly cross-platform implementation based on the SGI implementation.
Containers[edit]
The containers we will discuss in this section of the book are part of the standard namespace (std::). They all originated in the original SGI implementation of the STL.
Sequence Containers[edit]
- Sequences - easier than arrays
Sequences are similar to C arrays, but they are easier to use. Vector is usually the first sequence to be learned. Other sequences, list and double-ended queues, are similar to vector but more efficient in some special cases. (Their behavior is also different in important ways concerning validity of iterators when the container is changed; iterator validity is an important, though somewhat advanced, concept when using containers in C++.)
- vector - "an easy-to-use array"
- list - in effect, a doubly-linked list
- deque - double-ended queue (properly pronounced "deck", often mispronounced as "dee-queue")
vector[edit]
The vector is a template class in itself, it is a Sequence Container and allows you to easily create a dynamic array of elements (one type per instance) of almost any data-type or object within a programs when using it. The vector class handles most of the memory management for you.
Since a vector contain contiguous elements it is an ideal choice to replace the old C style array, in a situation where you need to store data, and ideal in a situation where you need to store dynamic data as an array that changes in size during the program's execution (old C style arrays can't do it). However, vectors do incur a very small overhead compared to static arrays (depending on the quality of your compiler), and cannot be initialized through an initialization list.
Accessing members of a vector or appending elements takes a fixed amount of time, no matter how large the vector is, whereas locating a specific value in a vector element or inserting elements into the vector takes an amount of time directly proportional to its location in it (size dependent).
- Example
/* David Cary 2009-03-04 quick demo for wikibooks */ #include <iostream> #include <vector> using namespace std; vector<int> pick_vector_with_biggest_fifth_element(vector<int> left,vector<int> right) { if(left[5] < right[5]) { return( right ); } // else return left ; } int* pick_array_with_biggest_fifth_element(int * left array_demo(void) { cout << "array demo" << endl; int left[7]; int right[7]; left[5] = 7; right[5] = 8; cout << left[5] << endl; cout << right[5] << endl; int * biggest = pick_array_with_biggest_fifth_element( left, right ); cout << biggest[5] << endl; return 0; } int main(void) { vector_demo(); array_demo(); }
- Member Functions
The
vector class models the Container concept, which means it has
begin(),
end(),
size(),
max_size(),
empty(), and
swap() methods.
- informative
vector::front- Returns reference to first element of vector.
vector::back- Returns reference to last element of vector.
vector::size- Returns number of elements in the vector.
vector::empty- Returns true if vector has no elements.
- standard operations
vector::insert- Inserts elements into a vector (single & range), shifts later elements up. Inefficient.
vector::push_back- Appends (inserts) an element to the end of a vector, allocating memory for it if necessary. Amortized O(1) time.
vector::erase- Deletes elements from a vector (single & range), shifts later elements down. Inefficient.
vector::pop_back- Erases the last element of the vector, (possibly reducing capacity - usually it isn't reduced, but this depends on particular STL implementation). Amortized O(1) time.
vector::clear- Erases all of the elements. Note however that if the data elements are pointers to memory that was created dynamically (e.g., the new operator was used), the memory will not be freed.
- allocation/size modification
vector::assign- Used to delete a origin vector and copies the specified elements to an empty target vector.
vector::reserve- Changes capacity (allocates more memory) of vector, if needed. In many STL implementations capacity can only grow, and is never reduced.
vector::capacity- Returns current capacity (allocated memory) of vector.
vector::resize- Changes the vector size.
- iteration
vector::begin- Returns an iterator to start traversal of the vector.
vector::end- Returns an iterator that points just beyond the end of the vector.
vector::at- Returns a reference to the data element at the specified location in the vector, with bounds checking.
vector<int> v; for (vector<int>::iterator it = v.begin(); it!=v.end(); ++it/* increment operand is used to move to next element*/) { cout << *it << endl; }
vector::Iterators[edit]
std::vector<T> provides Random Access Iterators; as with all containers, the primary access to iterators is via begin() and end() member functions. These are overloaded for const- and non-const containers, returning iterators of types std::vector<T>::const_iterator and std::vector<T>::iterator respectively.
vector examples[edit]
/* Vector sort example */ #include <iostream> #include <vector> int main() { using namespace std; cout << "Sorting STL vector, \"the easier array\"... " << endl; cout << "Enter numbers, one per line. Press ctrl-D to quit." << endl; vector<int> vec; int tmp; while (cin>>tmp) { vec.push_back(tmp); } cout << "Sorted: " << endl; sort(vec.begin(), vec.end()); int i = 0; for (i=0; i<vec.size(); i++) { cout << vec[i] << endl;; } return 0; }
The call to sort above actually calls an instantiation of the function template std::sort, which will work on any half-open range specified by two random access iterators.
If you like to make the code above more "STLish" you can write this program in the following way:
#include <iostream> #include <vector> #include <algorithm> #include <iterator> int main() { using namespace std; cout << "Sorting STL vector, \"the easier array\"... " << endl; cout << "Enter numbers, one per line. Press ctrl-D to quit." << endl; istream_iterator<int> first(cin); istream_iterator<int> last; vector<int> vec(first, last); sort(vec.begin(), vec.end()); cout << "Sorted: " << endl; copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, "\n")); return 0; }
Linked lists[edit]
The STL provides a class template called list (part of the standard namespace (std::)) which implements a non-intrusive doubly-linked list. Linked lists can insert or remove elements in the middle in constant time, but do not have random access. One useful feature of std::list is that references, pointers and iterators to items inserted into a list remain valid so long as that item remains in the list.
list examples[edit]
/* List example - insertion in a list */ #include <iostream> #include <algorithm> #include <iterator> #include <list> void print_list(std::list<int> const& a_filled_list) { using namespace std; ostream_iterator<int> out(cout, " "); copy(a_filled_list.begin(), a_filled_list.end(), out); } int main() { std::list<int> my_list; my_list.push_back(1); my_list.push_back(10); print_list(my_list); //print : 1 10 std::cout << std::endl; my_list.push_front(45); print_list(my_list); //print : 45 1 10 return 0; }
Associative Containers (key and value)[edit]
This type of container point to each element in the container with a key value, thus simplifying searching containers for the programmer. Instead of iterating through an array or vector element by element to find a specific one, you can simply ask for people["tero"]. Just like vectors and other containers, associative containers can expand to hold any number of elements.
Maps and Multimaps[edit]
map and multimap are associative containers that manage key/value pairs as elements as seen above. The elements of each container will sort automatically using the actual key for sorting criterion. The difference between the two is that maps do not allow duplicates, whereas, multimaps does.
- map - unique keys
- multimap - same key can be used many times
- set - unique key is the value
- multiset - key is the value, same key can be used many times
/* Map example - character distribution */ #include <iostream> #include <map> #include <string> #include <cctype> using namespace std; int main() { /* Character counts are stored in a map, so that * character is the key. * Count of char a is chars['a']. */ map<char, long> chars; cout << "chardist - Count character distributions" << endl; cout << "Type some text. Press ctrl-D to quit." << endl; char c; while (cin.get(c)) { // Upper A and lower a are considered the same c=tolower(static_cast<unsigned char>(c)); chars[c]=chars[c]+1; // Could be written as ++chars[c]; } cout << "Character distribution: " << endl; string alphabet("abcdefghijklmnopqrstuvwxyz"); for (string::iterator letter_index=alphabet.begin(); letter_index != alphabet.end(); letter_index++) { if (chars[*letter_index] != 0) { cout << char(toupper(*letter_index)) << ":" << chars[*letter_index] << "\t" << endl; } } return 0; }
Container Adapters[edit]
- stack - last in, first out (LIFO)
- queue - first in, first out (FIFO)
- priority queue
Iterators[edit]
C++'s iterators are one of the foundation of the STL. Iterators exist in languages other than C++, but C++ uses an unusual form of iterators, with pros and cons.
In C++, an iterator is a concept rather than a specific type, they are a generalization of the pointers as an abstraction for the use of containers. Iterators are further divided based on properties such as traversal properties.
The basic idea of an iterator is to provide a way to navigate over some collection of objects concept.
Some (overlapping) categories of iterators are:
- Singular iterators
- Invalid iterators
- Random access iterators
- Bidirectional iterators
- Forward iterators
- Input iterators
- Output iterators
- Mutable iterators
A pair of iterators [begin, end) is used to define a half open range, which includes the element identified from begin to end, except for the element identified by end. As a special case, the half open range [x, x) is empty, for any valid iterator x.
The most primitive examples of iterators in C++ (and likely the inspiration for their syntax) are the built-in pointers, which are commonly used to iterate over elements within arrays.
Iteration over a Container[edit]
Accessing (but not modifying) each element of a container group of type C<T> using an iterator.
for ( typename C<T>::const_iterator iter = group.begin(); iter != group.end(); ++iter ) { T const &element = *iter; // access element here }
Note the usage of typename. It informs the compiler that 'const_iterator' is a type as opposed to a static member variable. (It is only necessary inside templated code, and indeed in C++98 is invalid in regular, non-template, code. This may change in the next revision of the C++ standard so that the typename above is always permitted.)
Modifying each element of a container group of type C<T> using an iterator.
for ( typename C<T>::iterator iter = group.begin(); iter != group.end(); ++iter ) { T &element = *iter; // modify element here }
When modifying the container itself while iterating over it, some containers (such as vector) require care that the iterator doesn't become invalidated, and end up pointing to an invalid element. For example, instead of:
for (i = v.begin(); i != v.end(); ++i) { ... if (erase_required) { v.erase(i); } }
Do:
for (i = v.begin(); i != v.end(); ) { ... if (erase_required) { i = v.erase(i); } else { ++i; } }
The erase() member function returns the next valid iterator, or end(), thus ending the loop. Note that ++i is not executed when erase() has been called on an element.
Functors[edit]
A functor or function object, is an object that has an
operator (). The importance of functors is that they can be used in many contexts in which C++ functions can be used, whilst also having the ability to maintain state information. Next to iterators, functors are one of the most fundamental ideas exploited by the STL.
The STL provides a number of pre-built functor classes; std::less, for example, is often used to specify a default comparison function for algorithms that need to determine which of two objects comes "before" the other.
#include <vector> #include <algorithm> #include <iostream> // Define the Functor for AccumulateSquareValues template<typename T> struct AccumulateSquareValues { AccumulateSquareValues() : sumOfSquares() { } void operator()(const T& value) { sumOfSquares += value*value; } T Result() const { return sumOfSquares; } T sumOfSquares; }; std::vector<int> intVec; intVec.reserve(10); for( int idx = 0; idx < 10; ++idx ) { intVec.push_back(idx); } AccumulateSquareValues<int> sumOfSquare = std::for_each(intVec.begin(), intVec.end(), AccumulateSquareValues<int>() ); std::cout << "The sum of squares for 1-10 is " << sumOfSquare.Result() << std::endl; // note: this problem can be solved in another, more clear way: // int sum_of_squares = std::inner_product(intVec.begin(), intVec.end(), intVec.begin(), 0);
Algorithms[edit]
The STL also provides several useful algorithms, in the form of template functions, that are provided to, with the help of the iterator concept, manipulate the STL containers (or derivations).
The STL algorithms aren't restricted to STL containers, for instance:
#include <algorithm> int array[10] = { 2,3,4,5,6,7,1,9,8,0 }; int* begin = &array[0]; int* end = &array[0] + 10; std::sort(begin, end);// the sort algorithm will work on a C style array
- The _if suffix
- The _copy suffix
- Non-modifying algorithms
- Modifying algorithms
- Removing algorithms
- Mutating algorithms
- Sorting algorithms
- Sorted range algorithms
- Numeric algorithms
Permutations[edit]
[edit]
sort[edit]
stable_sort[edit]
partial_sort[edit]
Minimum and maximum[edit]
The standard library provides function templates
min and
max, which return the minimum and maximum of their two arguments respectively. Each has an overload available that allows you to customize the way the values are compared.
template<class T> const T& min(const T& a, const T& b); template<class T, class Compare> const T& min(const T& a, const T& b, Compare c); template<class T> const T& max(const T& a, const T& b); template<class T, class Compare> const T& max(const T& a, const T& b, Compare c);
An example of how to use the Compare type parameter :
#include <iostream> #include <algorithm> #include <string> class Account { private : std::string owner_name; int credit; int potential_credit_transfer; public : Account(){} Account(std::string name, int initial_credit, int initial_credit_transfer) : owner_name(name), credit(initial_credit), potential_credit_transfer(initial_credit_transfer) {} bool operator<(Account const& account) const { return credit < account.credit; } int potential_credit() const { return credit + potential_credit_transfer; } std::string const& owner() const { return owner_name; } }; struct CompareAccountCredit { bool operator()(Account const& account1, Account const& account2) const { return account1 < account2; } }; struct CompareAccountPotentialCredit { bool operator()(Account const& account1, Account const& account2) const { return account1.potential_credit() < account2.potential_credit(); } }; int main() { Account account1("Dennis Ritchie", 1000, 250), account2("Steeve Jobs", 500, 10000), result_comparison; result_comparison = std::min(account1, account2, CompareAccountCredit()); std::cout << "min credit of account is : " + result_comparison.owner() << std::endl; result_comparison = std::min(account1, account2, CompareAccountPotentialCredit()); std::cout << "min potential credit of account is : " + result_comparison.owner() << std::endl; return 0; }
Allocators[edit]
Allocators are used by the Standard C++ Library (and particularly by the STL) to allow parameterization of memory allocation strategies.
The subject of allocators is somewhat obscure, and can safely be ignored by most application software developers. All standard library constructs that allow for specification of an allocator have a default allocator which is used if none is given by the user.
Custom allocators can be useful if the memory use of a piece of code is unusual in a way that leads to performance problems if used with the general-purpose default allocator. There are also other cases in which the default allocator is inappropriate, such as when using standard containers within an implementation of replacements for global operators new and delete. | https://en.wikibooks.org/wiki/C%2B%2B_Programming/STL | CC-MAIN-2018-09 | en | refinedweb |
{
public boolean equals(C that) { return id(this) == id(that); }
}
But in order for table.get(c) to work you need to make the
equals method take an Object as the argument, not a
C:
public class C {
public boolean equals(Object that) {
return (that instanceof C) && id(this) == id((C)that);
}
}
Why? The code for Hashtable.get looks something like this:
public class Hashtable {
public Object get(Object key) {
Object entry;
...
if (entry.equals(key)) ...
}
}:
public class C {
public boolean equals(Object that) {
return (this == that)
|| ((that instanceof C) && this.equals((C)that));
}
public boolean equals(C that) {
return id(this) == id(that); // Or whatever is appropriate for class C
}
}
public class C2 extends C {
int newField = 0;
public boolean equals(Object that) {
if (this == that) return true;
else if (!(that instanceof C2)) return false;
else return this.newField == ((C2)that).newField) && super.equals(that);
}
}.
public class LinkedList {
Object contents;
LinkedList next = null;
public boolean equals(Object that) {
return (this == that)
|| ((that instanceof LinkedList) && this.equals((LinkedList)that));
}
public boolean equals(LinkedList that) { // Buggy!
return Util.equals(this.contents, that.contents) &&
Util.equals(this.next, that.next);
}
}
Here I have assumed there is a Util class with:
public static boolean equals(Object x, Object y) {
return (x == y) || (x != null && x.equals.)
This tip is reprinted on JavaFAQ.nu by by courtesy of
Peter Norvig I am
thankful for his important contributions to my site - 21 Infrequently Answered
Java Questions. Alexandre Patchine
RSS feed Java FAQ News | http://javafaq.nu/java-article893.html | CC-MAIN-2018-09 | en | refinedweb |
AWS Blog mass-produced compute power, the widespread availability of IP connectivity, and the ease with which large amounts of information can be distilled into intelligence using any number of big data tools and techniques:
- Mass-produced compute power means that it is possible to crank out powerful processors that consume modest amounts of power, occupy very little space, and cost very little. These attributes allow the processors to be unobtrusively embedded in devices of all shapes and sizes.
- Widespread IP connectivity (wired or wireless) lets these processors talk to each other and to the cloud. While this connectivity is fairly widespread, it is definitely not ubiquitous.
- Big data allows us to make sense of the information measured, observed, or collected, by the processors running in these devices.
We could also add advances in battery & sensor technology to the list of enabling technologies for the Internet of Things. Before too long, factory floors, vehicles, health care systems, household appliances, and much more will become connected “things.” Two good introductory posts on the topic are 20 Real World Problems Solved by IoT and Smart IoT: IoT as a Human Agent, Human Extension, and Human Complement. My friend Sudha Jamthe has also written on the topic; her book IoT Disruptions focuses on new jobs and careers that will come about as IoT becomes more common.
Taking all of these trends as givens, it should not come as a surprise that we are working to make sure that AWS is well-equipped to support many different types of IoT devices and applications. Although I have described things as connected devices, they can also take the form of apps running on mobile devices.
New AWS IoT
Today we are launching AWS IoT (Beta).
This new managed cloud service provides the infrastructure that allows connected cars, factory floors, aircraft engines, sensor grids, and the like (AWS IoT refers to them as “things”) to easily and securely interact with cloud services and with other devices, all at world-scale. The connection to the cloud is fast and lightweight (MQTT or REST), making it a great fit for devices that have limited memory, processing power, or battery life.
Let’s take a look at the components that make up AWS IoT:
-.
AWS IoT lets billions of things keep responsive connections to the cloud, and lets cloud applications interact with things (works in device shadows, rules engine, and the real-time functionality). It receives messages from things and filters, records, transforms, augments, or routes them to other parts of AWS or to your own code.
Getting Started with AWS IoT
We have been working with a large group of IoT Partners to create AWS-powered starter kits:
Beaglebone Green and Grove IoT Starter Kit Powered by AWS.
- Dragonboard IoT Starter Kit Powered by AWS.
- Intel Edison and Grove IoT Starter Kit Powered by AWS.
- Marvel EZ-Connect MW300 IoT Starter Kit Powered by AWS.
- MediaTek Linkit One IoT Starter Kit Powered by AWS.
- Microchip IoT Starter Kit Powered by AWS.
- Renasas IoT Starter Kit Powered by AWS.
- Seeeduino Cloud and Grove IoT Starter Kit Powered by AWS.
- TI LaunchPad IoT Starter Kit Powered by AWS.
- WICED B4343W IoT Starter Kit Powered by Broadcom and AWS.
Once you have obtained a kit and connected it to something interesting, you are ready to start building your first IoT application using AWS IoT. You will make use of several different SDKs during this process:
- The Device SDK (C, JavaScript, and Arduino Yún) runs on the device.
- The AWS SDKs give you access to AWS from your web or mobile app.
The AWS IoT Console will help you get started. With a few clicks you can create your first thing, and then download the SDK, security credentials, and sample code you will need to connect a device to AWS IoT.
You can also build AWS IoT applications that communicate with an Amazon Echo via the Alexa Skills Kit. AWS IoT can trigger an Alexa Skill via a Lambda function and Alexa Skills can interact with thing shadows. Alexa Skills can also take advantage of AWS IoT’s bidirectional messaging capability (which traverses NAT and firewalls found in home networks) to wake devices with commands from the cloud. Manufacturers can use thing shadows to store responses to application-specific messages.
AWS IoT in the Console
The Console includes an AWS IoT tutorial to get you started:
It also provides complete details on each thing, including the thing’s API endpoint, MQTT topic, and the contents of its shadow:
AWS IoT Topics, Messages, and Rules
All of the infrasructure that I described can be seen as a support system for the message and rule system that forms the heart of AWS IoT. Things disclose their state by publishing messages to named topics. Publishing a message to a topic will create the topic if necessary; you don’t have to create it in advance. The topic namespace is hierarchical (“myfactories/seattle/sensors/door”)
Rules use a SQL-like
SELECT statement to filter messages. In the IoT Rules Engine, the
FROM clause references an MQTT topic and the
WHERE clause references JSON properties in the message. When a rule matches a message, it can invoke one or more of the following actions:
- Insert, update, or query a DynamoDB table.
- Invoke a Lambda function.
- Write to an S3 bucket.
- Publish to an SNS topic or endpoint.
- Publish to an SQS queue.
- Publish to a Amazon Kinesis stream.
- Publish to an Amazon Kinesis Firehose.
- Republish to another topic.
The SELECT statement can use all (*) or specifically chosen fields of the message in the invocation.
The endpoints above can be used to reach the rest of AWS. For example, you can reach Amazon Redshift via Kinesis, and external endpoints via Lambda, SNS, or Kinesis.
Thing Shadows also participate in the message system. Shadows respond to HTTP GET requests with JSON documents (the documents are also accessible via MQTT for environments that don’t support HTTP). Each document contains the thing state, its metadata, and a version number for the state. Each piece of state information is stored in both “reported” (what the device last said), and “desired” (what the application wants it to be). Each shadow accepts changes to the desired state (HTTP) post, and publishes “delta” and “accepted” messages to topics associated with the thing shadow. The device listens on these topics and changes its state accordingly.
IoT at re:Invent
If you are at re:Invent, be sure to check out our Mobile Developer & IoT track. Here are some of the sessions we have in store:
- MBL203 – From Drones to Cars: Connecting the Devices in Motion to the Cloud.
- MBL204 -Connecting the Unconnected – State of the Union – Internet of Things Powered by AWS.
- MBL303 -Build Mobile Apps for IoT Devices and IoT Apps for Mobile Devices.
- MBL305 – You Have Date from the Devices, Now What? Getting Value of the IoT.
- WRK202 – Build a Scalable Mobile App on Serverless, Event-Triggered, Back-End Logic.
More to Come
There’s a lot more to talk about and I have barely scratched the surface with this introductory blog post. Once I recover from AWS re:Invent, I will retire to my home lab and cook up a thing or two of my own and share the project with you. Stay tuned!
PS – Check out the AWS IoT Mega Contest! | https://aws.amazon.com/blogs/aws/aws-iot-cloud-services-for-connected-devices/ | CC-MAIN-2017-09 | en | refinedweb |
Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.
public class Car { class Engine { { drive(); } } public static void main(String [] args) { new Car().go(); } void go() { new Engine(); } void drive() { System.out.println("hi"); } }
class Engine { { Car d = new Car(); d.drive(); } }
If you are experiencing a similar issue, please ask a related question
Join the community of 500,000 technology professionals and ask your questions.
Connect with top rated Experts
9 Experts available now in Live! | https://www.experts-exchange.com/questions/26901889/Inner-Class-in-Java.html | CC-MAIN-2017-09 | en | refinedweb |
I think it's a simple syntax error, but I can't seem to fix it.
Thx for the help! ^^Thx for the help! ^^Code:#include <iostream> using namespace std; class Town { public: Town(string Name): name(Name) {} //constructor protected: string name; }; void cho_destin(Town& towns[], int& location) //function that causes ERROR {} Town towns[6] = {Town("Bronx"), Town("Ghetto"), Town("Central Park"), Town("Manhattan"), Town("Coney Island"), Town("Brooklyn")}; int location = -1; //location ( -1 is starting point) int main() { cho_destin(towns[6], location); //prompts user to choose destination system("PAUSE"); return 0; } | https://cboard.cprogramming.com/cplusplus-programming/50260-need-help-again.html | CC-MAIN-2017-09 | en | refinedweb |
Authority
Authority helps you authorize actions in your Ruby app. It's ORM-neutral and has very little fancy syntax; just group your models under one or more Authorizer classes and write plain Ruby methods on them.
Authority will work fine with a standalone app or a single sign-on system. You can check roles in a database or permissions in a YAML file. It doesn't care! What it does do is give you an easy way to organize your logic and handle unauthorized actions.
If you're using it with Rails controllers, it requires that you already have some kind of user object in your application, accessible via a method like
current_user (configurable).
Contents
- Overview
- The flow of Authority
- Installation
- Defining Your Abilities
- Wiring It Together
- The Generic `can?`
- Security Violations & Logging
- Credits
- Contributing
Overview
Using Authority, you have:
- Broad, class-level rules. Examples:
- "Basic users cannot delete any Widget."
- "Only admin users can create Offices."
- Fine-grained, instance-level rules. Examples:
- "Management users can only edit schedules with date ranges in the future."
- "Users can't create playlists more than 20 songs long unless they've paid."
- A clear syntax for permissions-based views. Examples:
link_to 'Edit Widget', edit_widget_path(@widget) if current_user.can_update?(@widget)
link_to 'Keelhaul Scallywag', keelhaul_scallywag_path(@scallywag) if current_user.can_keelhaul?(@scallywag)
- Graceful handling of access violations: by default, it displays a "you can't do that" screen and logs the violation.
- Minimal effort and mess.
Most importantly, you have total flexibility: Authority does not constrain you into using a particular scheme of roles and/or permissions.
Authority lets you control access based on:
- Roles in your app's database (rolify makes this easy)
- Roles in a separate, single-sign-on app
- Users' points (like StackOverflow)
- Time and date
- Weather, stock prices, vowels in the user's name, or anything else you can check with Ruby
All you have to do is define the methods you need on your authorizers. You have all the flexibility of normal Ruby classes.
You make the rules; Authority enforces them.
The flow of Authority
Authority encapsulates all authorization logic in
Authorizer classes. Want to do something with a model? Ask its authorizer.
You can specify a model's authorizer one of two ways:
- specify the class itself:
authorizer = SomeAuthorizer
- specify the class's name:
authorizer_name = 'SomeAuthorizer'(useful if the constant isn't yet loaded)
If you don't specify an authorizer, the model will:
- Look for an authorizer with its name. Eg,
Commentwill look for
CommentAuthorizer.
- If that's not found, it will use
ApplicationAuthorizer.
Models that have the same authorization rules should use the same authorizer. In other words, if you would write the exact same methods on two models to determine who can create them, who can edit them, etc, then they should use the same authorizer.
Some example groupings:
Simplest case Logical groups Most granular ApplicationAuthorizer ApplicationAuthorizer ApplicationAuthorizer + + + | +--------+-------+ +-------------------+-------------------+ | + + + + + | BasicAuthorizer AdminAuthorizer CommentAuthorizer ArticleAuthorizer EditionAuthorizer | + + + + + +-------+-------+ +-+ +------+ | | | + + + + + + + + + Comment Article Edition Comment Article Edition Comment Article Edition
The authorization process generally flows like this:
current_user.can_create?(Article) # You ask this question, and the user + # automatically asks the model... | v Article.creatable_by?(current_user) # The model automatically asks + # its authorizer... | v AdminAuthorizer.creatable_by?(current_user) # *You define this method.* + # If you don't, the inherited one | # calls `default`... v AdminAuthorizer.default(:creatable, current_user) # *You define this method.* # If you don't, it will use the one # inherited from ApplicationAuthorizer. # (Its parent, Authority::Authorizer, # defines the method as `return false`.)
If the answer is
false and the original caller was a controller, this is treated as a
SecurityViolation. If it was a view, maybe you just don't show a link.
The authorization process for instances is different in that it calls the instance's
default method before calling the class
default method. This allows you to define default behaviour that requires access to the model instance to be determined (eg, assume any action on a blog post is allowed if that post is marked 'wiki').
(Diagrams made with AsciiFlow)
Installation
Starting from a clean commit status, add
authority to your Gemfile, then
bundle.
If you're using Rails, run
rails g authority:install. Otherwise, pass a block to
Authority.configure with configuration options somewhere when your application boots up.
Defining Your Abilities
Edit
config/initializers/authority.rb. That file documents all your options, but one of particular interest is
config.abilities, which defines the verbs and corresponding adjectives in your app. The defaults are:
config.abilities = { :create => 'creatable', :read => 'readable', :update => 'updatable', :delete => 'deletable' }
This option determines what methods are added to your users, models and authorizers. If you need to ask
user.can_deactivate?(Satellite) and
@satellite.deactivatable_by?(user), add
:deactivate => 'deactivatable' to the hash.
Wiring It Together
Users
# Whatever class represents a logged-in user in your app class User # Adds `can_create?(resource)`, etc include Authority::UserAbilities ... end
Models
class Article # Adds `creatable_by?(user)`, etc include Authority::Abilities # Without this, 'ArticleAuthorizer' is assumed; # if that doesn't exist, 'ApplicationAuthorizer' self.authorizer_name = 'AdminAuthorizer' ... end
Authorizers
Add your authorizers under
app/authorizers, subclassing the generated
ApplicationAuthorizer.
These are where your actual authorization logic goes. Here's how it works:
- Instance methods answer questions about model instances, like "can this user update this particular widget?" (Within an instance method, you can get the model instance with
resource).
- Any instance method you don't define (for example, if you didn't make a
def deletable_by?(user)) will fall back to the corresponding class method. In other words, if you haven't said whether a user can update this particular widget, we'll decide by checking whether they can update any widget.
- Class methods answer questions about model classes, like "is it ever permissible for this user to update a Widget?"
- Any class method you don't define (for example, if you didn't make a
def self.updatable_by?(user)) will call that authorizer's
defaultmethod.
For example:
# app/authorizers/schedule_authorizer.rb class ScheduleAuthorizer < ApplicationAuthorizer # Class method: can this user at least sometimes create a Schedule? def self.creatable_by?(user) user.manager? end # Instance method: can this user delete this particular schedule? def deletable_by?(user) resource.in_future? && user.manager? && resource.department == user.department end end # undefined; calls `ScheduleAuthorizer.default(:updatable, user)` ScheduleAuthorizer.updatable_by?(user)
As you can see, you can specify different logic for every method on every model, if necessary. On the other extreme, you could simply supply a default method that covers all your use cases.
Passing Options
Any options you pass when checking permissions will be passed right up the chain. One use case for this would be if you needed an associated instance in order to do a class-level check. For example:
# I don't have a comment instance to check, but I need to know # which post the user wants to comment on user.can_create?(Comment, :for => @post)
This would ultimately call
creatable_by? on the designated authorizer with two arguments: the user and
{:for => @post}. If you've defined that method yourself, you'd need to ensure that it accepts the options hash before doing this, or you'd get a "wrong number of arguments" error.
There's nothing special about the hash key
:for; I just think it reads well in this case. You can pass any options that make sense in your case.
If you don't pass options, none will be passed to your authorizer, either.
And you could always handle the case above without options if you don't mind creating an extra model instance:
user.can_create?(Comment.new(:post => @post))
Default Methods
Any class method you don't define on an authorizer will call the
default method on that authorizer. This method is defined on
Authority::Authorizer to simply return false. This is a 'whitelisting' approach; any permission you haven't specified (which falls back to the default method) is considered forbidden.
You can override this method in your
ApplicationAuthorizer and/or per authorizer. For example, you might want one that looks up the user's roles and correlates them with permissions:
# app/authorizers/application_authorizer.rb class ApplicationAuthorizer < Authority::Authorizer # Example call: `default(:creatable, current_user)` def self.default(able, user) has_role_granting?(user, able) || user.admin? end protected def has_role_granting?(user, able) # Does the user have any of the roles which give this permission? (roles_which_grant(able) & user.roles).any? end def roles_which_grant(able) # Look up roles for the current authorizer and `able` ... end end
If your system is uniform enough, this method alone might handle all the logic you need.
Testing Authorizers
One nice thing about putting your authorization logic in authorizers is the ease of testing. Here's a brief example.
# An authorizer shared by several admin-only models describe AdminAuthorizer do before :each do @user = FactoryGirl.build(:user) @admin = FactoryGirl.build(:admin) end describe "class" do it "lets admins update" do expect(AdminAuthorizer).to be_updatable_by(@admin) end it "doesn't let users update" do expect(AdminAuthorizer).not_to be_updatable_by(@user) end end describe "instances" do before :each do # A mock model that uses AdminAuthorizer @admin_resource_instance = mock_admin_resource end it "lets admins delete" do expect(@admin_resource_instance.).to be_deletable_by(@admin) end it "doesn't let users delete" do expect(@admin_resource_instance.).not_to be_deletable_by(@user) end end end
Controllers
If you're using Rails, ActionController support will be loaded in through a Railtie. Otherwise, you'll want to integrate it into your framework yourself. Authority's controller is an excellent starting point.
You can check authorization in your controllers in one of two ways:
authorize_actions_for Llamaprotects multiple controller actions with a
before_filter, which performs a class-level check. If the current user is never allowed to delete a
Llama, they'll never even get to the controller's
destroymethod.
authorize_action_for @llamacan be called inside a single controller action, and performs an instance-level check. If called inside
update, it will check whether the current user is allowed to update this particular
@llamainstance.
If either method finds a user attempting something they're not authorized to do, a Security Violation will result.
How does
authorize_actions_for know to check
deletable_by? before the controller's
destroy action? It checks your configuration. These mappings are configurable globally from the initializer file. Defaults are as follows:
config.controller_action_map = { :index => 'read', # `index` controller action will check `readable_by?` :show => 'read', :new => 'create', # `new` controller action will check `creatable_by?` :create => 'create', # ...etc :edit => 'update', :update => 'update', :destroy => 'delete' }
They are also configurable per controller, as follows:
class LlamasController < ApplicationController # Check class-level authorizations before all actions except :create # Also, to authorize this controller's 'neuter' action, ask whether `current_user.can_update?(Llama)` authorize_actions_for Llama, :except => :create, :actions => {:neuter => :update}, # To authorize this controller's 'breed' action, ask whether `current_user.can_create?(Llama)` # To authorize its 'vaporize' action, ask whether `current_user.can_delete?(Llama)` authority_actions :breed => 'create', :vaporize => 'delete' ... def edit @llama = Llama.find(params[:id]) authorize_action_for(@llama) # Check to see if you're allowed to edit this llama. failure == SecurityViolation end def update @llama = Llama.find(params[:id]) authorize_action_for(@llama) # Check to see if you're allowed to edit this llama. @llama.attributes = params[:llama] # Don't save the attributes before authorizing authorize_action_for(@llama) # Check again, to see if the changes are allowed. if @llama.save? # etc end end
You can pass extra arguments to your authorization checks in these controller helpers:
authorize_actions_for(Llama, args: [{:mamma => true}]
authorize_action_for(@llama, :sporting => @hat_style)
Generally, though, your authorization will depend on some attribute or association of the model instance, so the authorizer can check
@llama.neck_strength and
@llama.owner.nationality, etc, without needing any additional information.
Note that you can also call
authority_actions as many times as you like, so you can specify one mapping at a time if you prefer:
class LlamasController < ApplicationController def breed # some code end :breed => 'create' def vaporize # some code end :vaporize => 'delete' end
If you have a controller that dynamically determines the class it's working with, you can pass the name of a controller instance method to
authorize_actions_for instead of a class, and the class will be looked up when a request is made.
class LlamasController < ApplicationController :llama_class def llama_class # This method can simply return a class... [StandardLlama, LludicrousLlama].sample # ... or an array with a class and some options [OptionLladenLlama, {country: 'Peru'}] end end
If you want to authorize all actions the same way, use the special
all_actions hash key. For instance, if you have nested resources, you might say "you're allowed to do anything you like with an employee if you're allowed to update their employer".
class EmployeesController < ApplicationController :parent_resource, all_actions: :update private def parent_resource Employer.find(params[:employer_id]) end end
Finally, you can enforce that every controller action runs an authorization check using the class method
ensure_authorization_performed, which sets up an
after_filter to raise an exception if it wasn't. Any
only or
except arguments will be passed to
after_filter. You can also use
if or
unless to specify the name of a controller method which determines whether it's necessary.
Since this runs in an
after_filter, it obviously doesn't prevent the action, it just alerts you that no authorization was performed. Therefore, it's most useful in development. An example usage might be:
class ApplicationController < ActionController::Base :except => [:index, :search], :if => :auditing_security?, :unless => :devise_controller? def auditing_security? Rails.env != 'production' end end
If you want a skippable filter, you can roll your own using the instance method, also called
ensure_authorization_performed.
Views
Assuming your user object is available in your views, you can do all kinds of conditional rendering. For example:
link_to 'Edit Widget', edit_widget_path(@widget) if current_user.can_update?(@widget)
If the user isn't allowed to edit widgets, they won't see the link. If they're nosy and try to hit the URL directly, they'll get a Security Violation from the controller.
The Generic
can?
Authority is organized around protecting resources. But occasionally you may need to authorize something that has no particular resource. For that, it provides the generic
can? method. It works like this:
current_user.can?(:view_stats_dashboard) # calls `ApplicationAuthorizer.authorizes_to_view_stats_dashboard?` current_user.can?(:view_stats_dashboard, :on => :tuesdays, :with => :tea) # same, passing the options # application_authorizer.rb class ApplicationAuthorizer < Authority::Authorizer # ... def self.(user, = {}) user.has_role?(:manager) # or whatever end end
Use this very sparingly, and consider it a code smell. Overuse will turn your
ApplicationAuthorizer into a junk drawer of methods. Ask yourself, "am I sure I don't have a resource for this? Should I have one?"
Security Violations & Logging
If you're using Authority's
ActiveController integration or have used it as a template for your own, your application will handle unauthorized requests with
403 Forbidden automatically.
If you use Authority to conditionally render links, users will only see links for actions they're authorized to take. If a user deliberately tries to access a restricted resource (for instance, by typing the URL directly), Authority raises and rescues an
Authority::SecurityViolation.
When it rescues the exception, Authority calls whatever controller method is specified by your
security_violation_handler option, handing it the exception. The default handler is
authority_forbidden, which Authority mixes in to your
ApplicationController. It does the following:
- Renders
public/403.html
- Logs the violation to whatever logger you configured.
You can define your own
authority_forbidden method on
ApplicationController and/or any other controller. For example:
# Send 'em back where they came from with a slap on the wrist def (error) Authority.logger.warn(error.) redirect_to request.referrer.presence || root_path, :alert => 'You are not authorized to complete that action.' end
Your method will be handed the
SecurityViolation, which has a
message method. In case you want to build your own message, it also exposes
user,
action and
resource.
When a user action is successfully authorized, Authority will call
authority_success on your controller.
By default, this does nothing, but you can override it to log the event or do something else.
For instance:
def (user, action, resource) Authority.logger.info "user #{user} was authorized to #{action} resource #{resource}" end
Credits, AKA 'Shout-Outs'
- adamhunter for pairing with me on this gem. The only thing faster than his typing is his brain.
- kevmoo, MP211, and scottmartin for pitching in.
- nkallen for writing a lovely blog post on access control when he worked at Pivotal Labs. I cried sweet tears of joy when I read that a couple of years ago. I was like, "Zee access code, she is so BEEUTY-FUL!"
- jnunemaker for later creating Canable, another inspiration for Authority.
- TMA for employing me and letting me open source some of our code.
Responses, AKA 'Hollaback'
Do you like Authority? Has it cleaned up your code, made you more personable, and taught you the Secret to True Happiness? Awesome! I'd love to get email from you - see my Github profile for the address.
Contributing
How can you contribute? Let me count the ways.
1. Publicity
If you like Authority, tell people! Blog, tweet, comment, or even... [shudder]... talk with people in person. If you feel up to it, I mean. It's OK if you don't.
2. Documentation
Add examples to the wiki to help others solve problems like yours.
3. Issues
Tell me your problems and/or ideas.
4. Code or documentation
- Have an idea. If you don't have one, check the TODO file or grep the project for 'TODO' comments.
- Open an issue so we can talk it over.
- Fork this project
- Create your feature branch (
git checkout -b my-new-feature)
bundle installto get all dependencies
rspec specto run all tests.
- Update/add tests for your changes and code until they pass.
- Commit your changes (
git commit -am 'Added some feature')
- Push to the branch (
git push origin my-new-feature)
- Create a new Pull Request | http://www.rubydoc.info/gems/authority/frames | CC-MAIN-2017-09 | en | refinedweb |
In a statistics book there is an algorithm of generating pseudo-random numbers with uniform distribution [0,1]. It says:
I. Enter an initial variable X positive integer.
II. Multiply X by variable "a", which should be at least 5 digits long.
III. Divide a*X by value p (positive integer).
IV. Take the fraction part of the division as a first pseudo-random number.
V. Make the number from step IV into integer by a necessary multiplication and use it in step II.
VI. Step II-V are repeated to generate more pseudo-random numbers.
Here is what I have:
#include <cstdlib> #include <iostream> using namespace std; int main(int argc, char *argv[]) { int x,a,p; cout << "Enter initial positive integer number: "; cin >> x; cout << "Enter positive integer a: "; cin >> a; cout << "Enter positive integer p: "; cin >> p; for(int i=1; i<=12; i++) { x=(a*x % p); cout << x << endl; } system("PAUSE"); return EXIT_SUCCESS; }
How do I realize steps 4 and 5? I need to obtain random numbers between 0 and 1 and later use them in some other calculations. Please, help. | https://www.daniweb.com/programming/software-development/threads/340563/how-to-generate-random-numbers-without-using-rand-function | CC-MAIN-2017-09 | en | refinedweb |
>>>>> "Rob" == Robert Collins <address@hidden> writes: >> Recently gcc added precompiled header support. This is mostly useful >> for C++, but C might benefit in some cases too. Rob> Are you planning on doing this, or just sketching the design and hoping Rob> for volunteer contributions? I'm hoping someone else will do it :-) Rob> What might be a useful starting point is some manual test cases or Rob> sample rules, to aim for. No problem. libstdc++ is already using it. I've appended some snippets from their Makefile.am. We could probably already get most of this by abusing _PROGRAMS. That's ugly though. I've also appended the section of the gcc manual explaining precompiled headers. Tom pch_input = ${host_builddir}/stdc++.h pch_output_builddir = ${host_builddir}/stdc++.h.gch pch_source = ${glibcxx_srcdir}/include/stdc++.h PCHFLAGS=-Winvalid-pch -Wno-deprecated -x c++-header $(CXXFLAGS) if GLIBCXX_BUILD_PCH pch_build = ${pch_input} pch_install = install-pch else pch_build = pch_install = endif # Build a precompiled C++ include, stdc++.h.gch. ${pch_input}: ${allstamped} ${host_builddir}/c++config.h ${pch_source} touch ${pch_input}; \ if [ ! -d "${pch_output_builddir}" ]; then \ mkdir -p ${pch_output_builddir}; \ fi; \ $(CXX) $(PCHFLAGS) $(AM_CPPFLAGS) ${pch_source} -O0 -g -o ${pch_output_builddir}/O0g; \ $(CXX) $(PCHFLAGS) $(AM_CPPFLAGS) ${pch_source} -O2 -g -o ${pch_output_builddir}/O2g; @node Precompiled Headers @section Using Precompiled Headers @cindex precompiled headers @cindex speed of compilation @option{-x} option to make the driver treat it as a C or C++ header file. You will probably want to use a tool like @command{make} to keep the precompiled header up-to-date when the headers it contains change. A precompiled header file will be searched for when @code{#include} is seen in the compilation. As it searches for the included file (@pxref{Search Path,,Search Path,cpp.info,The C Preprocessor}) the compiler looks for a precompiled header in each directory just before it looks for the include file in that directory. The name searched for is the name specified in the @code{#include} with @samp{.gch} appended. If the precompiled header file can't be used, it is ignored. For instance, if you have @code{#include "all.h"}, and you have @file{all.h.gch} in the same directory as @file{all.h}, then the precompiled header file will be used if possible, and the original header will be used otherwise. Alternatively, you might decide to put the precompiled header file in a directory and use @option{ @code{#error} command. This also works with @option{ @option{ @emph{directory} named like @file: @itemize @item Only one precompiled header can be used in a particular compilation. @item @code{#include}. @item The precompiled header file must be produced for the same language as the current compilation. You can't use a C precompiled header for a C++ compilation. @item The precompiled header file must be produced by the same compiler version and configuration as the current compilation is using. The easiest way to guarantee this is to use the same compiler binary for creating and using precompiled headers. @item Any macros defined before the precompiled header (including with @option{-D}) must either be defined in the same way as when the precompiled header was generated, or must not affect the precompiled header, which usually means that the they don't appear in the precompiled header at all. @item Certain command-line options. @end itemize @ref{Bugs}. | http://lists.gnu.org/archive/html/automake/2003-10/msg00008.html | CC-MAIN-2014-52 | en | refinedweb |
Opened 4 years ago
Closed 4 years ago
#7874 closed defect (fixed)
RuntimeError: instance.__dict__ not accessible in restricted mode : when used with mod_wsgi
Description
We use mod_wsgi like this:
WSGIScriptAlias / /opt/define/httpd/define.wsgi WSGIImportScript /opt/define/httpd/define.wsgi process-group=%{GLOBAL} application-group=%{GLOBAL} <Directory /opt/define/httpd> WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all </Directory>
Where define.wsgi does this:
def application(environ, start_response): # ... return trac.web.main.dispatch_request(environ, start_response)
Suspect we need to understand more about the pool/svn bindings?
source:browsersvnoperationsplugin/0.12/trac_browser_svn_ops/svn_fs.py
Attachments (0)
Change History (1)
comment:1 Changed 4 years ago by pipern
- Resolution set to fixed
- Status changed from new to closed
Note: See TracTickets for help on using tickets.
We fixed this with a patch we've committed to trac-hacks as [9364] | http://trac-hacks.org/ticket/7874 | CC-MAIN-2014-52 | en | refinedweb |
m2secret is a simple encryption and decryption module and CLI utility built with the M2Crypto library (version 0.18 or later) to make it easy to secure strings and files from prying eyes. The serialized form does not follow any standards.
By default it will use 256-bit AES (Rijndael) symmetric-key cryptography in CBC mode. Key material is derived from submitted password using the PBKDF2 algorithm.
import m2secret # Encrypt secret = m2secret.Secret() secret.encrypt('my data', 'my master password') serialized = secret.serialize() # Decrypt secret = m2secret.Secret() secret.deserialize(serialized) data = secret.decrypt('my master password') assert data == 'my data'
I have found the following two books invaluable when dealing with OpenSSL-based software as well as learning to select safe cryptographic primitives and using them appropriately:
m2secret is Open Source software, licensed under the Apache License, 2.0.
Download from Python Package Index aka Cheeseshop, or just easy_install m2secret.
The source is available from Subversion at
Bugs, suggestions for improvements, patches and so on are welcome.
--Heikki Toivonen <My first name at heikkitoivonen.net> | http://www.heikkitoivonen.net/m2secret/ | CC-MAIN-2014-52 | en | refinedweb |
When you upgrade from Lightroom to Lightroom 4, be sure to upgrade your catalog. The first 2 minutes of this video will show you how.
When you upgrade from Lightroom to Lightroom 4, be sure to upgrade your catalog. The first 2 minutes of this video will show you how.
The bad thing on the LR4 upgrade is that you have to manually:
1. upgrade your catalog
2. upgrade your presets
3. upgrade your photos
4. update/regenerate your preview cache (as the images changed)
You have to do this manually and if you have huge collection of photos, it will take you some time. There is the possibility that you will just upgrade the first 2 points, but then you keep wondering why and wtf etc… So Adobe could maybe improve the process and do whatever is needed as set of transactions on the background…
Thanks for this useful info. I am about to upgrade from LR 2 to 4, is there anything different that I should be aware of to ensure a smooth transition?
Thank you.
This might help –
I’m afraid I have really screwed things up! When upgrading from LR3 to LR4, things did not go smoothly. I have watched every video from you and David Marx and had some communications about having to upgrade my LR3 catalog first, which I thought I followed correctly, and then I downloaded newly shot photos into LR4 catalog and was able to see and adjust them. But I still was getting the ? symbol over many of the images in my folders. So I tried importing the LR3 catalog again, and again. I’m now up to LR4-6 catalog and still getting ?s on many images. Then I tried creating a new Master Catalog and it can’t see any images in any of my folders at all. Some Collections are there, but no images are displayed.
I do understand the concept of Catalogs. I do get the difference between Importing Photos and Importing Catalogs. Somehow my computer doesn’t get something and quite frankly, this upgrade to LR4 could have been created much more easily. Why didn’t it go through automatically???
I do use Windows 7 with 16MB RAM. The one idiosyncrasy that I have is that the Lightroom catalogs are kept in my C drive, a solid state drive not big enough to keep everything, so my actual folders with the actual photo files are kept in hard drive E with 2TB of space. Backups are kept on a separate external hard drive.
Please help or tell me where to go or who I can call. Right now, I can’t use Lightroom at all because it can’t find any of my images in any catalog!!!
If you files and/pr folders are showing question marks, then the files have moved on disk. This video has information on relinking files:
In a nutshell,to relink a folder: right click on the highest level folder and select Update Folder Location.
To relink a file: click on the question mark in the grid view and navigate to find the missing file.
Hi, when I upgraded my catalog from lr3 to 4.1, all previously set flags in my collections went missing, though the star ratings and color labels where preserved. Is there a way to get the flags to migrate as well?
I also realized that the flags in the library folders themselves are preserved, its just the ones in the collections that are missing. Any help appreciated
Ryan, There is a great thread on this topic here:
Basically, Adobe has decided to make all flags global because some users were confused by local flags in collections. If you scroll about half way down the thread, you will see that Dorin Nicolaescu-Musteață has posted a tip (via Victoria Bampton) that will help you recover them.
Upon uograding My LR3 catalogue to LR4 all my colour labels disappeared. Any ideas whats going on?
Thanks.
I’m not aware of that issue, but I would post the issue to either of these forums to see if other customers are experiencing the same problem and if so, if they have found a solution.
I had the same thing happen. Also, when I went to “Set Color Label” under the Photo menu in LR4, the names that I had previously assigned to the different colors in LR3 had reverted back to default names of Red, Yellow, Green, etc.
Images that have a custom color label should appear white. if that’s not the case, I would post the issue to either of these forums to see if other customers are experiencing the same problem and if so, if they have found a solution.
How much does it cost to upgrade from lightroom 3 to lightroom 4?
I am upgrading from LR3 to 4. I have done what you advise in the first few minutes of this video, but the catalog name is now Lightroom 3 catalog current-2 rather than Lightroom 4. The -2 is to distinguish it from the prior LR catalog, I believe. Should I just rename this catalog to LR 4 somewhere?
Thanks for your help with a minor “itch.”
You are correct, and this will tell you how to rename your catalog:
When I open LR 3 catalogues in new upgraded 4, the new widow SAYS LR 4 and the new BOOK and MAP tabs are there, but all the old LR 3 buttons ( recovery instead of highlights) in develop module return ( brightness button is there again) when an image is chosen to work on. Now it is some weird hybrid.
???
The options that you will see in the basic panel are specific to the process version. When you see the older sliders, you are in the older process version. You can change this by clicking the exclamation point in the lower left of the image preview area in the develop module.
Hi!
My computer went to the “doctor” but everything is on it’s place. When opened LR 4 said I needed to upgrade from LR 3, wich I did following your video. But now, all the work done in LR4 is in LR3. Meaning= I can’t see my photos in LR4 but can in LR3. Now all the keyword listing, presets, photos.. everything is lost in LR4. What can I do to recover all that?
Photos I imported before from LR4 are where they used to be, but opens with LR3. Why is this?
Thanks a lot for your help!!!
Oh, and there is a Lightroom 4 Catalog, Lightroom Beta Catalog and a Lightroom 3 Catalog. Thanks again.
Xiomi, I would post the issue to either of these forums to see if other customers are experiencing the same problem and if so, if they have found a solution.
I downloaded lightroom4 2 months ago and my photos all went lightroom4 but I continued to use lightroom 3 for editing.
How do I now combine all the new work to lightroom 4 and not duplicate everything?
This video should help you upgrade your catalog from Lightroom 3 to Lightroom 4:
I want to upgrade from LR3 TO LR4. But after reading all the issues people are having I’m I am just a lettle nervies. Because I am not a very “Techey” person at all!! I’ll watch your video and see what happens.
I need to import the catalogue from lightroom 2 into lightroom 4 (I skipped lightrrom 3). I backed up the catalogue onto an external hard drive before getting a new PC. I have followed the instructions in the video/tutorial but just get the error message “Lightroom cannot use (that) catalogue because it is not writeable and cannot be opened”. Please help.
It sounds like the file is locked? If that’s not it, please post the issue to either of these forums to see if other customers are experiencing the same problem and if so, if they have found a solution.
hello,
i just wondering on an upgrade question , i have lightroom 3 installed because i a running win 97 but my computer will be upgraded to win 7 meaning everthing will be formated and newly installed thats the point where i wnat to move to lightroom 4 ,
the question is what to do.
i backupded as requested from within lightroom, anything elese to do?
remember i do not have any old version any more..
thanks
marc
This might help:
-j
thanks i saved all files and backups as you meantioned in you video, my question is know the new pc will have lightroom 4 on it so how to upgrade the backup and liberay etc to the new version? | http://blogs.adobe.com/jkost/2012/04/upgrading-your-lightroom-3-catalog-to-lightrom-4.html | CC-MAIN-2014-52 | en | refinedweb |
11 August 2010 17:44 [Source: ICIS news]
LONDON (ICIS)--Yara International is well positioned to profit from the projected rise in corn prices, driven by lower inventory levels, which will in turn lead to increased nitrogen fertilizer prices, particularly urea, investment bank JP Morgan Cazenove said on Wednesday.
The rally in wheat prices, which have risen by 30% over the past month, driven by supply concerns including the Russian export ban, wet weather in ?xml:namespace>
However, the investment bank said that other grain prices, in particular corn, could continue to strengthen as inventory levels appeared more fragile, which would in turn give a lift to nitrogen fertilizer prices.
"In our view, Yara’s earnings and share price continue to offer the greatest leverage to rising grain prices. A modest (2-3%) year-on-year increase in the rate of nitrogen fertilizer demand would tighten the overall market significantly, and lead to sharply higher prices and margins," it said.
On top of an improving demand backdrop, JP Morgan Cazenove said that Yara International, which released one of its best ever set of quarterly results on 16 July, would also benefit from the rising marginal production cost of urea, after the recent removal of the gas subsidy for Ukrainian producers, which in turn increased their production costs.
Additionally, JP Morgan Cazenove said that Swiss agrochemicals company Syngenta, which announced that its first-half net income fell by 11% year on year to $1.25bn (€950,000) last month, would also benefit from the price increase.
Rising grain prices and improving farm profits would improve demand and mean surplus crop inventories were consumed quicker, which would in turn bring recent severe price competition to an end, it said.
( | http://www.icis.com/Articles/2010/08/11/9384261/yara-to-benefit-from-rise-in-corn-and-nitrogen-fertilizer-prices.html | CC-MAIN-2014-52 | en | refinedweb |
a small module for verifying an organization’s ability to accept charitable contributions in the U.S. via their EIN number.
pip install charitycheck
simple as that, you’re now good to go! But make sure to read on for (very important) notices about module useage and getting good performance.
This module uses the IRS publication 78 to perform its checks against charity EIN’s. Essentially, the module downloads a copy of IRS Pub 78, unzips the file, converts the data to a quickly searchable dbm file, and then provides some functions to interface with this file. That means that the module searches its local version of Publication 78, thus if you check for a new nonprofit’s charity status, it might not yet be in your database. Similarly, if a nonprofit recently lost its status, your database might not yet reflect that either.
To fix the above problem, you should regularly update your dbm file. This can be done by running this module as a script from the commandline:
python /path/to/charitycheck.py
(in the above command, python should be whatever command your system uses to run python scripts, of course)
or importing the function make_dbm and running it without arguments:
from charitycheck import make_dbm make_dbm()
So that you don’t forget to do this regularly, we recommend setting up a cron job to do this at least less than every two weeks (14 days). You must be the judge of how important it is to make the most up to date information on these nonprofit organizations available to your module.
Because having up-to-date information from the IRS is so important, we’ve added a way for python to internally track how up-to-date your copy of publication 78 is. If you’re local copy is 15 or more days out of date, then the module will automatically download a new copy and recreate the database when one of the public functions in it is called with the argument optimize=False, which they are all set to by default; however, creating the database can take up to several minutes, so not regularly updating your database will unpredictably and severely affect the performance of this module, on top of increasingly jeopardize the validity of its results.
Only you can decide how often you should update your database, but for this reason we suggest at least once every 14 days.
The module uses python’s anydbm module, so for performance reasons you should make sure that you have a fast implementation of the dbm format installed to which python has access. Simply try the following imports to check:
import dbm # the classic new dbm implementation
import gdbm # gnu dbm implementation
import dbhash # dbm implementation found on windows in python2.7
If any of these imports work, you’re good to go. If none of them work, this module will still operate for you, but it will use the dumbdbm implementation, and could be much slower. Consider getting one of the above dbm implementations in python (dbhash is also deprecated and not included in python 3).
The following are the public functions make available by the module:
make_dbm()
Downloads publication 78 from the IRS, unzips it, saves the txt to disk, then converts it into a dbm file for quick useage.
get_nonprofit_data( ein, # the nonprofit organization's ein number optimize=False)
Given an EIN, retrieves the pipe delimited string data, "name|city|state|country|deductability code" from the local copy of publication 78 if the organization exists, otherwise it raises a key error.
If optimize=False, as by default, then it also checks to make sure the local copy of publication 78 is no more than 15 days out of date, calling make_dbm() if the data is more out of date than 15 days.
verify_nonprofit( ein, # the nonprofit organization's ein number name=None, # name of the organization **as it appears in publication 78** city=None, # name of the city the organization is based in state=None, # state abbreviation for the organization deductability_code=None, # the deductability code of the organization # (see 'explanation of data and sources' in README.md) optimize=False)
takes data about the nonprofit organization as outlined in its call signature. The EIN must always be provided, all data should be given as strings. Every piece of information provided besides the EIN is optional. The function will take the provided non-None data, and check it against organizations in the database. If an organization is found matching the provided arguments, then verify_nonprofit returns true, else it returns false. The optimize parameter behaves the same as in get_nonprofit_data.
get_deductability_code( ein, # the nonprofit organization's ein number name=None, # name of the organization **as it appears in publication 78** city=None, # name of the city the organization is based in state=None, # state abbreviation for the organization optimize=False)
takes data about the nonprofit organization as outlined in its call signature, the same as with verify_nonprofit except that it doesn’t accept a deductability code argument. Checks the provided data against organizations in the database, if a match is found, it returns the deductability code, if no match is found, it returns the empty string. The optimize parameter behaves the same as the optimize parameter for get_nonprofit_data.
Of course, this function can also be used to replace verify_nonprofit in a more extensible way, by coercing the string values returned by get_deductability_code to booleans.
The data used in this module is generated from IRS publication 78, located at.
The format of the file at that download site is expected to be a zipped folder, containing a text file, whose names are both data-download-pub78.zip and data-download-pub78.txt respectively, with data-download-pub78.txt being a textfile with a charity on each line, and every line having the format:
EIN|name|city|state|country|deductability code
If any of these assumptions change, the code may need to change accordingly
From the IRS website, here is an explanation of the deductability status codes:
----------------------------------------------------------------------------------------------- | Code | Type of organization and use of contribution. | Deductibility Limitation | ----------------------------------------------------------------------------------------------- | PC | A public charity. | 50% | ----------------------------------------------------------------------------------------------- | POF | A private operating foundation. | 50% | ----------------------------------------------------------------------------------------------- | PF | A private foundation. | 30% (generally) | ----------------------------------------------------------------------------------------------- | GROUP | Generally, a central organization holding a group| | | | exemption letter, whose subordinate units covered| | | | by the group exemption are also eligible to | Depends on various factors. | | | receive tax-deductible contributions, even though| | | | they are not separately listed. | | ----------------------------------------------------------------------------------------------- | LODGE | A domestic fraternal society, operating under the| | | | lodge system, but only if the contribution is to | 30% | | | be used exclusively for charitable purposes. | | ----------------------------------------------------------------------------------------------- | UNKWN | A charitable organization whose public charity | Depends on various factors. | | | status has not been determined. | | ----------------------------------------------------------------------------------------------- | EO | An organization described in section 170(c) of | | | | the Internal Revenue Code other than a public | Depends on various factors. | | | charity or private foundation. | | ----------------------------------------------------------------------------------------------- | FORGN | A foreign-addressed organization. These are | | | | generally organizations formed in the United | | | | States that conduct activities in foreign | | | | countries. Certain foreign organizations that | Depends on various factors. | | | receive charitable contributions deductible | | | | pursuant to treaty are also included, as are | | | | organizations created in U.S. possessions. | | ----------------------------------------------------------------------------------------------- | SO | A Type I, Type II, or functionally integrated | 50% | | | Type III supporting organization. | | ----------------------------------------------------------------------------------------------- | SONFI | A non-functionally integrated Type III | 50% | | | supporting organization. | | ----------------------------------------------------------------------------------------------- | SOUNK | A supporting organization, unspecified type. | 50% | ----------------------------------------------------------------------------------------------- # contributors So far this module has been developed only by Nicholas Lourie, but if other people are interested in helping to extend it to a larger framework for dealing with nonprofit data, pull requests are. | https://pypi.org/project/charitycheck/ | CC-MAIN-2017-13 | en | refinedweb |
tex2pix 0.3.1
Lightweight renderer of LaTeX to a variety of graphics formats
A little library which renders LaTeX to various formats, using applications on your system like latex, pdflatex, bibtex, dvips, ps2eps, and convert. LaTeX is automatically run as many times as necessary to achieve a clean compile (with a user-provided max number of attempts), and Bibtex processing is supported.
Compilation takes place in temporary directories which are automatically cleaned up, can be initiated on a file or text string and include extra input files, and rendering stages are cached to reduce rendering latency.
See also the ‘tex’ module, for a more established TeX renderer with different design requirements.
Usage example:
import tex2pix f = open('example.tex') r = tex2pix.Renderer(f, runbibtex=True, extras=['example.bib']) #r.verbose = True # be loud to the terminal #r.rmtmpdir = False # keep the working dir around, for debugging r.mkeps('example.eps') r.mkpng('example.png') r.mkpdf('example.pdf') # uses cached version from PNG build r.mk('duplicate.pdf') # auto-detect format; uses cached PDF tex2pix.check_latex_package('tikz.sty')
- TODO:
- Provide mechanism (hidden?) for threaded parallel compilation.
- Author: Andy Buckley
- Keywords: tex latex bibtex pdf eps postscript png graphics renderer
- License: GPL
- Package Index Owner: andybuckley
- DOAP record: tex2pix-0.3.1.xml | https://pypi.python.org/pypi/tex2pix | CC-MAIN-2017-13 | en | refinedweb |
Generating Custom XML from SQL 2005
There are a number of ways to programmatically generate custom XML from a database. Before reading Professional ASP.NET 2.0 Special Edition, you probably used FOR XML AUTO to generate fairly basic XML and then modified the XML in post processing to meet your needs. This was formerly a very common pattern. FOR XML AUTO was fantastically easy; and FOR XML EXPLICIT, a more explicit way to generate XML, was very nearly impossible to use.
SQL Server 2005 adds the new PATH method to FOR XML that makes arbitrary XML creation available to mere mortals. SQL 2005's XML support features very intuitive syntax and very clean namespace handling.
Here is an example of a query that returns custom XML. The WITH XMLNAMESPACS commands at the start of the query set the stage by defining a default namespace and using column-style name aliasing to associate namespaces with namespace prefixes. In this example addr: is the prefix for urn:hanselman.com/northwind/address.
use Northwind; WITH XMLNAMESPACES ( DEFAULT 'urn:hanselman.com/northwind' , 'urn:hanselman.com/northwind/address' as "addr" ) SELECT CustomerID as "@ID", CompanyName, Address as "addr:Address/addr:Street", City as "addr:Address/addr:City", Region as "addr:Address/addr:Region", PostalCode as "addr:Address/addr:Zip", Country as "addr:Address/addr:Country", ContactName as "Contact/Name", ContactTitle as "Contact/Title", Phone as "Contact/Phone", Fax as "Contact/Fax" FROM Customers FOR XML PATH('Customer'), ROOT('Customers'), ELEMENTS XSINIL
The aliases using the AS keyword declaratively describe the elements and their nesting relationships, whereas the PATH keyword defines an element for the Customers table. The ROOT keyword defines the root node of the document.
The ELEMENTS keyword, along with XSINIL, describes how you handle null. Without these keywords, no XML element is created for a row's column that contains null; this absence of data in the database causes the omission of data in the resulting XML document. When the ELMENTS XSINIL combination is present, an element outputs using an explicit xsi:nil syntax such as <addr:Region xsi:.
When you run the example, SQL 2005 outputs an XML document like the one that follows. Note the namespaces and prefixes are just as you defined them.
<Customers xmlns: <Customer ID="ALFKI"> <CompanyName>Alfreds Futterkiste</CompanyName> <addr:Address> <addr:Street>Obere Str. 57</addr:Street> <addr:City>Berlin</addr:City> <addr:Region xsi: <addr:Zip>12209</addr:Zip> <addr:Country>Germany</addr:Country> </addr:Address> <Contact> <Name>Maria Anders</Name> <Title>Sales Representative</Title> <Phone>030-0074321</Phone> <Fax>030-0076545</Fax> </Contact> </Customer> ...the rest of the document removed for brevity...
The resulting XML can now be manipulated using an XmlReader or any of the techniques covered in Chapter 13, "Working with XML" of Professional ASP.NET 2.0 Special Edition (Wrox, 2006, ISBN: 0470041781).
There are no comments yet. Be the first to comment! | http://www.codeguru.com/csharp/sample_chapter/article.php/c13651/Generating-Custom-XML-from-SQL-2005.htm | CC-MAIN-2017-17 | en | refinedweb |
Java's miscellaneous operators are: ternary operator, member access, comma, array index, new, instanceof, and typecast. These operators are explained one by one in following sections.
Java provides a special operator that is called ternary or conditional operator. This operator is a set of two symbols that are
? and
:. Both symbols collectively form the conditional operator. This operator can be used if we have to initialize or assign a variable on basis of some condition. It follows the below syntax.
expr-1 ? expr-2 : expr-3;
In above syntax,
expr-1 can be any expression that returns a
boolean value. If
expr-1 returns
true then
expr-2 is processed; else
expr-3 is processed. Note that both
expr-2 and
expr-3 must return the same type of value and they cannot be void. Following piece of code demonstrates the use of Java ternary operator.
/* TernaryOperatorDemo.java */ public class TernaryOperatorDemo { public static void main(String[] args) { int n = 10; boolean flag = (n % 2 == 0 ? true : false ); System.out.println(n + " is even? " + flag); } } OUTPUT ====== 10 is even? true
The Java member access operator is a dot (.) symbol that is used to access data members and member methods of a class by its objects.
Java comma operator is a ',' sign that is used to separate function arguments, and to declare more than one variable of same type in one statement.
Java array index operator, a set of square brackets ([]), is used to declare and access array elements.
The Java
new operator is used to create a new object. Operator
new is a Java keyword. It is followed by a call to a constructor, which initializes the new object. Note that declaring an object and creating an object are two different things. Simply declaring a reference variable does not create an object. For that, we need to use the
new operator. The
new operator creates an object by allocating memory to it and returns a reference to that memory location. The Java
new operator needs a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. Following piece of code demonstrates the use of
new operator.
/* NewOperatorDemo.java */ class Universe { public Universe() {} public void myUniverse() { System.out.println("This is my Universe"); } } public class NewOperatorDemo { public static void main(String[] args) { //new operator creates a new object of type Universe //and assigns it to reference newUniverse Universe newUniverse = new Universe(); newUniverse.myUniverse(); } } OUTPUT ====== This is my Universe
Java instanceof operator also called type comparison operator compares an object to a specific type. It follows the syntax
objRef instanceof type. Here
objRef is the object name and the
type is the name of object type whom
objRef will be compared to. The
equals() method of Java is a nice example that uses
instanceof operator to check if two objects are equal. The following example (
InstanceOfDemo.java) shows the use of Java
instanceof operator.
/* InstanceOfDemo.java */ class Universe { public Universe() {} public void myUniverse() { System.out.println("This is my Universe"); } } public class InstanceOfDemo { public static void main(String[] args) { Universe newUniverse = new Universe(); newUniverse.myUniverse(); System.out.println("Is newUniverse an object of Universe? " + (newUniverse instanceof Universe)); System.out.println("Does newUniverse inherit Object? " + (newUniverse instanceof Object)); } } OUTPUT ====== This is my Universe Is newUniverse an object of Universe? true Does newUniverse inherit Object? true
Java has a rich set of operators. But, like C and C++, Java does not support operator overloading. You can also note that most of the operators of Java are applied on basic types only and not on objects. To perform any operation on objects Java believes in using member methods that's because of object orientation approach of Java to problem solving.
In this tutorial we explained miscellaneous Java | http://cs-fundamentals.com/java-programming/java-miscellaneous-operators.php | CC-MAIN-2017-17 | en | refinedweb |
The app is getting stuck. When I click on "Loading stuck? Click here!" it starts again and this keep on going on in a loop. Everytime I click on I get back to the main screen. When I close the app, it core dumps.
Stack trace of thread 2917:
#0 0x00007f8b33679706 n/a (libnw.so)
In gdb, I get the following:
#0 0x00007f8b33679706 in () at /usr/share/popcorntime/lib/libnw.so
#1 0x000055ffcd446980 in ()
#2 0x00007f8b31bb49e3 in () at /usr/share/popcorntime/lib/libnw.so
#3 0x00007ffe37bd1b01 in ()
#4 0x0000000000000000 in ()
Search Criteria
Package Details: popcorntime 0.3.10-1
Dependencies (13)
- alsa-lib (alsa-lib-noassertion)
- gconf (gconf-gtk2)
-)
- bower (make)
- git (git-git) (make)
- gulp (gulp-cli) (make)
- nodejs-grunt-cli (grunt-cli) (make)
- npm (nodejs6-bin, npm2) (make)
- net-tools (net-tools-debian-ifconfig, net-tools-mptcp) (optional) – vpn.ht client
Required by (0)
Sources (2)
Latest Comments
amitavmohanty01 commented on 2017-03-26 09:56
The app is getting stuck. When I click on "Loading stuck? Click here!" it starts again and this keep on going on in a loop. Everytime I click on I get back to the main screen. When I close the app, it core dumps.
ItachiSan commented on 2016-12-21 08:19
@Commander not really sure about that...
The source code for this package is here:
If you can find any malware, please report me and I will switch repository.
I have sincerely no problem with it, also on my Windows 10 OS.
Commander commented on 2016-12-20 22:42
Acording to
This version maybe got maleware
The clones are a mess atm.
letty commented on 2016-12-14 07:34
Typo in source:
src/debug/debug.js namespae -> namespace
after manual correction, it compiles fine and works! (no black window)
AK_IL commented on 2016-10-19 20:13
Doesn't work: after the first screen when you have to accept the terms I accept and then there is an empty window.
This package seems to work:
RidingLuck commented on 2016-10-17 13:46
This version is not working for me....It opens but show me black screen only. I suggest to use popcorntime-bin if someone have the same problem.
goetzc commented on 2016-08-03 21:34
You can remove the update-desktop-database from install file, as that is now handled by Pacman hooks.
ItachiSan commented on 2016-06-07 21:43
@xantares and @PetrGottesman I am getting the same issue, I was able to reproduce it.
Now I am pointing the PKGBUILD to a different commit which is working.
Keeping it there.
PeterGottesman commented on 2016-06-02 00:46
@ItachiSan
Probably getting the same issue, here is the output.
ItachiSan commented on 2016-05-20 14:27
@xantares I just tried the package and works properly for me.
What exactly happens? | https://aur.archlinux.org/packages/popcorntime/ | CC-MAIN-2017-17 | en | refinedweb |
Having chosen to use Python 3 as implementation language, this CodeEval problem #230 asks for working with a dictionary.
Let's have a look at the test cases. I found that the ordering requirement was not clarified enough in the provided samples, so I added one test case more:
def test_provided_1(self): self.assertEqual('1:1,2,3; 2:1; 3:1,2; 4:1,3;', solution('1 2 3 4 | 3 1 | 4 1')) def test_provided_2(self): self.assertEqual('11:1; 19:1,2; 21:2; 23:2; 29:3; 31:3; 39:3;', solution('19 11 | 19 21 23 | 31 39 29')) def test_key_numbers(self): self.assertEqual('1:1,2,3; 2:2; 4:3; 10:1;', solution('1 10 | 2 1 | 4 1'))We see how the input line is formatted, and how we have to format the output. The third test case shows that the team "10" has to be placed in the output after the team "4", being number 4 less than 10, and not between "1" and "2" as the sorting in lexicographical order would do.
I divided my solution in two steps.
Dictionary transposition
I have in input a dictionary that maps each country in a list of team, I want to get a dictionary team to countries. Let's build it:
def solution(line): teams = {} for country, clubs in enumerate(line.split(' | '), start=1): # 1 for team in map(int, clubs.split()): # 2 teams.setdefault(team, []).append(str(country)) # 3 # ...1) The input gives me the country number only implicitly, I make it explicit by using the built-in python function enumerate() that returns a tuple containing a count (that I force to be 1-based by the parameter start) and a value from the passed iterable. As iterable I have passed to enumerate() the input string, as resulting from splitting it on ' | ', that's it, a list of strings containing a space separated string representing the most cheered teams (I called them "clubs" to avoid name clashes) in that country.
2) I split the clubs string, I convert on the fly, by map(), each resulting value to an integer, and I loop on them.
3) Finally, push a value, stored in country, to the teams dictionary for the key stored in club. However, I should be careful not to append the value on nothing. Meaning I need to explicitly consider the case the current team is not already in the dictionary. This is done by a call to setdefault(), that returns the value associated to the passed key if it exists, otherwise create a new entry for it, with the other parameter as its value (by default None, I have astutely passed an empty list instead).
Formatting the dictionary
I have the data in the teams dictionary, I just need to create a string out of it, respecting the required format. I did it in this way:
result = ["{}:{};".format(key, ",".join(teams[key])) for key in sorted(teams.keys())] return ' '.join(result)To keep the code compact, I did large part of the job in a list comprehension, and then I simply joined each element on a blank string. But let's how I built up the list.
Firstly, look to the right. I have got the keys() from the teams dict, I sorted them, as required - notice that in (2) above I converted them to integers, so the order is the expected one - and I loop on them.
Now on the left. Each element in the list is a string in the format "{}:{};" where the curly brackets are parameters received from the for loop on the right. The first parameter is easy, just the key as retrieved from the dictionary, namely a team number. The second one in a string generated by joining on a comma the value associated to the key on the dictionary. That is the list of countries for the given team.
As a minor point, there is no need to sort the countries, since we have pushed them in the map respecting the order given implicitly in input.
Solution accepted by CodeEval, code pushed to GitHub, both test cases and python script. | https://thisthread.blogspot.com/2017/01/codeeval-football.html | CC-MAIN-2017-51 | en | refinedweb |
I created this method for testing/experimenting with a kernel on a 32 bit Intel/AMD system. The programs can easily be port to a 64 bit Intel/AMD processor with some reference to the Intel/AMD manuals..I actually have it here somewhere if you really need it.
Please Note - This is a hack that will only work on a 32 bit Intel/AMD system, paying special attention to the lines "don't need this line for some compilers/systems - i.e slackware 13.0"
So what does the module and program do?
The module basically sets up an interrupt "0x81" and a simple handler so that the programmer can interact with the kernel in a free and controlled way by calling the interrupt and executing the handler.
I know, not much of an example, its basic allowing the programmer to pass the address of a variable into the kernel an then set it to 99999 but this implementation can be expanded to cover a whole host of interests.
test1.c - The Kernel Module
testit.c - The test user space executabletestit.c - The test user space executableCode:
#include <linux/kernel.h>
#include <linux/module.h>
struct id//interrupt description table
{
unsigned short limit;
void *base;
}__attribute__((packed)) myidtr;
struct intgate//interrupt gate struct
{
unsigned short off1;
unsigned short sel;
unsigned short none;
unsigned short off2;
}__attribute__((packed)) *idttr1, *idttr2, orig, orig2;
unsigned int myint = 99999;//value to set user variable to
void myfunc(void)//our simple handler
{
__asm__
(
"movl %ebp, %esp\n\t"//don't need this line for some compilers/systems - i.e slackware 13.0
"popl %ebp\n\t"//don't need this line for some compilers/systems - i.e slackware 13.0
"pushl %eax\n\t"
"pushl %ebx\n\t"
"movl myint, %ebx\n\t"
"movl %ebx, (%eax)\n\t"
"popl %ebx\n\t"
"popl %eax\n\t"
"iret\n\t"
);
}
union myaddr
{
void *addr;
struct
{
unsigned short a;
unsigned short b;
}__attribute__((packed)) iaddr;
}__attribute__((packed)) theaddr;
int init_module()
{ __asm__ ("sidt myidtr\n\t");
idttr1 = (struct intgate*)(myidtr.base + (128 * 8));//interrupt 0x80
idttr2 = (struct intgate*)(myidtr.base + (129 * 8));//interrupt 0x81
orig2 = *idttr2;
*idttr2 = *idttr1;//short cut - set 0x81 interrupt equal to interrupt 0x08
theaddr.addr = (void*)myfunc;//interrupt handler
idttr2->off1 = theaddr.iaddr.a;//set myfunc to 0x81 handler
idttr2->off2 = theaddr.iaddr.b;//set myfunc to 0x81 handler
return 0;
}
void cleanup_module()
{
*idttr2 = orig2;
printk("setting everything back...we're out of here!\n");
}
Note - this is from months of reading the AMD/Intel manuals...I thought I would save you the pleasure of that task..Note - this is from months of reading the AMD/Intel manuals...I thought I would save you the pleasure of that task..Code:
#include <stdio.h>
#include <stdlib.h>
unsigned int testval = 0;
int main(int argc, char**argv)
{
fprintf(stdout, "initial testval->%d\n", testval);
__asm__
(
"movl $testval, %eax\n\t"
"int $0x81\n\t"
);
fprintf(stdout, "final testval->%d\n", testval);
exit(EXIT_SUCCESS);
} | http://www.linuxforums.org/forum/kernel/creating-test-interrupt-intel-amd-32-bit-processor-print-158869.html | CC-MAIN-2017-51 | en | refinedweb |
This is the mail archive of the cygwin mailing list for the Cygwin project.
On 6/24/16, 2:59 PM, "Corinna Vinschen" <cygwin-owner@cygwin.com on behalf of corinna-cygwin@cygwin.com> wrote: >>. I ended up implementing this a couple of days ago. I was just spending a lazy Sunday morning and then it hit me: this is an exceptionally bad idea. The problem is that Windows uses the Anonymous identity for accounts who have not logged in using a password (as per Erik Soderquistâs email regarding IIS behavior). Files in FUSE file systems that have a UID that cannot be mapped to a SID, will suddenly be owned by that Anonymous user! Obviously this is a huge security hole. I intend to fix this ASAP, but I am now back to where we started. The obvious SID to use is the NULL SID, but that is already used by Cygwin for other purposes. >>". Ideally we should choose a SID that: (1) Is very unlikely to be used by Microsoft at any point in the future. (2) Cannot be associated to a user logon for any reason (see problem with Anonymous SID) above. (3) Maps to a reasonable UID in Cygwin. I propose the following SID/UID mapping: S-1-0-99 <=> UID 0xffffffff (32-bit -1) This is a SID in the S-1-0 (Null Authority) namespace (same one that contains the NULL SID), which is unlikely to be used by Microsoft. So it likely satisfies (1). For the same reason (that it is a new/unused SID in the S-1-0) namespace, I think it also satisfies (2). If we follow the rules from Cygwinâs "POSIX accounts, permission, and securityâ document [IDMAP], the SID S-1-0-99 maps to 0x10063. But we can make a special rule for this SID to map it to a different UID. Mapping it to -1 may be the easiest option, but perhaps we can also consider mapping it to 0xfffffffe (-2). Bill [IDMAP] | http://www.cygwin.com/ml/cygwin/2016-06/msg00372.html | CC-MAIN-2017-51 | en | refinedweb |
Recursion is a topic in mathematics and computer science. In computer programming languages, the term recursion refers to a function that calls itself. Another way of putting it would be a function definition that includes the function itself in its definition. One of the first warnings I received when my computer science professor talked about recursion was that you can accidentally create an infinite loop that will make your application hang. This can happen because when you use recursion, your function may end up invoking itself infinitely. So, as with any other potential infinite loop, you need to make sure you have a way to break out of the loop. The idea in most recursive functions is to break up the procedure being done into smaller pieces that we can still process with the same function.
The favorite method of describing recursion is usually illustrated by creating a factorial function. A factorial normally looks something like this: 5!. Note that there is an exclamation mark after the number. That notation denotes that it is to be treated as a factorial. What this means is that 5! = 5*4*3*2*1 or 120.
Let’s take a look at a simple example.
# factorial.py def factorial(number): if number == 0: return 1 else: return number * factorial(number-1) if __name__ == '__main__': print(factorial(3)) print(factorial(5))
In this code, we check the number that we pass in to see if it is equal to zero. If it is, we return the number one. Otherwise, we take the number and multiply it with the result of calling the same function but with the number minus one. We can modify this code a bit to get the number of times we have recursed:
def factorial(number, recursed=0): if number == 0: return 1 else: print('Recursed {} time(s)'.format(recursed)) recursed += 1 return number * factorial(number-1, recursed) if __name__ == '__main__': print(factorial(3))
Each time we call the factorial function and the number is greater than zero, we print out the number of times we recursed. The last string you should see should be
“Recursed 2 time(s)” because it should only need to call factorial twice with the number 3.
Python’s Recursion Limit
At the beginning of this article, I mentioned that you can create an infinite recursive loop. Well, you can in some languages, but Python actually has a recursion limit. You can check it yourself by doing the following:
>>> import sys >>> sys.getrecursionlimit() 1000
If you feel that limit is too low for your program, you can also set the recursion limit via the sys module’s
setrecursionlimit() function. Let’s try to create a recursive function that will exceed that limit to see what happens:
# bad_recursion.py def recursive(): recursive() if __name__ == '__main__': recursive()
If you run this code, you should see the following exception thrown:
RuntimeError: maximum recursion depth exceeded.
Python prevents you from creating a function that ends up in a never-ending recursive loop.
Flattening Lists With Recursion
There are other things you can do with recursion besides factorials, though. A more practical example would be creating a function to flatten a nested list — for example:
# flatten.py def flatten(a_list, flat_list=None): if flat_list is None: flat_list = [] for item in a_list: if isinstance(item, list): flatten(item, flat_list) else: flat_list.append(item) return flat_list if __name__ == '__main__': nested = [1, 2, 3, [4, 5], 6] x = flatten(nested) print(x)
When you run this code, you should end up with a list of just integers instead of a list of integers and one list. Of course, there are many other valid ways to flatten a nested list, such as using Python’s
itertools.chain(). You might want to check out the code behind the
chain() class, as it has a very different approach for flattening a list.
Wrapping Up
Now, you should have a basic understanding of how recursion works and how you can use it in Python. I think it’s neat that Python has a built-in limit for recursion to prevent developers from creating poorly constructed recursive functions. I also want to note that in my many years as a developer, I don’t think I have ever really needed to use recursion to solve a problem. I am sure there are plenty of problems where the solution could be implemented in a recursive function, but Python has so many other ways to do the same thing that I’ve never felt the need to do so. One other note I want to bring up is that recursion can be difficult to debug since it is hard to tell what level of recursion that you have reached when the bug occurred.
Regardless, I hope you have found this article useful. Happy coding!
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/python-101-rescursion?fromrel=true | CC-MAIN-2017-51 | en | refinedweb |
fypp 2.1.1
Python powered Fortran preprocessor
Fypp is a Python powered preprocessor. It can be used for any programming languages but its primary aim is to offer a Fortran preprocessor, which helps to extend Fortran with condititional compiling and template metaprogramming capabilities. Instead of introducing its own expression syntax, it uses Python expressions in its preprocessor directives, offering the consistency and versatility of Python when formulating metaprogramming tasks. It puts strong emphasis on robustness and on neat integration into developing toolchains.
The project is hosted on github.
Detailed DOCUMENTATION is available on readthedocs.org.
Fypp is released under the BSD 2-clause license.
Main features
Definition, evaluation and removal of variables:
#:if DEBUG > 0 print *, "Some debug information" #:endif #:set LOGLEVEL = 2 print *, "LOGLEVEL: ${LOGLEVEL}$" #:del LOGLEVEL
Macro definitions and macro calls:
#:def assertTrue(cond) #:if DEBUG > 0 if (.not. ${cond}$) then print *, "Assert failed in file ${_FILE_}$, line ${_LINE_}$" error stop end if #:endif #:enddef assertTrue ! Invoked via direct call (argument needs no quotation) @:assertTrue(size(myArray) > 0) ! Invoked as Python expression (argument needs quotation) $:assertTrue('size(myArray) > 0')
Conditional output:
program test #:if defined('WITH_MPI') use mpi #:elif defined('WITH_OPENMP') use openmp #:else use serial #:endif
Iterated output (e.g. for generating Fortran templates):
interface myfunc #:for dtype in ['real', 'dreal', 'complex', 'dcomplex'] module procedure myfunc_${dtype}$ #:endfor end interface myfunc
Inline directives:
logical, parameter :: hasMpi = #{if defined('MPI')}# .true. #{else}# .false. #{endif}#
Insertion of arbitrary Python expressions:
character(*), parameter :: comp_date = "${time.strftime('%Y-%m-%d')}$"
Inclusion of files during preprocessing:
#:include "macrodefs.fypp"
Using Fortran-style continutation lines in preprocessor directives:
#:if var1 > var2 & & or var2 > var4 print *, "Doing something here" #:endif
Passing (unquoted) multiline string arguments to callables:
#! Callable needs only string argument #:def debug_code(code) #:if DEBUG > 0 $:code #:endif #:enddef debug_code #! Pass code block as first positional argument #:call debug_code if (size(array) > 100) then print *, "DEBUG: spuriously large array" end if #:endcall debug_code #! Callable needs also non-string argument types #:def repeat_code(code, repeat) #:for ind in range(repeat) $:code #:endfor #:enddef repeat_code #! Pass code block as positional argument and 3 as keyword argument "repeat" #:call repeat_code(repeat=3) this will be repeated 3 times #:endcall repeat_code
Preprocessor comments:
#! This will not show up in the output #! Also the newline characters at the end of the lines will be suppressed
Suppressing the preprocessor output in selected regions:
#! Definitions are read, but no output (e.g. newlines) will be produced #:mute #:include "macrodefs.fypp" #:endmute
Explicit request for stopping the preprocessor:
#:if DEBUGLEVEL < 0 #:stop 'Negative debug level not allowed!' #:endif
Easy check for macro parameter sanity:
#:def mymacro(RANK) #! Macro only works for RANK 1 and above #:assert RANK > 0 : #:enddef mymacro
Line numbering directives in output:
program test #:if defined('MPI') use mpi #:endif :
transformed to
# 1 "test.fypp" 1 program test # 3 "test.fypp" use mpi # 5 "test.fypp" :
when variable MPI is defined and Fypp was instructed to generate line markers.
Automatic folding of generated lines exceeding line length limit
Installing
Fypp needs a working Python interpreter. It is compatible with Python 2 (version 2.6 and above) and Python 3 (all versions).
Automatic install
Use Pythons command line installer pip in order to download the stable release from the Fypp page on PyPI and install it on your system:
pip install fypp
This installs both, the command line tool fypp and the Python module fypp.py. Latter you can import if you want to access the functionality of Fypp directly from within your Python scripts.
Manual install
For a manual install, you can download the source code of the stable releases from the Fypp project website.
If you wish to obtain the latest development version, clone the projects repository:
git clone
and check out the master branch.
The command line tool is a single stand-alone script. You can run it directly from the source folder
FYPP_SOURCE_FOLDER/bin/fypp
or after copying it from the bin folder to any location listed in your PATH environment variable, by just issuing
fypp
The python module fypp.py can be found in FYP_SOURCE_FOLDER/src.
Running
The Fypp command line tool reads a file, preprocesses it and writes it to another file, so you would typically invoke it like:
fypp source.fpp source.f90
which would process source.fpp and write the result to source.f90. If input and output files are not specified, information is read from stdin and written to stdout.
The behavior of Fypp can be influenced with various command line options. A summary of all command line options can be obtained by:
fypp -h
- Author: Bálint Aradi
- Keywords: fortran metaprogramming pre-processor
- License: BSD
- Categories
- Development Status :: 5 - Production/Stable
- Intended Audience :: Developers
- Intended Audience :: Science/Research
- License :: OSI Approved :: BSD License
- Programming Language :: Python :: 2
- Programming Language :: Python :: 2.6
- Programming Language :: Python :: 2.7
- Programming Language :: Python :: 3
- Programming Language :: Python :: 3.0
- Programming Language :: Python :: 3.1
- Programming Language :: Python :: 3.2
- Programming Language :: Python :: 3.3
- Programming Language :: Python :: 3.4
- Programming Language :: Python :: 3.5
- Programming Language :: Python :: 3.6
- Topic :: Software Development :: Code Generators
- Topic :: Software Development :: Pre-processors
- Package Index Owner: aradi
- DOAP record: fypp-2.1.1.xml | https://pypi.python.org/pypi/fypp/ | CC-MAIN-2017-51 | en | refinedweb |
In this post we will see what are the basics for developing an Android mobile application that has multiple windows or activities. To do that, we need to know how to create and display a new form, window or activity (for the rest of the post we will use the Android vocabulary and call it just activity).
We have seen in the previous parts of the Android Tutorial which are the fundamentals of an Android application and its components. Also we have seen that behind a window there is an Activity type instance that has a lifecycle and a display.
Other topics that are part of this Android tutorial are accessible through Android Tutorial – Overview and contents.
The sketch of the Android mobile application described in this post (the Eclipse project for the example is available at the end of the post) is:
Android Example Sketch
To achieve the proposed objective, to create and display a new Activity, we define the solution steps:
- define a widget on the main activity display used to open the new Activity;
- define the new Activity and its layout; also declare the activity in the Android application manifest file, the AndroidManifest.xml;
- define in the main activity the event and its handler that will display the new Activity;
We will start by creating the skeleton Android project using the Eclipse ADT plugin with the next settings:
- Project Name: AndroidSecondActivity
- Build target: Android 2.3.3
- Application Name: Create and display a new Activity
- Package name: eu.itcsolutions.android.tutorial
- Create Activity: MainActivity
- Min SDK Version: 10
Step 1. The main Activity user interface will be designed in a declarative manner because we will use Java code for more complex things. In order to open the new Activity we will provide a Button on the display. When the user clicks it, the new Activity will be displayed.
1.1. Edit the project /res/values/strings.xml file and add a new item. Use the text editor and not the Resources visual editor, as the first one is faster. Add the item after the existing ones, on line 5 (hello is for the TextView and app_name is for the main Activity title bar):
1: <?xml version="1.0" encoding="utf-8"?>
2: <resources>
3: <string name="hello">Hello World, MainActivity!</string>
4: <string name="app_name">Create and display a new Activity</string>
5: <string name="btnClick">Click me !</string>
6: </resources>
1.2. Add a Button instance on the display by editing the project /res/layout/main.xml. You can delete the existing TextView that has the hello message. The Button instance properties that we initialize are:
- Text: the btnClick string in strings.xml file. If you use the declarative design then the element is accessed using “@string/btnClick”. For procedural design the string resource is accessed using getString(R.string.btnClick).
- Width: wrap_content which is equal to the size of the text;
- Height: wrap_content
- Id: buttonClick. If you use the declarative design then the id of the Button instance is defined using the android:id property. The property gets a value with the “@+id/id_name” syntax. The android:id property is the equivalent of the Button reference when writing Java code and it will be used to refer that particular Button instance (remember that when you use declarative design you don’t write any Java code, but later you may want to access the Button from the code). If you use the graphical layout editor to place the button on the screen, it will generate a default id (android:id=”@+id/button1″) for the Button instance. If you don’t use the graphical layout editor add it in the <Button> description.
Either you use the layout graphical layout editor or not, the main.xml file should look like this (I have deleted the existing TextView and centered the content using of the android:gravity attribute of the LinearLayout element:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns: <Button android: </Button> </LinearLayout>
Step 2.To define a new Activity we must create a new class that extends Activity and also a new layout for it. To do that we have two possibilities. One is to get our hands dirty and write everything form zero and the second option is to use the Manifest visual editor (a WYSIWYG editor with tabs at the bottom which is opened by default when you select the manifest file) that generates part of the needed code (see How to create a new Activity class with the Manifest editor or without it). In this example I will use the first approach. To open the simple XML text editor, select the tab with the manifest file name on it (the last tab) from the WYSIWYG editor.
2.1. The class is created as a common Java class, using File –> New –> Class. Name it SecondActivity and set android.app.Activity as its superclass:
2.2. Because the ADT plugin is not so helpful when creating a new Activity class, in this manner, you must edit it from scratch:
package eu.itcsolutions.android.tutorial; import android.app.Activity; import android.os.Bundle; public class SecondActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } }
2.3. Let’s define a layout for the new Activity. For that, Eclipse is somehow helpful because there is a New Android XML File wizard. To open it, select the project and use File –> New –> Other and from the Android category select Android XML File.
Name the new layout file, second.xml and edit it by placing a TextView on it. The text of the TextView is set in the layout file (not recommended).
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns: <TextView android: </LinearLayout>
2.4. Link the layout file second.xml with the SecondActivity by calling setContentView() in the class onCreate() method:
this.setContentView(R.layout.second);
2.5. Important ! Declare the SecondActivity in the Android project manifest file, AndroidManifest.xml. To do that, you can use the Android Manifest Application tab or you can use the XML text editor (the AndroidManifest.xml tab). I will use the latter option and I will add the next line in the XML file, between <application> and </application> (after the main Activity declaration):
<activity android: </activity>
Step 3. The event that will display the second activity is generated when the user clicks the button. The event-handler architecture is the same as in any Java JSE application. The event is managed by the system and the application defines and register listeners for that event.
3.1. The event listener is the button from the main Activity. To register it as a listener we must reference the button instance from Java code. But the button has been defined in the XML layout file.
- Important !
- To get the reference of a View item, defined in the layout XML file, you can use the View class findViewById(int ID) method. As argument, use the static constant from the R generated class. Also, the XML element must have an android:id attribute with a “@+id/id_name” like value.
After we get the Button reference with a call to findViewById(int ID) method, we register it as a listener using setOnCLickListener() method. This is done in the main Activity onCreate() method after the call to setContentView():
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //get the Button reference //Button is a subclass of View //buttonClick is defined in main.xml "@+id/buttonClick" View v = findViewById(R.id.buttonClick); //set event listener v.setOnClickListener(this); }
After adding the previous code, you will get a compiler error. We will solve it right away.
As you can see, the setOnCLickListener(OnCLickListener l) method requires a reference to an instance of a class that implements the OnClickListener interface, providing a handler for the event.
3.2. The define a handler for the OnClick event we will implement the android.view.View.OnClickListener interface. The interface has an abstract method, onClick(), that we must override. Modify the MainActivity class:
//implement the OnClickListener interface public class MainActivity extends Activity implements OnClickListener { ... //overrides the OnClickListener interface method @Override public void onClick(View arg0) { } }
3.3. The onClick(View arg0) method parameter represents the reference to the widget that launched the event when it was clicked. We compare it to our button reference (we have a single button, but it is best practice to check it).
3.4. As you remember from Android Tutorial (02) – Applications key concepts, activities and resources, the Intent component represents an asynchronous message used to activate activities. So if we want to display a new activity we must do use an Intent reference. The second activity is displayed using the startActivity() method of the Activity class.
@Override public void onClick(View arg0) { if(arg0.getId() == R.id.buttonClick){ //define a new Intent for the second Activity Intent intent = new Intent(this,SecondActivity.class); //start the second Activity this.startActivity(intent); } }
Run and test the Android application. To return to the main activity, use the return button of the emulator keypad.
- Important !
- DO NOT FORGET to declare the SecondActivity in the manifest file. Without that you will get a ActivityNotFoundException and an explicit error message.
It it helps you can check the Android project source. Alex on September 7th, 2011
Android project source link is invalid
#2 by Catalin on September 10th, 2011
HI Alex,
Thank you for the observation. Now, the link is up and the problem has been solved.
#3 by Alex on September 7th, 2011
#4 by Ces on September 26th, 2011
nice example, just have a question, what if i want to add a button to return to the previous page?
thanks a lot.
#5 by Catalin on September 26th, 2011
Hi Ces,
By default the return key of the device will bring back to foreground the previous Activity.
If you want an explicit Back button (on the screen or in the menu) you can use the same principles as in this article. The difference is that when selecting the Back button you must use the Intent to close the current Activity and to return a response to the calling Activity.
Because running Activities are manage by a stack, closing the current one will bring back the previous one.
A possible solution for the Back button onClick handler is:
//create a new Intent
Intent intent = new Intent();
//set the result for the caller
setResult(RESULT_OK, intent);
//close current Activity
finish();
The returning result is useful if you have started the new Activity with startActivityForResult(Intent intent, int requestCode) instead of startActivity(Intent intent) and also if you override the onActivityResult(int, int, Intent) method in the calling Activity.
If you have problems with this, I will put a new article on it.
#6 by Naveenraj xavier on February 14th, 2012
Very Very Very thanks …….Very helpful for Beginners
#7 by hardik on March 31st, 2012
Hey..while linking the second.xml file with the second activity class it is showing an error on ‘second’-”second can not be resolved or is not a field??” buggin’ me a lot!!
#8 by Ravi Joshi on April 14th, 2012
Hi,
I am a beginner in Android app development and was trying to write an app with more than one widget. This post of yours exactly showed me how to do it. I guess developing any application with multiple widgets is so simple now.
Can you kindly provide some pointers/examples of how to develop applications like Angry bird (for e.g) which is more complex and involve lot of graphical content.
Thanks & Regards,
-Ravi
#9 by harsh on March 9th, 2013
thanks…..
it worked | http://www.itcsolutions.eu/2011/08/31/android-tutorial-how-to-create-and-display-a-new-form-window-or-activity/ | CC-MAIN-2017-51 | en | refinedweb |
I just started to experiment with the Session module and came up with
a minimalistic but complete example using the publisher handler. There
are two files, login.py asks for a password to log the user in and
another one which checks if the user was already logged in. In case
he/she isn't the request is redirected to login.py. There are a couple
of security issues with this solution of course but the point is only
to give a toy model demonstrating how this mechanism could in
principle work.
The notation assumes a SetHandler apache directive, with AddHandler
one needs to refer to the scripts as 'login.py' and 'test.py' not just
'login' or 'test'.
Please let me know what the experts think since I wouldn't want to
cause more harm than good by posting a silly FAQ entry :)
# this is our login page, login.py
from mod_python import Session, util
def index( req ):
session = Session.Session( req )
if not session.is_new( ):
return 'You are already logged in.'
form = """<html><form enctype="multipart/form-data" method="POST"
action="login">
<input type=text<br>
<input type='submit' name='go' value='Go'>
</form></html>
"""
try:
secret = req.form[ 'secret' ]
except KeyError:
return form
if secret == 'my_dear_password':
session.save( )
return 'Password correct, now you are logged in.'
else:
return form
# end of login.py
and the other file is:
# this is test.py
from mod_python import Session, util
def index( req ):
session = Session.Session( req )
if session.is_new( ):
util.redirect( req, 'login' )
return
else:
return 'You are logged in.'
# end of test.py | http://modpython.org/pipermail/mod_python/2006-April/020922.html | CC-MAIN-2017-51 | en | refinedweb |
*****************************************
.
*****************************************
So I have been using the Intel Setup and Configuration Software to manage my vPro AMT clients in my test network. I have to admit it is quite nice to have things just work when I want to setup and configure Intel vPro AMT.
But how do I manage those systems? Come on – you know me…I use the Intel vPro Technology Module for PowerShell. I helped make it.
So then the question becomes, how do I get a list of configured computers from the SCS Database? Well, the SCS includes a WMI interface to the data. Great! Now I just need to make a couple wmi calls. And thanks to all the built in PowerShell WMI goodness, those calls are pretty easy.
All my clients are in my network subdomain domain “ent.vprodemo”. I also have an RCS server setup. My credentials I am storing in $cred, and the server’s IP address is stored in $ServerIP.
So here is a sample script that gets all the AMT system Full Qualified domain names and sends them to invoke-amtgui.ps1:
$computerList = @()
$query = "SELECT * FROM RCS_AMT"
$output = Get-WMIObject -computername $serverIP -credential $cred -namespace "root/Intel_RCS_Systems" –query $query -authentication PacketPrivacy
foreach ($item in $output)
{
$computerList += $item.AMTfqdn
}
invoke-amtgui $computerList -credential $cred
If doesn't have to be invoke-amtgui - you could send all the machine to invoke-amtpowermanagement just as easily.
Of course, we could use the IP address as well by using the following line:
$computerList += $item.AMTIPv4
Want to see what else is available? Just write-host $output. Here are the results from one of the systems:
You can see the name, AD OU, AMT version, managed state, LOTs of stuff. Awesome!
In my environment I am using Kerberos, so authentication is covered. But what happens if your environment uses digest credentials? Well, you can use WMI to ask for the digest admin password on a machine:
$output = invoke-WMIMethod -computername $serverIP -credential $cred -Namespace "root/Intel_RCS_Systems" -class "RCS_Systems_RemoteConfigurationService" -name GetConfiguredPassword -authentication PacketPrivacy -argumentlist $FQDN, $IPAddress, $true, $UUID
$output.Password
The WMI interface checks with the machine by logging into it to ensure that it returns the correct password to you. So if the machine is not available you will not be able to get the password. But that is ok since you could not manage it anyways.
How do you get the $UUID and $FQDN? From that WQL query we made earlier –
$query = "SELECT * FROM RCS_AMT"
Just make sure you grab the data you need:
$FQDN = $item.AMTfqdn
$uuid = $ item.name
$AMTIPv4 = $ item.AMTIPv4 | https://communities.intel.com/community/tech/vproexpert/blog/2012/09/21/using-powershell-to-manage-intel-clients-configured-with-the-intel-scs | CC-MAIN-2017-51 | en | refinedweb |
Bagel Programming Guide
Bagel will soon be superseded by GraphX; we recommend that new users try GraphX instead.
Bagel is a Spark implementation of Google’s Pregel graph processing framework. Bagel currently supports basic graph computation, combiners, and aggregators.
In the Pregel programming model, jobs run as a sequence of iterations called supersteps. In each superstep, each vertex in the graph runs a user-specified function that can update state associated with the vertex and send messages to other vertices for use in the next iteration.
This guide shows the programming model and features of Bagel by walking through an example implementation of PageRank on Bagel.
Linking with Bagel
To use Bagel in your program, add the following SBT or Maven dependency:
groupId = org.apache.spark artifactId = spark-bagel_2.10 version = 1.0.1
Programming Model
Bagel operates on a graph represented as a distributed dataset of (K, V) pairs, where keys are vertex IDs and values are vertices plus their associated state. In each superstep, Bagel runs a user-specified compute function on each vertex that takes as input the current vertex state and a list of messages sent to that vertex during the previous superstep, and returns the new vertex state and a list of outgoing messages.
For example, we can use Bagel to implement PageRank. Here, vertices represent pages, edges represent links between pages, and messages represent shares of PageRank sent to the pages that a particular page links to.
We first extend the default
Vertex class to store a
Double
representing the current PageRank of the vertex, and similarly extend
the
Message and
Edge classes. Note that these need to be marked
@serializable to allow Spark to transfer them across machines. We also import the Bagel types and implicit conversions.
import org.apache.spark.bagel._ import org.apache.spark.bagel.Bagel._ @serializable class PREdge(val targetId: String) extends Edge @serializable class PRVertex( val id: String, val rank: Double, val outEdges: Seq[Edge], val active: Boolean) extends Vertex @serializable class PRMessage( val targetId: String, val rankShare: Double) extends Message
Next, we load a sample graph from a text file as a distributed dataset and package it into
PRVertex objects. We also cache the distributed dataset because Bagel will use it multiple times and we’d like to avoid recomputing it.
val input = sc.textFile("data/pagerank_data.txt") val numVerts = input.count() val verts = input.map(line => { val fields = line.split('\t') val (id, linksStr) = (fields(0), fields(1)) val links = linksStr.split(',').map(new PREdge(_)) (id, new PRVertex(id, 1.0 / numVerts, links, true)) }).cache
We run the Bagel job, passing in
verts, an empty distributed dataset of messages, and a custom compute function that runs PageRank for 10 iterations.
val emptyMsgs = sc.parallelize(List[(String, PRMessage)]()) def compute(self: PRVertex, msgs: Option[Seq[PRMessage]], superstep: Int) : (PRVertex, Iterable[PRMessage]) = { val msgSum = msgs.getOrElse(List()).map(_.rankShare).sum val newRank = if (msgSum != 0) 0.15 / numVerts + 0.85 * msgSum else self.rank val halt = superstep >= 10 val msgsOut = if (!halt) self.outEdges.map(edge => new PRMessage(edge.targetId, newRank / self.outEdges.size)) else List() (new PRVertex(self.id, newRank, self.outEdges, !halt), msgsOut) }
val result = Bagel.run(sc, verts, emptyMsgs)()(compute)
Finally, we print the results.
println(result.map(v => "%s\t%s\n".format(v.id, v.rank)).collect.mkString)
Combiners
Sending a message to another vertex generally involves expensive communication over the network. For certain algorithms, it’s possible to reduce the amount of communication using combiners. For example, if the compute function receives integer messages and only uses their sum, it’s possible for Bagel to combine multiple messages to the same vertex by summing them.
For combiner support, Bagel can optionally take a set of combiner functions that convert messages to their combined form.
Example: PageRank with combiners
Aggregators
Aggregators perform a reduce across all vertices after each superstep, and provide the result to each vertex in the next superstep.
For aggregator support, Bagel can optionally take an aggregator function that reduces across each vertex.
Example
Operations
Here are the actions and types in the Bagel API. See Bagel.scala for details.
Actions
/*** Full form ***/ Bagel.run(sc, vertices, messages, combiner, aggregator, partitioner, numSplits)(compute) // where compute takes (vertex: V, combinedMessages: Option[C], aggregated: Option[A], superstep: Int) // and returns (newVertex: V, outMessages: Array[M]) /*** Abbreviated forms ***/ Bagel.run(sc, vertices, messages, combiner, partitioner, numSplits)(compute) // where compute takes (vertex: V, combinedMessages: Option[C], superstep: Int) // and returns (newVertex: V, outMessages: Array[M]) Bagel.run(sc, vertices, messages, combiner, numSplits)(compute) // where compute takes (vertex: V, combinedMessages: Option[C], superstep: Int) // and returns (newVertex: V, outMessages: Array[M]) Bagel.run(sc, vertices, messages, numSplits)(compute) // where compute takes (vertex: V, messages: Option[Array[M]], superstep: Int) // and returns (newVertex: V, outMessages: Array[M])
Types
trait Combiner[M, C] { def createCombiner(msg: M): C def mergeMsg(combiner: C, msg: M): C def mergeCombiners(a: C, b: C): C } trait Aggregator[V, A] { def createAggregator(vert: V): A def mergeAggregators(a: A, b: A): A } trait Vertex { def active: Boolean } trait Message[K] { def targetId: K }
Where to Go from Here
Two example jobs, PageRank and shortest path, are included in
examples/src/main/scala/org/apache/spark/examples/bagel. You can run them by passing the class name to the
bin/run-example script included in Spark; e.g.:
./bin/run-example org.apache.spark.examples.bagel.WikipediaPageRank
Each example program prints usage help when run without any arguments. | http://spark.apache.org/docs/1.0.1/bagel-programming-guide.html | CC-MAIN-2017-51 | en | refinedweb |
This example shows how to access the sensors present on a device and list them.
We begin by declaring a unique namespace for the package we are creating. This is typically based on the reversed form of a domain name and should be unique to this package.
__package__ = "com.example.sensorlist"
We import the classes and modules needed by our application. The most relevant ones for this example are the Sensor and SensorManager classes.
from android.app import Activity from android.content import Context from android.hardware import Sensor, SensorManager import android.os from android.view import ViewGroup from android.widget import LinearLayout, TextView
The SensorListActivity is derived from the standard Activity class and represents the application. Android will create an instance of this class when the user runs it.
class SensorListActivity(Activity): def __init__(self): Activity.__init__(self)
The initialisation method only needs to call the corresponding method in the base class.
The onCreate method is called when the activity is created. Our implementation calls the onCreate method of the base class, queries the available sensors and displays them in a graphical layout.
.
service = self.getSystemService(Context.SENSOR_SERVICE) sensorManager = CAST(service, SensorManager)
We create a vertical layout in which to place text labels for each of the sensors on the device.
layout = LinearLayout(self) layout.setLayoutParams(ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) layout.setOrientation(LinearLayout.VERTICAL)
A list of sensors is obtained by calling the appropriate method of the sensor manager with a constant that requests information about all of the available sensors. We iterate over this list, creating text views for each sensor that show its name.
sensors = sensorManager.getSensorList(Sensor.TYPE_ALL) i = 0 while i < len(sensors): view = TextView(self) view.setText(sensors[i].getName()) layout.addView(view) i += 1
Finally, we use the layout as the main view in the activity.
self.setContentView(layout) | http://www.boddie.org.uk/david/Projects/Python/DUCK/Examples/Serpentine/SensorList/docs/sensorlist.html | CC-MAIN-2017-51 | en | refinedweb |
Agent: Performance has been improved for the
add packagecommand by removing unnecessary queries from its execution process. (Bug #28950231)
Agent: The initialization script for mcmd now cleans up the temporary files it creates under the
tmpdirectory while starting new mcmd processes. (Bug #28924059)
Agent: The
list hostscommand now returns, in addition to
Availableand
Unavailable, two more possible statuses for the agent of a host:
Recovery: The agent is in the process of recovering itself
Unresponsive: The agent rejected an attempt to connect
(Bug #28438155)
Agent: The option
--core-file, when used on the command line to start a node in a wild cluster, now causes the
import clusterand
update processcommands to give a warning (that the option “may be removed on next restart of the process”), instead of causing the commands to fail. See Creating and Configuring the Target Cluster for details. (Bug #28177366)
Agent: The
import clusterand
update processcommands now support a new
--remove-angeloption, which kills any angel processes for the data nodes to be imported or updated and also updates the data nodes' PID files. See descriptions for the two commands for details. (Bug #28116279)
Agent: The backup cluster command finishes faster now, as some unnecessary wait time has been eliminated from the backup process. (Bug #27986443)
Agent: A new option for mcmd,
--initial, allows an agent that has fallen into an inconsistent state to recover its configuration from other agents. See the description for
--initialfor details. (Bug #20892397)
Agent: The
set,
get, and
resetcommands now support the following command-line-only attributes, which can only be configured on the command line when outside MySQL Cluster Manager:
For ndb_mgmd:
--core-file,
--log-name,
--verbose
For ndbd and ndbmtd:
--core-file, --
--verbose
Agent: The internal mechanism for agent recovery has been improved, making it more robust and less error-prone.
Client: To reduce the size of the mcmd log, node events are no longer dumped into the log during a cluster restart. (Bug #28843656)
Client: The message for
ERROR 5200(“
Restore cannot be performed ...”) has been expanded to include the reason for the restore's failure. (Bug #25075284)
Client: The message for
ERROR 5017has been expanded to include the reason for an action being invalid for a process or cluster. (Bug #22777846)
Agent: A large number of unnecessary warnings and error messages have been removed from the log for the
import clustercommand. (Bug #28950370)
Agent: During a rolling restart for a cluster (which takes place, for example, after a cluster reconfiguration), the node group IDs for some data nodes might become some invalid numbers transiently, and that might cause mcmd to throw an internal error (
Error 1003). With this fix, such transient changes of node group IDs are ignored by mcmd, and no error is thrown. (Bug #28949173)
Agent: An
update processcommand on a mysqld node failed with a timeout if the node was in the status of
stopping. It was because mcmd did not retry stopping the node, and this fix makes it do so in the situation. (Bug #28913525)
Agent: After a cluster reconfiguration failed, the restart of an mcmd agent that had lost contact with other agents might fail with a checksum error. That was because in the process, the original configuration for the cluster was removed from the agent's repository by mistake. With this fix, the original cluster configuration was preserved and the agent restarts as expected. (Bug #28904775)
Agent: When trying to shutdown a mysqld node, if mcmd failed to get the MySQL Server's version number through a query, the shutdown failed because mcmd could not decide on the proper shutdown method. With this fix, mcmd falls back on the shutdown method for the MySQL Server version bundled with the mcmd version in the MySQL Cluster CGE distribution. (Bug #28830884)
Agent: Commands to reconfigure or stop a cluster hung when a mysqld node did not respond to queries. With this fix, under the situation, a query to a mysqld node times out after a certain period of time, after which the command for reconfiguring or stopping the cluster is aborted and an error is returned. (Bug #28813012)
Agent: mcmd hung when it failed to stop a data node that was in an unknown status. With this fix, the
stop processcommand fails with an error in the situation. (Bug #28780427)
Agent: Attempts to restore an mcmd agent with data from other agents failed with the agent remaining in the state of recovering indefinitely, when any of the cluster log files was very long. With this fix, the agent only scans the most recent segments of the logs instead of the full logs for error information, which speeds up the restore process and allows it to be completed. (Bug #28671584)
Agent: In an environment that used only IP addresses, if a site was defined using host names, an mcmd agent hung at startup or restart when it attempted reverse DNS lookups. (Bug #28437469)
Agent: The
collect logscommand sometimes reported success before the operation was actually finished if the cluster had many hosts and a lot of log data to be collected. (Bug #28282932)
Agent: mcmd failed to start when its
init.dscript found the previous PID for mcmd was in use by another process, which was taken to mean mcmd was already running. With this fix, the process name for the PID is also checked, so that mcmd is started again if the PID is no longer used by mcmd. (Bug #28278727)
Agent: The
collect logscommand failed with an
ERROR 1003 Internal errorwhen no data was received on the TCP connection established for collecting data from another host. With this fix, the connection is closed gracefully if no data is received, allowing other hosts to connect to the TCP port and send data. (Bug #28278410)
Agent: The
restore clustercommand failed when the cluster to be restored contained databases with special characters in their names. (Bug #28220549)
Agent: Memory leaks occurred when an mcmd process on a management node read large cluster logs during its operations. This fix makes sure mcmd regularly truncates the buffer for log reading, so the buffer size does not keep growing in an uncontrolled manner. (Bug #28076545)
Agent: On Windows platforms, the
collect logscommand failed with an
ERROR 1003 Internal errorwhen the path name of a log file to be transferred was exactly 260 characters. It was because, while 260 is the maximum number of characters allowed, the internal test forgot to count the trailing zero for the path name in the internal buffer, so it failed to catch the error. With this fix, mcmd throws an
ERROR 106 Path max length exceeded for fileinstead in the situation. (Bug #28062069)
Agent: If mcmd was started on Windows platforms with the option
--log-syslogbeing true but without specifying the
--log-fileoption, running the
show settingscommand would cause mcmd to quit with an Error 2013 (Lost connection to MySQL server during query). (Bug #27981362)
Agent: When, due to some reasons (for example, time jumps on virtual machines), an mcmd agent ended up receiving incomplete event records from an ndb_mgmd node, the agent quit unexpectedly. With this fix, mcmd can now parse and handle incomplete records properly. (Bug #25746295)
Agent: Agent recovery (for example, after upgrading the agents) sometimes failed when the agent received recovery configurations both locally and from a remote host, and the recovering process was then frustrated, With the new recovery mechanism now in place, the recovery configuration is only received once. (Bug #25517245)
Agent: The
create sitecommand failed with a timeout when the site to be created had a large number of hosts (more than 45), and the hosts were not uniform in their machine configurations. (Bug #25075284)
Client: In a number of instances where an ndb_mgmd command or a mysqld query failed, the wrong error (
Error 1006or
Error 7006) was thrown. With this fix, the appropriate
Error 7030is thrown instead. (Bug #28829732) | https://dev.mysql.com/doc/relnotes/mysql-cluster-manager/1.4/en/news-1-4-7.html | CC-MAIN-2019-04 | en | refinedweb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.