text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91 values | source stringclasses 1 value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
I am trying to write a piece of code using a random number generation result. I have not been able to successfully debug (see below). Could you assist? I am very new to this programming language.
// Guess - Number Game
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <cstdlib>
int main()
{
int guessCounter = 1,
x;
for (int guess = 1; guess <=20; guess++) {
x = 1 + rand() % 1;
cout <<"I've got the number. Please guess it:";
cin >> guess;
if (guess < x)
cout << "It's less than the number. Please guess again:";
if (guess > x)
cout << "It's greater than the number. Please guess again:";
else
break;
guessCounter = guessCounter+ 1;
cout<<"Input next guess.";
if (guess == x)
cout << "You guessed it!"<<endl;
}
return 0;
} | http://cboard.cprogramming.com/cplusplus-programming/16622-random-number-generation.html | CC-MAIN-2014-35 | refinedweb | 125 | 84.98 |
Post your Comment
Requests Intercepting through a HandlerInterceptor
In this section, you will learn about requests interception through a HandlerInterceptor
Design patterns interview questions2
to declaratively apply filters for intercepting requests and responses. For ex... requests through a centralized code. This could either be through a servlet...;
Q9. What is Intercepting Filter pattern?
Ans
Interview Questions - Struts Interview Questions
for intercepting and translating user input into actions to be performed by the model... by the ActionServlet class. All incoming requests are mapped to the central controller... as action forward through out the application. The action forward are specified
sql connectivity through java
sql connectivity through java i want an example for java db through sql connection.
Thanks in advance
Connecting to a database through the Proxy.
Connecting to a database through the Proxy. Connecting to a database through the Proxy I want to connect to remote database using a program that is running in the local network behind the proxy. Is that possible
html5 through escenic cms
html5 through escenic cms whether we can use html5 in escenic cms?? and how to implement
Iterating through pages
Iterating through pages hello,
I have a web page with a table display of 100 records. At the end of the page, we have a button, "Next Page... with a sample java/ jsp code or technical details of how to iterate through the pages
recovery of password through mail
recovery of password through mail hi i want code for login page authentication in jsp with oracle database.it should be similar to any mail login type.means registration form for new users must be provided,already registered
database through jsp
database through jsp sir actually i want to retrieve the data from database dynamically.because i dont know how many records are there in the database?
thanks
Here is an example of jsp which retrieves data from
sending commands through RxTx
sending commands through RxTx i am trying to call lightOn and LightOff method from NewSerialWriter's run() method but not able to make the correct logic. please help me with this. here is my code of different classes.
package
run a batch file through javascript
run a batch file through javascript How to run a batch file through javascript without prompting
Traversing through filtering
Traversing through filtering
Traversing through filtering
Using jQuery, you can traverse through different elements of a web
page-randomly or sequentially
how to connect the database using hibernet through servlet/jsp through form
how to connect the database using hibernet through servlet/jsp through form plz give me the reply
Hi Friend,
Please visit the following link:
Hope
Connecting to Unix through Java - JavaMail
Connecting to Unix through Java Could you please tell a sample code, where i connect to the unix server and run a script and write the results in a file and mail that file back to me
Overview of Networking through JAVA
Overview of Networking through JAVA
The
Java platform is extremely preferable...
package.
Through TCP we can communicate over the network.
1. Computer... in java network programming through a full
code-example. The example give
Sending images through java mail
Sending images through java mail Am trying to develop greeting application that having images..... in one jsp page i displayed all images and by clicking one image the control go to mail sending page in that the image should add
get element through attribute - XML
get element through attribute hi,i need a function that gets(nodename and the attributevalue)and returns the node
my file look like this:
-
yes
is there function like this:f(medicine,lili)returns the node
Java through Exel - Java Beginners
Java through Exel Hi All,
im ravikiran im suffering with one problem
how can i put the constant height and width values
to the cells in Exel sheet and in the same way how can i goto the
new line in cells
Thanks
Overview of Networking through JAVA
Overview of Networking through JAVA
The Java platform is extremely preferable... in the java.net package. Through TCP we can communicate over the network.
Java
Overview of Networking through JAVA
Style through namespace in Flex4
.style1 {
font-size: medium;
}
Style in Flex4 through <fx:Style> tag:-
In this example we have apply style property through corresponding
components. User can see we have create Text and Link button components
View Resolving through ViewResolver interface
In this section, you will learn about resolving view through ViewResolver interface
how to connect two databse through HibernateFramework
how to connect two databse through HibernateFramework how to connect two databse through HibernateFramework
How we can create a table through procedure ?
How we can create a table through procedure ? How we can create a table through procedure
File copy through intranet - Java Beginners
File copy through intranet Can i copy files from system A to System B connected through intranet??
Is this possible through java IO?
If yes, please let me know
Post your Comment | http://www.roseindia.net/discussion/47022-Requests-Intercepting-through-a-HandlerInterceptor.html | CC-MAIN-2014-42 | refinedweb | 828 | 57.1 |
Hi
can anybody out there tell me how to draw a mouse cursor for 800x600 24bit color graphics mode?
thx
This is a discussion on Mouse in 800x600 24Bit Mode? within the A Brief History of Cprogramming.com forums, part of the Community Boards category; Hi can anybody out there tell me how to draw a mouse cursor for 800x600 24bit color graphics mode? thx...
Hi
can anybody out there tell me how to draw a mouse cursor for 800x600 24bit color graphics mode?
thx
just draw it over... use a double buffering system... try to explain it more...
hasafraggin shizigishin oppashigger...
In VGA graphics when using a mouse, the cursor is automatically redrawn and everything, but in SVGA graphics it's not.
So, you have to continually check to see if the mouse has moved. If it has, redraw it.
The easiest way to do this would be to make an interrupt handler fire off when the mouse is moved.
Well, I don't know if the easiest way is to install an interrupt handler for 33h. The 33h ISR will tell you where the mouse cursor is even on higher res modes, but it will not display the cursor. Instead of hooking the interrupt and re-inventing the wheel (the driver already does most of what you need) the easiest way is poll the mouse driver functions that return the mouse cursor position. Place your bitmap in your double buffer or directly to the screen, whichever is applicable in your program, and you will have a mouse cursor in 800x600 modes.
In this method you will have to poll the driver within your main loop to continually check for mouse activity. However, this method is somewhat easier to implement than hooking the 33h interrupt.
One more thing. When the mouse driver returns the x,y of the cursor in cx and dx registers remember that the driver is not taking into account the bit depth of your current video mode. So, to place the cursor at the correct location, you will have to take the bit depth of your current mode into account.
hi
OK i'll explain my problem better:
i have the code for getting the mouse cursor x,y. Now in this mode i can't see the cursor. So i have to paint one for this mode. Now i'm asking you if i have to redraw the screen everywhere the mousecursor is moving above or if it exist an easier function which automatical redraws the screen.
i'm currently use this code, wich has a (bios?) cursor. (if somebody has an idea to make it better...)
Please tell me if i have to draw the cursor in any special register or sth. else.
// Begin code
union REGS rin,rout;
int InitMouse(void)
{
rin.x.ax=0;
int86(0x33,&rin,&rout);
return (rout.x.ax);
}
void mouseoff(void)
{
rin.x.ax=2;
int86(0x33,&rin,&rout);
}
void mouseon(void)
{
rin.x.ax=1;
int86(0x33,&rin,&rout);
}
int eixx(void)
{
rin.x.ax=3;
int86(0x33,&rin,&rout);
return(rout.x.cx);
}
int eixy(void)
{
rin.x.ax=3;
int86(0x33,&rin,&rout);
return(rout.x.dx);
}
int button(void)
{
rin.x.ax=3;
int86(0x33,&rin,&rout);
return(rout.x.bx);
}
void SetMousePos(int x, int y)
{
rin.x.ax=4;
rin.x.cx=x;
rin.x.dx=y;
int86(0x33,&rin,&rout);
}
// end of code
bye
There are a couple of ways to accomplish what you want. First off, no there is not a function that will draw a mouse cursor on the screen in 800x600x16M or 24 bit mode. The hardware cursor, or the cursor that the mouse driver uses, is not designed for hi-color modes. This cannot be done just using an interrupt with the correct register values.
As I said before, you retrieve the coordinates of the mouse cursor, which you already know how to do. Then:
If you are double buffering, that is, drawing the screen to a buffer first and then copying the buffer to vid-ram (can only be done effectively in protected mode for 800x600 24 bit using the LFB) then you will draw your mouse cursor at x,y in the buffer - remember to take into account the bit depth for your mode.
If you are not double buffering, that is, you are drawing the mouse cursor directly to the screen, you could use masks. The first mask will represent the area that the cursor does not occupy. This is called the screen mask. The second mask will only cover the areas that the cursor will occupy. This is called the cursor mask. It is similar to what you have to do when you call subfunction 9 on int 33h to change the mouse cursor. You must supply a cursor mask and a screen mask.
I believe the order of operations is to AND the screen mask with existing screen information. Then XOR the cursor mask with the result of the above operation. To restore the background, you must recopy the rectangular area that the entire graphic used.
If you do not want to mess with masks and you already have a sprite 'put' function that allows for transparent pixels then just use that function to place the mouse cursor. This might be easier since you could set up your mouse cursor exactly like all of your other bitmaps. Just use your transparent color on the areas that the cursor does not occupy. But, if you are not double-buffering there is a chance you will get flicker when you redraw the background image over the mouse cursor, effectively erasing the mouse cursor in preparation for a cursor move.
To minimize flicker in a non-double buffer environment, only erase the mouse cursor when it is being moved, or when some screen operation needs to be done that will affect the mouse, such as re-drawing a button under the mouse.
Code:struct tagMouse { int x; int y; int lastx; int lasty; int btndwn; }Mouse; void ResetMouse { union REGS regs; regs.x.ax=0x00; int86(0x33,& regs, & regs); if (regs.x.ax!=0xFFFF) { printf("Mouse driver not found.\n"); exit(0); //no error code - but will still exit } Mouse.x=regs.x.cx; Mouse.y=regs.x.dx; Mouse.lastx=Mouse.x; Mouse.lasty=Mouse.y; Mouse.btndwn=0; //could be used to return num buttons on //mouse - regs.x.bx } //Inline because will be called often - eliminate function call //overhead inline void GetMousePosition(void) { union REGS regs; regs.x.ax=0x03; int86(0x33,& regs,& regs); Mouse.x=regs.x.cx; Mouse.y=regs.x.dx; Mouse.btndwn=regs.x.bx; } //Checks for mouse activity void CheckMouse(void) { GetMousePosition(); if (Mouse.x!=Mouse.lastx || Mouse.y!=Mouse.lasty) { //Mouse has been moved on x or y coord //Redraw screen area with prior image to erase mouse //Draw mouse cursor at Mouse.x,Mouse.y to move cursor //These will be calls to your functions that draw the cursor, etc .... .... //Now set lastx and lasty to reflect new change Mouse.lastx=Mouse.x; Mouse.lasty=Mouse.y; } //Now you could check for button presses if (Mouse.btndwn==0x01) { //Button 1 pressed //Do something here...... //Check to see if we overlap a button //If so, before we redraw the button as pushed - //we must erase the mouse cursor prior to redrawing //and replace the cursor after we are done //Clear btndwn - event has been processed and dealt with Mouse.btndwn=0; } }
Now the mouse cursor will only be erased with the screen image when the mouse has been moved or some other mouse event has happened. The flicker will very limited. This is not very elegant, but I usually make the mouse a global object unless I'm programming some type of advanced windowing system with a definite hierarchy. This could easily be implemented using classes, etc., and would eliminate the global mouse object (if that bothers you). All of this would become part of your graphics system. For multiple mode support, you would just override the pixel plotting function to deal with different modes, bit depths, color depths, etc. This way your mouse cursor could be displayed in other modes other than 800x600x24 bit since it uses the 'put' sprite function which in turn would use the appropriate plot pixel function.
Hope this helps.
Hi
thanks this helps a little bit, but now I've got the problem that the cursor only appears between pixel 0,0 and about 700,200 and moves only every 5 pixels (OK the 5 pixel problem might be uninteresting but the other one...)
if you've got an idea...
bye
Let's see...
Since your offset is clearly beyond one bank at 700,200 I'll assume you are bank switching correctly. Make sure that the granularity of your video card for 800x600x16M is indeed 64k. If it is not, then your offset will be off and you will not be selecting the correct bank.
There is also a case in 24-bit mode where you will have to bank switch amidst writing a pixel to the screen. In other words, part of the color information for one pixel belongs in another bank.
If you are using the LFB, then this would not apply to you.
I'll attach one of the Peroxide tutorials on VBE 2.0+ which will explain everything. You can get more tutorials at. They are amidst making a game so not many new tutorials are there.
oh, hmmm... when using VESA modes the mouse interrupts only generate increments of 8 in it's position variables. so, i'd suggest you set the limits to 8 times the size of your screen resolution, and translate... that could attribute to your pecularities...
hasafraggin shizigishin oppashigger...
I've not ran into that problem. Usually in hi-res modes I'm just doing mouse look functions and not cursor related stuff. If the driver limits the cursor to a certain area, then multiplying or whatever will move your cursor. But, if the driver doesn't know the new position, or accept the new position, then the cursor still won't work right.
There is a function that allows you to set a bounding box for the mouse. It might be possible to set this box to the entire screen for your resolution. This way the driver would allow you to move beyond what it thinks is the edge of the screen.
Well, I've looked at my docs and there seems to be two functions that might help you with this problem, if it is in fact due to the driver limiting the cursor range.
Subfunction 07h - Set Horizontal Cursor Range
IN: AX=0007h; CX=min col (pixels); DX=max col (pixels)
OUT: none
Subfunction 08h - Set Vertical Cursor Range
IN: AX=0008h; CX=min row (pixels); DX=max row (pixels)
OUT none
If you are using subfunction 04h, try to set the cursor range beyond what it is currently allowing. If this works, then you know that the driver will allow you to set the range to a value beyond what it currently allows and the above functions would work.
Remember your bit depth. The driver will not take this into account, so you will need to do some multiplies (hopefully left shifting) to get the cursor at the right point on the screen.
Set your max row and min row according to your resolution w/o the bit depth. Your multiplies should correspond that when the driver reaches 800 on the horizontal - your cursor is at the far right edge of the screen.
oh, speaking of interrupts... [and here's where i got my information too...] a great resource on interrupts is Ralph Brown's Interrupt List... i don't know where they currently serve it, but if anyone reads this, it's a good resource for DOS programmers...
hasafraggin shizigishin oppashigger...
Actually, I got my info from an earlier doc I had downloaded while at college. The doc no longer exists, or all links to it are broken, but you can get the same info from the interrupt list.
Do not know where it is right now. Look up Ralph Brown's Interrupt List on or. It should be near the top of the list as this thing is all over the Internet.
That was posted by Bubba. Apparently my browser did not auto log me in this time. Wonder why?
hmmm... that has been a problem occasionally... it's never happened to me though, [i'm using IE5.5 btw]... that, and i'd know if i wasn't logged in since i'm a moderator... it'd be more obvious... do you go directly from your email notifications to the board? maybe that could have been the problem...
oh, and i find it interesting where you got your information, i don't know what i'd do without my sweet sweet interrupt list...
finding it otherwise was very difficult...finding it otherwise was very difficult...
hasafraggin shizigishin oppashigger... | http://cboard.cprogramming.com/brief-history-cprogramming-com/4622-mouse-800x600-24bit-mode.html | CC-MAIN-2015-35 | refinedweb | 2,186 | 73.58 |
Java projects for beginners
In this tutorial you will be briefed about the Java projects for beginners
who have to various ideas and projects, which is likely to involving Java. Java... of complex java projects as far as you can
imagine and think, as these projects
Regarding struts validation - Struts
Regarding struts validation how to validate mobile number field should have 10 digits and should be start with 9 in struts validation? Hi...
-------------------------------------------------------------
For more <p>hi here is my code in struts i want to validate my...
}//execute
}//class
struts-config.xml
<struts..."/>
</plug-in>
</struts-config>
validator
regarding struts 2
regarding struts 2 is it not possible to get values from applicationresources.properties into our application in struts 2
Free Java Projects - Servlet Interview Questions
Free Java Projects Hi All,
Can any one send the List of WebSites which will provide free JAVA projects with source code on "servlets" and "Jsp" relating to Banking Sector? don't know
java struts DAO - Struts
java struts DAO hai friends i have some doubt regarding the how to connect strutsDAO and action dispatch class please provide some example to explain this connectivity.
THANKS IN
How to build a Struts Project - Struts
How to build a Struts Project Please Help me. i will be building a small Struts Projects, please give some Suggestion & tips
regarding tags - Struts
regarding tags What is the difference between html:submit and nested:submit and usage of tags based on the situation
Struts Articles
It is the first widely adopted Model View Controller (MVC) framework, and has proven itself in thousands of projects. Struts was ground-breaking when... years. It is also fair to say that Struts is not universally popular, and
Apache Ant - Building Simple Java Projects
Apache Ant - Building Simple Java Projects
... will introduce you to Apache's Ant
technology, which is a mean to build java projects... to build his/her own java projects;
and if you are already exposed to Ant, then also
What is Struts
do not work when it comes to large projects and hence we require Struts.
Java...Apache Struts is used to create Java web applications using Java Servlet API... and their associated Java classes.
Struts is open-source and uses Java
Struts - Struts
Java Bean tags in struts 2 i need the reference of bean tags in struts 2. Thanks! Hello,Here is example of bean tags in struts 2: Struts 2 UI
Struts Articles
Struts Articles
Building on Struts for Java 5 Users
Struts is undoubtedly the most successful Java web...) framework, and has proven itself in thousands of projects. Struts was ground-breaking
projects on cyber cafe
projects on cyber cafe To accept details from user like name Birth date address contact no etc and store in a database
Hi Friend,
Try this:
import java.awt.*;
import java.sql.*;
import javax.swing.*;
import
Struts 2 - History of Struts 2
;
Doubt Regarding Charts
Doubt Regarding Charts Hi,
Can you please help me out by answering "hoe to include charts in core java code and struts code"
thanks in advance,
Swaroop Eswara
Please visit the following link:
Jfreechart
Struts Books
Struts
Jakarta Struts is an Open Source Java framework for developing... for applying Struts to J2EE projects and generally accepted best practices as well...- projects:
AppFuse - A baseline Struts application to
struts - Struts
struts hi..
i have a problem regarding the webpage
in the webpage i have 3 submit buttons are there.. in those two are similar and another one is taking different action..
as per my problem if we click on first two submit
Regarding one business scenario
Regarding one business scenario Ya actually i have a requirement... questions randomly into jsp page?
How to solve this requirement using Struts 2.x...
Java
And how to integrate java application to jsp page
Open Source projects
;
Java technology : Open source projects
The new Enterprise-class...Open Source projects
Mono
Open Source Project
Mono provides... standards
* Can run .NET, Java, Python and more.
* Open Source, Free Software
struts
java - Struts
java what is the default Action class in struts
Java Struts - Struts
Java Struts How we can create mvc architecture and its advantages? Hi Friend,
Please visit the following link:
Thanks... big projects.
Struts 2 Actions
Struts 2
Actions...Struts 2 Tutorial
Advertisements
If you enjoyed this post then why not add us on Google+? Add us to your Circles | http://roseindia.net/tutorialhelp/comment/81286 | CC-MAIN-2015-40 | refinedweb | 731 | 68.4 |
How to create admin user in Kubernetes to login to Dashboard
There are cheap Kubernetes clusters out there and nowadays people like to do some tests. In this short article I will show you how to create a simple admin user with complete access easily. I’ll also show you how to enjoy the Kubernetes Dashboard on a DigitalOcean (or any other) cluster.
I would assume that you created your cluster. Within DigitalOcean this is as simple as a click. If you don’t have access to DO already you can use this ref link and get $100 of services for free:
Providing developers and businesses a reliable, easy-to-use cloud computing platform of virtual servers (Droplets)…m.do.co
Before we start to make things even easier let’s create a simple alias. I called my alias “kube” and it will be referring the –kubeconfig at all times. I’ll be using it throughout this article so adjust your environment to your liking so you can follow along. Here’s my alias:
[kstaykov@manja ~]$ alias kube
alias kube='kubectl --kubeconfig=/home/kstaykov/Downloads/k8s-1-11-1-do-1-lon1-1540329911350-kubeconfig.yaml'
[kstaykov@manja ~]$
Now it’s time to setup your service account. Use this command:
kube create -n kube-system serviceaccount admin
Notice that I created my service account in the kube-system namespace. If you want to know what namespaces you have you can get them using:
kube get namespaces
Now let’s put on a very permissive role binding setting for our cluster.
kube create clusterrolebinding permissive-binding \
--clusterrole=cluster-admin \
--user=admin \
--user=kubelet \
--group=system:serviceaccounts
Note that this policy will allow for ALL service accounts to act as administrators. Bare it in mind and don’t use this for production service. The concept of this article is to make a simple testing cluster.
Now it’s time to get the configuration of our user.
[kstaykov@manja ~]$ kube -n kube-system get serviceaccount admin -o yaml
apiVersion: v1
kind: ServiceAccount
metadata:
creationTimestamp: 2018-10-28T08:45:31Z
name: admin
namespace: kube-system
resourceVersion: "463455"
selfLink: /api/v1/namespaces/kube-system/serviceaccounts/admin
uid: d3adfa7a-da8d-11e8-aeb9-622f6909f16e
secrets:
- name: admin-token-ndrwp
[kstaykov@manja ~]$
We can see that there is a secret here. Let’s grab it:
[kstaykov@manja ~]$ kube -n kube-system get secret admin-token-ndrwp -o yaml
apiVersion: v1
data:
ca.crt: <removed>
token: <removed>
kind: Secret
metadata:
annotations:
kubernetes.io/service-account.name: admin
kubernetes.io/service-account.uid: d3adfa7a-da8d-11e8-aeb9-622f6909f16e
creationTimestamp: 2018-10-28T08:45:31Z
name: admin-token-ndrwp
namespace: kube-system
resourceVersion: "463454"
selfLink: /api/v1/namespaces/kube-system/secrets/admin-token-ndrwp
uid: d3afa9e0-da8d-11e8-aeb9-622f6909f16e
type: kubernetes.io/service-account-token
[kstaykov@manja ~]$
I removed the ca.crt and token data but you should be able to see some big strings there. Notice that the token is base64 encoded. Use a command such as this to decode it:
echo "put-token-here" | base64 --decode
Now you should have a different string and that’s your true token. Keep this private as it has complete access over your cluster! Time to use it to login to the Dashboard. Open a proxy to the cluster:
kube proxy
This will open port 8001 on your machine and using it you can proxy to the API of the cluster. It’s a tunnel of a sort. Go to this URI:
Login using token authentication and use the token you decoded.
There you go! The Kubernetes Dashboard.
| https://medium.com/@k.t.staykov/how-to-create-admin-user-in-kubernetes-to-login-to-dashboard-9e9bffe72c01 | CC-MAIN-2019-26 | refinedweb | 595 | 56.45 |
14 August 2012 10:03 [Source: ICIS news]
SINGAPORE (ICIS)--?xml:namespace>
September PIA prices are being targeted at around $1,700-1,750/tonne CFR (cost & freight)
Prices of feedstock mixed xylene have gone up to $1,260-1,280/tonne CFR NE (northeast) Asia in the week ended 10 August, up by $178/tonne or 16% over two months, according to ICIS.
Over the same period, PIA prices increased at a slower pace of around 9%.
This makes another round of price increase for PIA “inevitable”, the source said.
Expectations of tighter supply-and-demand balance in the PIA market will lend additional support to the prices, the source said.
KP Chemical, which is Asia’s largest PIA producer, plans to shut its 200,000 tonne/year PIA unit in
PIA is used as a modifier in downstream polyethylene terephthalate (PET) bottle-grade resins and as an additive in unsaturated polyester resins (UPR), coatings and low melting fibre (LM | http://www.icis.com/Articles/2012/08/14/9586612/s-koreas-kp-chemical-proposes-150tonne-price-hike-for-sept.html | CC-MAIN-2014-52 | refinedweb | 161 | 55.78 |
Opened 9 years ago
Last modified 7 years ago
#14422 new defect
Rename `sage.symbolic.units.is_unit`
Description
sage.symbolic.units.is_unit should be renamed, since there are
is_unit methods for
Expression and
Integer, for example, with completely different functionality. This is confusing, especially since you can do the following:
sage: units.length.meter.is_unit() True sage: x.is_unit() True sage: sage.symbolic.units.is_unit(units.length.meter) True sage: sage.symbolic.units.is_unit(x) False
Perhaps something like
is_measurement_unit would be better?
Change History (5)
comment:1 Changed 9 years ago by
Last edited 9 years ago by (previous) (diff)
- Milestone changed from sage-6.3 to sage-6.4
Note: See TracTickets for help on using tickets.
I believe (I haven't checked this) that those
is_unit()methods are on instances of
Expressionand
Integer, not for direct use. Plus by explicitly calling
sage.symbolic.units.is_unit(), you should know what you're doing. However the
is_*functions are deprecated from the global namespace (not to mention that it seems like this is not even in the global namespace) and this might even be a simple enough function that it can be removed, see #12824.
Thus I'm thinking this ticket should be closed, but a small patch to change the name might not hurt... | https://trac.sagemath.org/ticket/14422 | CC-MAIN-2021-43 | refinedweb | 216 | 51.44 |
*
A friendly place for programming greenhorns!
Big Moose Saloon
Search
|
Java FAQ
|
Recent Topics
|
Flagged Topics
|
Hot Topics
|
Zero Replies
Register / Login
JavaRanch
»
Java Forums
»
Java
»
I/O and Streams
Author
Getting the free disk space
Proteu Alcebidiano
Greenhorn
Joined: Oct 28, 2004
Posts: 9
posted
Oct 28, 2004 06:15:00
0
Does anyone known a pure
java
solution (or alternative methods) for this problem?? (Don�t tell me about JConfig)
Joe Ess
Bartender
Joined: Oct 29, 2001
Posts: 8924
9
I like...
posted
Oct 28, 2004 12:37:00
0
There's no functionality in the API to get the free disk space. The work-around I've seen involves exec()ing the appropriate platform-dependent command (dir on Windows, df on *nix) and parsing out the answer.
"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[
How To Ask Questions On JavaRanch
]
Proteu Alcebidiano
Greenhorn
Joined: Oct 28, 2004
Posts: 9
posted
Oct 28, 2004 18:21:00
0
dir command is problematic...
if I list a directory from a empty disk (a:\ for example) the output cannot return the free disk space
Its necessary to have some file inside the disk...
Do you know any alternative method for this problem?
thanx
Bertie Ramsbottom
Greenhorn
Joined: Nov 17, 2004
Posts: 1
posted
Nov 17, 2004 16:32:00
0
Dear Proteu,
I have an alternative. You may not like it, but it's better than nothing. I managed to solve the problem of disc space reporting by downloading the excellent and free Cygwin, and calling the "df" command with exec().
You don't need to have the entire Cygwin distribution installed on the machine executing the code when you use df: I only use df.exe and the two DLLs required by df.exe (cygiconv-2.dll and cygwin2.dll), in a special lib directory I created for the assorted binary utilities used by my code.
As I'm creating a custom
Ant
task in Java that will check the available disc space before a build runs, this method seemed to be the best way of doing it, when considering my available time, my limited programming skill, and my requirements. And of course it would be easy to convert my Ant script to run on a Linux or Unix, because df is a standard tool.
There's a snippet of my code at the end of my code... it's a bit rubbishy, but I'm not a developer, and all I wanted was to get it working. You will be able to at least get an idea of what I'm doing.
This is the output it produces when called from ant:
check_disc_space: [checkdiscspace] Checking disc space on E: (../cygwin/df.exe E: -m) [checkdiscspace] - Total volume size: 4997M [checkdiscspace] - Total space in use: 4360M (88%) [checkdiscspace] - Total space available: 636M [checkdiscspace] - Minimum space required: 300M [checkdiscspace] There is enough free disc space to perform this task. [checkdiscspace] Setting Ant variable "repair.enough_disc_space" to true... [echo] Disc space okay: commencing with analyse/repair process...
This is the Ant code I use to call the Java:
<!-- ================================================================ --> <!-- Compile the custom Ant tasks, ready for use below --> <!-- ================================================================ --> <target name="build_custom_tasks"> <property name="build.dir" location="build"/> <mkdir dir="${build.dir}"/> <javac srcdir="src" destdir="${build.dir}"/> <taskdef name="checkdiscspace" classname="com.bestbuyca.CheckDiscSpace" classpath="build;${env.CLASSPATH}"/> <taskdef name="getuseremailaddresses" classname="com.bestbuyca.GetUserEmailAddresses" classpath="build;${env.CLASSPATH}"/> <taskdef name="waitforit" classname="com.bestbuyca.WaitForIt" classpath="build;${env.CLASSPATH};../j2sdk1.4.2_06/lib"/> </target> <!-- ================================================================ --> <!-- Make sure that there is enough disc space for proper execution --> <!-- ================================================================ --> <target name="check_disc_space" depends="build_custom_tasks"> <checkdiscspace dfcommand="../cygwin/df.exe" drive="E:" minimummegs="300" flagvar="repair.enough_disc_space"/> <if> <istrue value="${repair.enough_disc_space}"/> <then> <echo message="Disc space okay: commencing with analyse/repair process..."/> </then> <else> <fail message="There is not enough disc space available."/> </else> </if> </target>
This is the source code from CheckDiscSpace.java:
package com.bestbuyca; import java.io.*; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Task; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.MatchingTask; public class CheckDiscSpace extends Task { private String drive; private String dfCommand; private String[] driveInfo; private String flagVar; private String minimumMegs; public void setDfCommand (String dfCommand) { this.dfCommand = dfCommand; } public void setDrive (String drive) { this.drive = drive; } public void setFlagVar (String flagVar) { this.flagVar = flagVar; } public void setMinimumMegs (String minimumMegs) { this.minimumMegs = minimumMegs; } public void execute() throws BuildException { try { // Execute command String command = dfCommand + " " + drive + " -m"; System.out.println ("Checking disc space on " + drive + " (" + command + ")"); Process child = Runtime.getRuntime().exec(command); // Get the input stream and read from it InputStream in = child.getInputStream(); // Set up an assortment of variables used in processing output int c; boolean secondLineFlag = false; int lineCharacterIndent = 0; String stats = ""; char lastChar = '\n'; // Parse the output from InputStream in while ((c = in.read()) != -1) { // Uncomment for debug: will display all output //System.out.print ((char) c); // ignore the first line (contains column headings) if (c == '\n') { // When set, characters are saved to a buffer string secondLineFlag = true; // In starts on 25th character of second line... lineCharacterIndent = 24; } if (secondLineFlag) { lineCharacterIndent--; if (lineCharacterIndent < 1) { // Condense duplicate space characters to one if (!(c == ' ' && lastChar == ' ')) stats += (char) c; } } // Remember the last character lastChar = (char) c; } in.close(); // Split stats at each space character to extract details driveInfo = stats.split(" "); System.out.println (" - Total volume size: " + driveInfo[0] + "M"); System.out.println (" - Total space in use: " + driveInfo[1] + "M (" + driveInfo[3] + ")"); System.out.println (" - Total space available: " + driveInfo[2] + "M"); System.out.println (" - Minimum space required: " + minimumMegs + "M"); if (Integer.parseInt(minimumMegs) > Integer.parseInt(driveInfo[2])) { System.out.println ("There is not enough disc space to perform this task."); System.out.println ("Setting Ant variable \"" + flagVar + "\" to false..."); getProject().setNewProperty(flagVar, "false"); } else { System.out.println ("There is enough free disc space to perform this task."); System.out.println ("Setting Ant variable \"" + flagVar + "\" to true..."); getProject().setNewProperty(flagVar, "true"); } } catch (IOException e) {} } }
Hope you find it at least somewhat useful. If not, you haven't lost anything.
Bertie
[ November 17, 2004: Message edited by: Bertie Ramsbottom ]
[ November 17, 2004: Message edited by: Bertie Ramsbottom ]
I agree. Here's the link:
subject: Getting the free disk space
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/276998/java-io/java/free-disk-space | CC-MAIN-2014-42 | refinedweb | 1,061 | 50.33 |
On 02.07.2011 04:24, Greg Stein wrote:
Hey Greg,
thanks for the review.
> On Fri, Jul 1, 2011 at 15:04,<stefan2_at_apache.org> wrote:
>> ...
>> +++ subversion/branches/svn_mutex/subversion/include/private/svn_mutex.h Fri Jul 1 19:04:29 2011
>> ...
>> +#ifndef SVN_MUTEX_H
>> +#define SVN_MUTEX_H
>> +
>> +#include<apr_thread_mutex.h>
>> +#include "svn_error.h"
> Typical style is to put blank lines between the "natural groupings" of includes.
>
Fixed in r1142191.
>> +
>> +#ifdef __cplusplus
>> +extern "C" {
>> +#endif /* __cplusplus */
>> +
>> +/**
>> + * This is a simple wrapper around @c apr_thread_mutex_t and will be a
>> + * valid identifier even if APR does not support threading.
>> + */
> Actually, I don't think it will be valid: if !APR_HAS_THREADS, then
> you have an empty structure. I think some compiles will barf on that,
> so you probably want "int unused;" in that situation.
>
I got mislead with the whole struct thing. It is a simple
typedef now and much closer to APR (r1142191).
>> ...
>> +/** Initialize the @a *mutex with a lifetime defined by @a pool, if
>> + * @a enable_mutex is TRUE and with @c NULL otherwise. If @a enable_mutex
>> + * is set but threading is not supported by APR, this function returns an
>> + * @c APR_ENOTIMPL error.
>> + */
>> +svn_error_t *
>> +svn_mutex__init(svn_mutex__t *mutex,
>> + svn_boolean_t enable_mutex,
>> + apr_pool_t *pool);
>> +
>> +/** Acquire the @a mutex, if that has been enabled in @ref svn_mutex__init.
>> + * Make sure to call @ref svn_mutex__unlock some time later in the same
>> + * thread to release the mutex again. Recursive locking are not supported.
>> + */
>> +svn_error_t *
>> +svn_mutex__lock(svn_mutex__t mutex);
> In the Subversion source code, we generally do not pass structures as
> parameters. I'm not even sure if I can find an example. The code
> "always" passes a pointer-to-structure.
>
> This also has an impact on the signature for svn_mutex__init, and the
> unlock function, of course.
>
Same fix.
>> +/** Release the @a mutex, previously acquired using @ref svn_mutex__lock
>> + * that has been enabled in @ref svn_mutex__init.
>> + */
>> +svn_error_t *
>> +svn_mutex__unlock(svn_mutex__t mutex,
>> + svn_error_t *err);
>> +
>> +#ifdef __cplusplus
>> +}
>> +#endif /* __cplusplus */
> I agree with Daniel's suggestion to add a "with_lock" function that
> invokes a callback with the mutex held. That is probably the safest
> way to use the mutexes, and it will always guarantee they are unlocked
> (eg. in the face of an error). I see that you're accepting an ERR as a
> parameter on the unlock, presumably to try and handle these error-exit
> situations. My preference would be to completely omit the explicit
> lock/unlock functions, and *only* have the with_lock concept. I think
> it makes for better/safer code.
>
I understand what you guys are trying to achieve but
there seems to be no way to do it in a meaningful way.
r1142193 is an implementation for that and might be
useful in some situations.
In most cases, however, it will complicate things and
make the code less dependable. My preferred locking
style:
static svn_error_t *
bar()
{
... prepare parameters 1 to 4 ...
SVN_ERR(svn_mutex__lock(mutex));
return svn_mutex__unlock(mutex, foo(param1, param2, param3, param4));
}
Now the same using *__with_lock:
struct foo_params_t
{
T1 param1;
T2 param2;
T3 param3;
T4 param4;
};
static svn_error_t *
foo_void(void* baton)
{
struct foo_params_t * p = baton;
return foo(p->param1, p->param2, p->param3, p->param4);
}
static svn_error_t *
bar()
{
struct foo_params_t params;
... prepare parameters 1 to 4 ...
params.param1 = param1;
params.param2 = param2;
params.param3 = param3;
params.param4 = param4;
return svn_mutex__with_lock(mutex, foo_void, ¶ms);
}
Despite the obvious coding overhead, we also lose
type safety. So, I don't see an actual advantage in
a widespread use of the *__with_lock API.
Instead, we should strife to refactor functions such
that they lock and unlock only in one place. Then we
can use the initial pattern.
>> ...
>> +++ subversion/branches/svn_mutex/subversion/libsvn_subr/svn_mutex.c Fri Jul 1 19:04:29 2011
>> ...
>> +#else
>> + if (enable_mutex)
>> + return svn_error_wrap_apr(APR_ENOTIMPL, _("APR doesn't support threads"));
>> +#endif
> Euh. You can just return one of the SVN_ERR_ codes here. Wrapping an
> APR error doesn't make much sense :-P
>
> Maybe SVN_ERR_UNSUPPORTED_FEATURE ?
Done in r1142191 as well. IIRC, I took that line from
the original inprocess cache implementation.
-- Stefan^2.
Received on 2011-07-04 23:56:01 CEST
This is an archived mail posted to the Subversion Dev
mailing list. | https://svn.haxx.se/dev/archive-2011-07/0079.shtml | CC-MAIN-2017-39 | refinedweb | 678 | 58.99 |
Mac:
>>> import macropy.console 0=[]=====> MacroPy Enabled <=====[]=0 >>> from macropy.case_classes import macros, case >>> @case class Point(x, y): pass >>> p = Point(1, 2) >>> print p.x 1 >>> print p Point(1, 2)
Try it out in the REPL, it should just work! You can also see the docs/examples/using_macros folder for a minimal example of using MacroPy's existing macros.
MacroPy has been used to implement features such as:
As well as a number of more experimental macros such as:
Browse the high-level overview, or look at the Tutorials will go into greater detail and walk you through
The Reference Documentation contains information about:
Or just skip ahead to the Discussion and Conclusion. We're open to contributions, so send us your ideas/questions/issues/pull-requests and we'll do our best to accommodate you! You can ask questions on the Google Group or file bugs on thee issues page. See the changelist to see what's changed recently.
MacroPy is tested to run on CPython 2.7.2 and PyPy 2.0, but with only partial support for Python 3.X (You'll need to clone the python3 branch yourself) and no support for Jython. MacroPy is also available on PyPI, using a standard setup.py to manage dependencies, installation and other things. Check out this gist for an example of setting it up on a clean system.
Macro functions are defined in three ways:
from macropy.core.macros import * macros = Macros() @macros.expr def my_expr_macro(tree, **kw): ... return new_tree @macros.block def my_block_macro(tree, **kw): ... return new_tree @macros.decorator def my_decorator_macro(tree, **kw): ... return new_tree
The line
macros = Macros() is required to mark the file as providing macros, and the
macros object then provides the methods
expr,
block and
decorator which can be used to decorate functions to mark them out as the three different kinds of macros.
Each macro function is passed a
tree. The
tree is an
AST object, the sort provided by Python's ast module. The macro is able to do whatever transformations it wants, and it returns a modified (or even an entirely new)
AST object which MacroPy will use to replace the original macro invocation. The macro also takes
**kw, which contains other useful things which you may need.
These three types of macros are called via:
from my_macro_module import macros, my_expr_macro, my_block_macro, my_decorator_macro val = my_expr_macro[...] with my_block_macro: ... @my_decorator_macro class X(): ...
Where the line
from my_macro_module import macros, ... is necessary to tell MacroPy which macros these module relies on. Multiple things can be imported from each module, but
macros must come first for macros from that module to be used.
Any time any of these syntactic forms is seen, if a matching macro exists in any of the packages from which
macros has been imported from, the abstract syntax tree captured by these forms (the
... in the code above) is given to the respective macro to handle. The tree (new, modified, or even unchanged) which the macro returns is substituted into the original code in-place.
MacroPy intercepts the module-loading workflow, via the functionality provided by PEP 302: New Import Hooks. The workflow is roughly:
Note that this means you cannot use macros in a file that is run directly, as it will not be passed through the import hooks. Hence the minimum viable setup is:
# run.py import macropy.activate # sets up macro import hooks import other # imports other.py and passes it through import hooks # my_macro_module.py from macropy.core.macros import * macros = Macros() ... define some macros ... # other.py from macropy.macros.my_macro_module import macros, ... ... do stuff with macros ...
Where you run
run.py instead of
other.py. For the same reason, you cannot directly run MacroPy's own unit tests directly using
unittest or
nose: you need to run the macropy/run_tests.py file from the project root for the tests to run. See the runnable, self-contained no-op example to see exactly what this looks like, or the example for using existing macros.
MacroPy also works in the REPL:
PS C:\Dropbox\Workspace\macropy> python Python 2.7 (r27:82525, Jul 4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import macropy.console 0=[]=====> MacroPy Enabled <=====[]=0 >>> from macropy.tracing import macros, trace >>> trace[[x*2 for x in range(3)]] range(3) -> [0, 1, 2] x*2 -> 0 x*2 -> 2 x*2 -> 4 x*2 for x in range(3) -> [0, 2, 4] [0, 2, 4]
This example demonstrates the usage of the Tracing macro, which helps trace the evaluation of a Python expression. Although support for the REPL is still experimental, most examples on this page will work when copied and pasted into the REPL verbatim. MacroPy also works in the PyPy and IPython REPLs.
Below are a few example uses of macros that are implemented (together with test cases!) in the macropy and macropy/experimental folders. These are also the ideal places to go look at to learn to write your own macros: check out the source code of the String Interpolation or Quick Lambda macros for some small (<30 lines), self contained examples. Their unit tests demonstrate how these macros are used.
Feel free to open up a REPL and try out the examples in the console; simply
import macropy.console, and most of the examples should work right off the bat when pasted in! Macros in this section are also relatively stable and well-tested, and you can rely on them to work and not to suddenly change from version to version (as much as can be said for a two-month-old project!).
from macropy.case_classes import macros, case @case class Point(x, y): pass p = Point(1, 2) print str(p) # Point(1, 2) print p.x # 1 print p.y # 2 print Point(1, 2) == Point(1, 2) # True x, y = p print x, y # 1 2
Case classes are classes with extra goodies:
__str__and
__repr__methods autogenerated
__slots__declaration, to improve memory efficiency
__iter__method, to allow destructuring
The reasoning being that although you may sometimes want complex, custom-built classes with custom features and fancy inheritance, very (very!) often you want a simple class with a constructor, pretty
__str__ and
__repr__ methods, and structural equality which doesn't inherit from anything. Case classes provide you just that, with an extremely concise declaration:
@case class Point(x, y): pass
As opposed to the equivalent class, written manually:
class Point(object): __slots__ = ['x', 'y'] def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "Point(" + self.x + ", " + self.y + ")" def __repr__(self): return self.__str__() def __eq__(self, other): return self.x == other.x and self.y == other.y def __ne__(self, other): return not self.__eq__(other) def __iter__(self, other): yield self.x yield self.y
Whew, what a lot of boilerplate! This is clearly a pain to do, error prone to deal with, and violates DRY in an extreme way: each member of the class (
x and
y in this case) has to be repeated 8 times, with loads and loads of boilerplate. It is also buggy, and will fail at runtime when the above example is run, so see if you can spot the bug in it! Given how tedious writing all this code is, it is no surprise that most python classes do not come with proper
__str__ or useful
__eq__ functions! With case classes, there is no excuse, since all this will be generated for you.
Case classes also provide a convenient copy-constructor, which creates a shallow copy of the case class with modified fields, leaving the original unchanged:
a = Point(1, 2) b = a.copy(x = 3) print a # Point(1, 2) print b # Point(3, 2)
Like any other class, a case class may contain methods in its body:
@case class Point(x, y): def length(self): return (self.x ** 2 + self.y ** 2) ** 0.5 print Point(3, 4).length() # 5.0
or class variables. The only restrictions are that only the
__init__,
__repr__,
___str__,
__eq__ methods will be set for you, and the initializer/class body and inheritance are treated specially.
@case class Point(x, y): self.length = (self.x**2 + self.y**2) ** 0.5 print Point(3, 4).length # 5
Case classes allow you to add initialization logic by simply placing the initialization statements in the class body: any statements within the class body which are not class or function definitions are taken to be part of the initializer, and so you can use e.g. the
self variable to set instance members just like in a normal
__init__ method.
Any additional assignments to
self.XXX in the body of the class scope are detected and the
XXX added to the class'
__slots__ declaration, meaning you generally don't need to worry about
__slots__ limiting what you can do with the class. As long as there is an assignment to the member somewhere in the class' body, it will be added to slots. This means if you try to set a member of an instance via
my_thing.XXX = ... somewhere else, but aren't setting it anywhere in the class' body, it will fail with an AttributeError. The solution to this is to simply add a
self.XXX = None in the class body, which will get picked up and added to its
__slots__.
The body initializer also means you cannot set class members on a case class, as it any bare assignments
XXX = ... will get treated as a local variable assignment in the scope of the class'
__init__ method. This is one of several limitations.
*argsand
**kwargs
Case classes also provide a syntax for default values:
@case class Point(x | 0, y | 0): pass print str(Point(y = 5)) # Point(0, 5)
For
*args:
@case class PointArgs(x, y, [rest]): pass print PointArgs(3, 4, 5, 6, 7).rest # (5, 6, 7)
and
**kwargs:
@case class PointKwargs(x, y, {rest}): pass print PointKwargs(1, 2, a=1, b=2).rest # {'a': 1, 'b': 2}
All these behave as you would expect, and can be combined in all the normal ways. The strange syntax (rather than the normal
x=0,
*args or
**kwargs) is due to limitations in the Python 2.7 grammar, which are removed in Python 3.3.
Instead of manual inheritance, inheritance for case classes is defined by nesting, as shown below:
@case class List(): def __len__(self): return 0 def __iter__(self): return iter([]) class Nil: pass class Cons(head, tail): def __len__(self): return 1 + len(self.tail) def __iter__(self): current = self while len(current) > 0: yield current.head current = current.tail print isinstance(List.Cons(None, None), List) # True print isinstance(List.Nil(), List) # True my_list = List.Cons(1, List.Cons(2, List.Cons(3, List.Nil()))) empty_list = List.Nil() print my_list.head # 1 print my_list.tail # List.Cons(2, List.Cons(3, List.Nil())) print len(my_list) # 5 print sum(iter(my_list)) # 6 print sum(iter(empty_list)) # 0
This is an implementation of a singly linked cons list, providing both
head and
tail (LISP's
car and
cdr) as well as the ability to get the
len or
iter for the list.
As the classes
Nil are
Cons are nested within
List, both of them get transformed into case classes which inherit from it. This nesting can go arbitrarily deep.
Except for the
__init__ method, all the methods provided by case classes are inherited from
macropy.case_classes.CaseClass, and can thus be overriden, with the overriden method still accessible via the normal mechanisms:
from macropy.case_classes import CaseClass @case class Point(x, y): def __str__(self): return "mooo " + CaseClass.__str__(self) print Point(1, 2) # mooo Point(1, 2)
The
__init__ method is generated, not inherited. For the common case of adding additional initialization steps after the assignment of arguments to members, you can use the body initializer described above. However, if you want a different modification (e.g. changing the number of arguments) you can achieve this by manually defining your own
__init__ method:
@case class Point(x, y): def __init__(self, value): self.x = value self.y = value print Point(1) # mooo Point(1, 1)
You cannot access the replaced
__init__ method, due to fact that it's generated, not inherited. Nevertheless, this provides additional flexibility in the case where you really need it.
Case classes provide a lot of functionality to the user, but come with their own set of limitations:
foo = ...syntax. However,
@staticand
@classmethods work fine
macropy.case_classes.CaseClass, as well as any case classes it is lexically scoped within. There is no way to express any other form of inheritance
__slots__declarations by default. Thus you cannot assign ad-hoc members which are not defined in the class signature (the
class Point(x, y)line).
Overall, case classes are similar to Python's
namedtuple, but far more flexible (methods, inheritance, etc.), and provides the programmer with a much better experience (e.g. no arguments-as-space-separated-string definition). Unlike
namedtuples, they are flexible enough that they can be used to replace a large fraction of user defined classes, rather than being relegated to niche uses.
In the cases where you desperately need additional flexibility not afforded by case classes, you can always fall back on normal Python classes and do without the case class functionality.
from macropy.case_classes import macros, enum @enum class Direction: North, South, East, West print Direction(name="North") # Direction.North print Direction.South.name # South print Direction(id=2) # Direction.East print Direction.West.id # 3 print Direction.North.next # Direction.South print Direction.West.prev # Direction.East print Direction.all # [Direction.North, Direction.East, Direction.South, Direction.West]
MacroPy also provides an implementation of Enumerations, heavily inspired by the Java implementation and built upon Case Classes. These are effectively case classes with
name,
id,
nextand
prevfields
alllist, which enumerates all instances.
__new__method that retrieves an existing instance, rather than creating new ones
Note that instances of an Enum cannot be created manually: calls such as
Direction(name="North") or
Direction(id=2) attempt to retrieve an existing Enum with that property, throwing an exception if there is none. This means that reference equality is always used to compare instances of Enums for equality, allowing for much faster equality checks than if you had used Case Classes.
The instances of an Enum can be declared on a single line, as in the example above, or they can be declared on subsequent lines:
@enum class Direction: North South East West
or in a mix of the two styles:
@enum class Direction: North, South East, West
The basic rule here is that the body of an Enum can only contain bare names, function calls (show below), tuples of these, or function defs: no other statements are allowed. In turn the bare names and function calls are turned into instances of the Enum, while function defs (shown later) are turned into their methods. This also means that unlike Case Classes, Enums cannot have body initializers.
@enum class Direction(alignment, continents): North("Vertical", ["Northrend"]) East("Horizontal", ["Azeroth", "Khaz Modan", "Lordaeron"]) South("Vertical", ["Pandaria"]) West("Horizontal", ["Kalimdor"]) @property def opposite(self): return Direction(id=(self.id + 2) % 4) def padded_name(self, n): return ("<" * n) + self.name + (">" * n) # members print Direction.North.alignment # Vertical print Direction.East.continent # ["Azeroth", "Khaz Modan", "Lordaeron"] # properties print Direction.North.opposite # Direction.South # methods print Direction.South.padded_name(2) # <<South>>
Enums are not limited to the auto-generated members shown above. Apart from the fact that Enums have no constructor, and no body initializer, they can contain fields, methods and properties just like Case Classes do. This allows you to associate arbitrary data with each instance of the Enum, and have them perform as full-fledged objects rather than fancy integers.
from macropy.quick_lambda import macros, f, _ print map(f[_ + 1], [1, 2, 3]) # [2, 3, 4] print reduce(f[_ * _], [1, 2, 3]) # 6
Macropy provides a syntax for lambda expressions similar to Scala's anonymous functions. Essentially, the transformation is:
f[_ * _] -> lambda a, b: a * b
where the underscores get replaced by identifiers, which are then set to be the parameters of the enclosing
lambda. This works too:
print map(f[_.split(' ')[0]], ["i am cow", "hear me moo"]) # ['i', 'hear']
Quick Lambdas can be also used as a concise, lightweight, more-readable substitute for
functools.partial
from macropy.quick_lambda import macros, f basetwo = f[int(_, base=2)] print basetwo('10010') # 18
is equivalent to
import functools basetwo = functools.partial(int, base=2) print basetwo('10010') # 18
Quick Lambdas can also be used entirely without the
_ placeholders, in which case they wrap the target in a no argument
lambda: ... thunk:
from random import random thunk = f[random() * 2 + 3] print thunk() # 4.522011062548173 print thunk() # 4.894243231792029
This cuts out reduces the number of characters needed to make a thunk from 7 (using
lambda) to 2, making it much easier to use thunks to do things like emulating by name parameters. The implementation of quicklambda is about 30 lines of code, and is worth a look if you want to see how a simple (but extremely useful!) macro can be written.
from macropy.quick_lambda import macros, lazy # count how many times expensive_func runs count = [0] def expensive_func(): count[0] += 1 thunk = lazy[expensive_func()] print count[0] # 0 thunk() print count[0] # 1 thunk() print count[0] # 1
The
lazy macro is used to create a memoizing thunk. Wrapping an expression with
lazy creates a thunk which needs to be applied (e.g.
thunk()) in order to get the value of the expression out. This macro then memoizes the result of that expression, such that subsequent calls to
thunk() will not cause re-computation.
This macro is a tradeoff between declaring the value as a variable:
var = expensive_func()
Which evaluates exactly once, even when not used, and declaring it as a function
thunk = lambda: expensive_func()
Which no longer evaluates when not used, but now re-evaluates every single time. With
lazy, you get an expression that evaluates 0 or 1 times. This way, you don't have to pay the cost of computation if it is not used at all (the problems with variables) or the cost of needlessly evaluating it more than once (the problem with lambdas).
This is handy to have if you know how to compute an expression in a local scope that may be used repeatedly later. It may depend on many local variables, for example, which would be inconvenient to pass along to the point at which you know whether the computation is necessary. This way, you can simply
compute the lazy value and pass it along, just as you would compute the value normally, but with the benefit of only-if-necessary evaluation.
from macropy.quick_lambda import macros, interned # count how many times expensive_func runs count = [0] def expensive_func(): count[0] += 1 def func(): return interned[expensive_func()] print count[0] # 0 func() print count[0] # 1 func() print count[0] # 1
The
interned macro is similar to the Lazy macro in that the code within the
interned[...] block is wrapped in a thunk and evaluated at most once. Unlike the
lazy macro, however,
interned does not created a memoizing thunk that you can pass around your program; instead, the memoization is done on a per-use-site basis.
As you can see in the example above, although
func is called repeatedly, the
expensive_func() call within the
interned block is only ever evaluated once. This is handy in that it gives you a mechanism for memoizing a particular computation without worrying about finding a place to store the memoized values. It's just memoized globally (often what you want) while being scoped locally, which avoids polluting the global namespace with names only relevant to a single function (also often what you want).
from macropy.string_interp import macros, s a, b = 1, 2 print s["{a} apple and {b} bananas"] # 1 apple and 2 bananas
Unlike the normal string interpolation in Python, MacroPy's string interpolation allows the programmer to specify the variables to be interpolated inline inside the string. The macro
s then takes the string literal
"{a} apple and {b} bananas"
and expands it into the expression
"%s apple and %s bananas" % (a, b)
Which is evaluated at run-time in the local scope, using whatever the values
a and
b happen to hold at the time. The contents of the
{...} can be any arbitrary python expression, and is not limited to variable names:
from macropy.string_interp import macros, s A = 10 B = 5 print s["{A} + {B} = {A + B}"] # 10 + 5 = 15
from macropy.tracing import macros, log log[1 + 2] # 1 + 2 -> 3 # 3 log["omg" * 3] # ('omg' * 3) -> 'omgomgomg' # 'omgomgomg'
Tracing allows you to easily see what is happening inside your code. Many a time programmers have written code like
print "value", value print "sqrt(x)", sqrt(x)
and the
log() macro (shown above) helps remove this duplication by automatically expanding
log(1 + 2) into
wrap("(1 + 2)", (1 + 2)).
wrap then evaluates the expression, printing out the source code and final value of the computation.
In addition to simple logging, MacroPy provides the
trace() macro. This macro not only logs the source and result of the given expression, but also the source and result of all sub-expressions nested within it:
from macropy.tracing import macros, trace trace[[len(x)*3 for x in ["omg", "wtf", "b" * 2 + "q", "lo" * 3 + "l"]]] # "b" * 2 -> 'bb' # "b" * 2 + "q" -> 'bbq' # "lo" * 3 -> 'lololo' # "lo" * 3 + "l" -> 'lololol' # ["omg", "wtf", "b" * 2 + "q", "lo" * 3 + "l"] -> ['omg', 'wtf', 'bbq', 'lololol'] # len(x) -> 3 # len(x)*3 -> 9 # len(x) -> 3 # len(x)*3 -> 9 # len(x) -> 3 # len(x)*3 -> 9 # len(x) -> 7 # len(x)*3 -> 21 # [len(x)*3 for x in ["omg", "wtf", "b" * 2 + "q", "lo" * 3 + "l"]] -> [9, 9, 9, 21] # [9, 9, 9, 21]
As you can see,
trace logs the source and value of all sub-expressions that get evaluated in the course of evaluating the list comprehension.
Lastly,
trace can be used as a block macro:
from macropy.tracing import macros, trace with trace: sum = 0 for i in range(0, 5): sum = sum + 5 # sum = 0 # for i in range(0, 5): # sum = sum + 5 # range(0, 5) -> [0, 1, 2, 3, 4] # sum = sum + 5 # sum + 5 -> 5 # sum = sum + 5 # sum + 5 -> 10 # sum = sum + 5 # sum + 5 -> 15 # sum = sum + 5 # sum + 5 -> 20 # sum = sum + 5 # sum + 5 -> 25
Used this way,
trace will print out the source code of every statement that gets executed, in addition to tracing the evaluation of any expressions within those statements.
Apart from simply printing out the traces, you can also redirect the traces wherever you want by having a
log() function in scope:
result = [] def log(x): result.append(x)
The tracer uses whatever
log() function it finds, falling back on printing only if none exists. Instead of printing, this
log() function appends the traces to a list, and is used in our unit tests.
We think that tracing is an extremely useful macro. For debugging what is happening, for teaching newbies how evaluation of expressions works, or for a myriad of other purposes, it is a powerful tool. The fact that it can be written as a <100 line macro is a bonus.
from macropy.tracing import macros, require require[3**2 + 4**2 != 5**2] # Traceback (most recent call last): # File "<console>", line 1, in <module> # File "macropy.tracing.py", line 67, in handle # raise AssertionError("Require Failed\n" + "\n".join(out)) # AssertionError: Require Failed # 3**2 -> 9 # 4**2 -> 16 # 3**2 + 4**2 -> 25 # 5**2 -> 25 # 3**2 + 4**2 != 5**2 -> False
MacroPy provides a variant on the
assert keyword called
require(. Like
assert,
require throws an
AssertionError if the condition is false.
Unlike
assert,
require automatically tells you what code failed the condition, and traces all the sub-expressions within the code so you can more easily see what went wrong. Pretty handy!
`require can also be used in block form:
from macropy.tracing import macros, require with require: a > 5 a * b == 20 a < 2 # Traceback (most recent call last): # File "<console>", line 4, in <module> # File "macropy.tracing.py", line 67, in handle # raise AssertionError("Require Failed\n" + "\n".join(out)) # AssertionError: Require Failed # a < 2 -> False
This requires every statement in the block to be a boolean expression. Each expression will then be wrapped in a
require(), throwing an
AssertionError with a nice trace when a condition fails.
show_expanded
from ast import * from macropy.core.quotes import macros, q from macropy.tracing import macros, show_expanded print show_expanded[q[1 + 2]] # BinOp(left=Num(n=1), op=Add(), right=Num(n=2))
show_expanded is a macro which is similar to the simple
log macro shown above, but prints out what the wrapped code looks like after all macros have been expanded. This makes it extremely useful for debugging macros, where you need to figure out exactly what your code is being expanded into.
show_expanded also works in block form:
from macropy.core.quotes import macros, q from macropy.tracing import macros, show_expanded, trace with show_expanded: a = 1 b = q[1 + 2] with q as code: print a # a = 1 # b = BinOp(left=Num(n=1), op=Add(), right=Num(n=2)) # code = [Print(dest=None, values=[Name(id='a', ctx=Load())], nl=True)]
These examples show how the quasiquote macro works: it turns an expression or block of code into its AST, assigning the AST to a variable at runtime for other code to use.
Here is a less trivial example: case classes are a pretty useful macro, which saves us the hassle of writing a pile of boilerplate ourselves. By using
show_expanded, we can see what the case class definition expands into:
from macropy.case_classes import macros, case from macropy.tracing import macros, show_expanded with show_expanded: @case class Point(x, y): pass # class Point(CaseClass): # def __init__(self, x, y): # self.x = x # self.y = y # pass # _fields = ['x', 'y'] # _varargs = None # _kwargs = None # __slots__ = ['x', 'y']
Pretty neat!
If you want to write your own custom logging, tracing or debugging macros, take a look at the 100 lines of code that implements all the functionality shown above.
from macropy.peg import macros, peg from macropy.quick_lambda import macros, f """ PEG grammar from Wikipedia Op <- "+" / "-" / "*" / "/" Value <- [0-9]+ / '(' Expr ')' Expr <- Value (Op Value)* Simplified to remove operator precedence """ def reduce_chain(chain): chain = list(reversed(chain)) o_dict = { "+": f[_+_], "-": f[_-_], "*": f[_*_], "/": f[_/_], } while len(chain) > 1: a, [o, b] = chain.pop(), chain.pop() chain.append(o_dict[o](a, b)) return chain[0] with peg: op = '+' | '-' | '*' | '/' value = '[0-9]+'.r // int | ('(', expr, ')') // f[_[1]] expr = (value, (op, value).rep is rest) >> reduce_chain([value] + rest) print expr.parse("123") # 123 print expr.parse("((123))") # 123 print expr.parse("(123+456+789)") # 1368 print expr.parse("(6/2)") # 3 print expr.parse("(1+2+3)+2") # 8 print expr.parse("(((((((11)))))+22+33)*(4+5+((6))))/12*(17+5)") # 1804
MacroPEG is an implementation of Parser Combinators, an approach to building recursive descent parsers, when the task is too large for regexes but yet too small for the heavy-duty parser generators. MacroPEG is inspired by Scala's parser combinator library, utilizing python macros to make the syntax as clean as possible .
The above example describes a simple parser for arithmetic expressions, which roughly follows the PEG syntax. Note how that in the example, the bulk of the code goes into the loop that reduces sequences of numbers and operators to a single number, rather than the recursive-descent parser itself!
Any assignment (
xxx = ...) within a
with peg: block is transformed into a
Parser. A
Parser comes with a
.parse(input) method, which returns the parsed result if parsing succeeds and raises a
ParseError in the case of failure. The
ParseError contains a nice human-readable string detailing exactly what went wrong.
json_exp.parse('{"omg": "123", "wtf": , "bbq": "789"}') # ParseError: index: 22, line: 1, col: 23 # json_exp / obj / pair / json_exp # {"omg": "123", "wtf": , "bbq": "789"} # ^ # expected: (obj | array | string | true | false | null | number)
In addition to
.parse(input), a Parser also contains:
parse_string(input), a more program-friendly version of
parsethat returns successes and failures as boxed values (with metadata).
parse_partial(input)method, which is identical to
parse_string, but does not require the entire
inputto be consumed, as long as some prefix of the
inputstring matches. The
remainingattribute of the
Successindicates how far into the
inputstring parsing proceeded.
Parsers are generally built up from a few common building blocks. The fundamental atoms include:
'+'match the input to their literal value (e.g. '+') and return it as the parse result, or fails if it does not match.
'[0-9]+'.rmatch the regex to the input if possible, and return it.
('(', expr, ')')match each of the elements within sequentially, and return a list containing the result of each element. It fails if any of its elements fails.
|, for example
'+' | '-' | '*' | '/', attempt to match each of the alternatives from left to right, and return the result of the first success.
&, for example
'[1234]'.r & '[3456]'.r, require both parsers succeed, and return the result of the left side.
parser.repattempts to match the
parser0 or more times, returning a list of the results from each successful match.
-parsernegates the
parser: if
parsersucceeded (with any result),
-parserfails. If
parserfailed,
-parsersucceeds with the result
"", the empty string.
Apart from the fundamental atoms, MacroPeg also provides combinators which are not strictly necessary, but are nevertheless generally useful in almost all parsing scenarios:
parser.rep1attempts to match the
parser1 or more times, returning a list of the results from each successful match. If
parserdoes not succeed at least once,
parser.rep1fails. Equivalent to
parser.rep & parser.
parser.rep_with(other)and
parser.rep1_with(other)repeat the
parser0 or more or 1 or more times respectively, except now the
otherparser is invoked in between invocations of
parser. The output of
otheris discarded, and these methods return a list of values similar to
repand
rep1.
parser * nattempts to match the
parserexactly
ntimes, returning a list of length
ncontaining the result of the
nsuccesses. Fails otherwise.
parser.optmatches the
parser0 or 1 times, returning either
[]or
[result]where
resultis the result of
parser. Equivalent to
parser | Succeed([])
parser.jointakes a parser that returns a list of strings (e.g. tuples,
rep,
rep1, etc.) and returns a parser which returns the strings concatenated together. Equivalent to
parser // "".join.
//
So far, these building blocks all return the raw parse tree: all the things like whitespace, curly-braces, etc. will still be there. Often, you want to take a parser e.g.
from macropy.peg import macros, peg with peg: num = '[0-9]+'.r print repr(num.parse("123")) # '123'
which returns a string of digits, and convert it into a parser which returns an
int with the value of that string. This can be done with the
// operator:
from macropy.peg import macros, peg with peg: num = '[0-9]+'.r // int print repr(num.parse("123")) # 123
The
// operator takes a function which will be used to transform the result of the parser: in this case, it is the function
int, which transforms the returned string into an integer.
Another example is:
with peg: laugh = 'lol' laughs1 = 'lol'.rep1 laughs2 = laughs1 // "".join print laughs1.parse("lollollol") # ['lol', 'lol', 'lol] print laughs2.parse("lollollol") # lollollol
Where the function
"".join" is used to join together the list of results from
laughs1 into a single string. As mentioned earlier,
laughs2 can also be written as
laughs2 = laughs1.join.
>>
Although
// is sufficient for everyone's needs, it is not always convenient. In the example above, a
value is defined to be:
value = ... | ('(', expr, ')') // (lambda x: x[1])
As you can see, we need to strip off the unwanted parentheses from the parse tree, and we do it with a
lambda that only selects the middle element, which is the result of the
expr parser. An alternate way of representing this is:
value = ... | ('(', expr is result, ')') >> result
In this case, the
is keyword is used to bind the result of
expr to the name
result. The
>> (
bind) operator can be used to transform the parser by only operating on the bound results within the parser.
>> also binds the results of other parsers to their name. Hence the above is equivalent to:
value = ... | ('(', expr, ')') >> expr
The
expr on the left refers to the parser named
expr in the
with peg: block, while the
expr on the right refers to the results of the parser named
expr in case of a successful parse. The parser on the left has to be outside any
is expressions for it to be captured as above, and so in this line in the above parser:
expr = (value, (op, value).rep is rest) >> reduce_chain([value] + rest)
The result of the first
value on the left of
>> is bound to
value on the right, while the second
value is not because it is within an
is expression bound to the name
rest. If you have multiple parsers of the same name on the left of
>>, you can always refer to each individual explicitly using the
is syntax shown above.
Althought this seems like a lot of shuffling variables around and meddling with the local scope and semantics, it goes a long way to keep things neat. For example, a JSON parser may define an array to be:
with peg: ... # parses an array and extracts the relevant bits into a Python list array = ('[', (json_exp, (',', json_exp).rep), space.opt, ']') // (lambda x: [x[1][0]] + [y[1] for y in x[1][1]]) ...
Where the huge
lambda is necessary to pull out the necessary parts of the parse tree into a Python list. Although it works, it's difficult to write correctly and equally difficult to read. Using the
is operator, this can be rewritten as:
array = ('[', json_exp is first, (',', json_exp is rest).rep, space.opt, ']') >> [first] + rest
Now, it is clear that we are only interested in the result of the two
json_exp parsers. The
>> operator allows us to use those, while the rest of the parse tree (
[s,
,s, etc.) are conveniently discarded. Of course, one could go a step further and us the
rep_with method which is intended for exactly this purpose:
array = ('[', json_exp.rep_with(',') >> arr, space.opt, ']') >> arr
Which arguably looks the cleanest of all!
from macropy.peg import macros, peg, cut with peg: expr1 = ("1", "2", "3") | ("1", "b", "c") expr2 = ("1", cut, "2", "3") | ("1", "b", "c") print expr1.parse("1bc") # ['1', 'b', 'c'] print expr2.parse("1bc") # ParseError: index: 1, line: 1, col: 2 # expr2 # 1bc # ^ # expected: '2'
cut is a special token used in a sequence of parsers, which commits the parsing to the current sequence. As you can see above, without
cut, the left alternative fails and the parsing then attempts the right alternative, which succeeds. In contrast, with
expr2, the parser is committed to the left alternative once it reaches the
cut (after successfully parsing
1) and thus when the left alternative fails, the right alternative is not tried and the entire
parse fails.
The purpose of
cut is two-fold:
Using JSON as an example: if your parser sees a
{, begins parsing a JSON object, but some time later it fails, it does not need to both backtracking and attempting to parse an Array (
[...), or a String (
"...), or a Number. None of those could possibly succeed, so cutting the backtracking and failing fast prevents this unnecessary computation.
For example, if you try to parse the JSON String;
{ : "failed lol"}
if your JSON parser looks like:
with peg: ... json_exp = obj | array | string | num | true | false | null obj = '{', pair.rep_with(",") , space, '}' ...
Without
cut, the only information you could gain from attempting to parse that is something like:
index: 0, line: 1, col: 1 json_exp { : 1, "wtf": 12.4123} ^ expected: (obj | array | string | true | false | null | number)
On the other hand, using a
cut inside the
object parser immediately after parsing the first
{, we could provide a much more specific error:
index: 5, line: 1, col: 6 json_exp / obj { : 1, "wtf": 12.4123} ^ expected: '}'
In the first case, after failing to parse
obj, the
json_exp parser goes on to try all the other alternatives. After all to them fail to parse, it only knows that trying to parse
json_exp starting from character 0 doesn't work; it has no way of knowing that the alternative that was
supposed to work was
obj.
In the second case,
cut is inserted inside the
object parser, something like:
obj = '{', cut, pair.rep_with(",") , space, '}'
Once the first
{ is parsed, the parser is committed to that alternative. Thus, when it fails to parse
string, it knows it cannot backtrack and can immediately end the parsing. It can now give a much more specific source location (character 10) as well as better information on what it was trying to parse (
json / object / string)
MacroPEG is not limited to toy problems, like the arithmetic expression parser above. Below is the full source of a JSON parser, provided in the unit tests:
from macropy.peg import macros, peg, cut from macropy.quick_lambda import macros, f def decode(x): x = x.decode('unicode-escape') try: return str(x) except: return x escape_map = { '"': '"', '/': '/', '\\': '\\', 'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t' } """ Sample JSON PEG grammar for reference, shameless stolen from JSON <- S? ( Object / Array / String / True / False / Null / Number ) S? Object <- "{" ( String ":" JSON ( "," String ":" JSON )* / S? ) "}" Array <- "[" ( JSON ( "," JSON )* / S? ) "]" String <- S? ["] ( [^ " \ U+0000-U+001F ] / Escape )* ["] S? Escape <- [\] ( [ " / \ b f n r t ] / UnicodeEscape ) UnicodeEscape <- "u" [0-9A-Fa-f]{4} True <- "true" False <- "false" Null <- "null" Number <- Minus? IntegralPart fractPart? expPart? Minus <- "-" IntegralPart <- "0" / [1-9] [0-9]* fractPart <- "." [0-9]+ expPart <- ( "e" / "E" ) ( "+" / "-" )? [0-9]+ S <- [ U+0009 U+000A U+000D U+0020 ]+ """ with peg: json_doc = (space, (obj | array), space) // f[_[1]] json_exp = (space, (obj | array | string | true | false | null | number), space) // f[_[1]] pair = (string is k, space, ':', cut, json_exp is v) >> (k, v) obj = ('{', cut, pair.rep_with(",") // dict, space, '}') // f[_[1]] array = ('[', cut, json_exp.rep_with(","), space, ']') // f[_[1]] string = (space, '"', (r'[^"\\\t\n]'.r | escape | unicode_escape).rep.join is body, '"') >> "".join(body) escape = ('\\', ('"' | '/' | '\\' | 'b' | 'f' | 'n' | 'r' | 't') // escape_map.get) // f[_[1]] unicode_escape = ('\\', 'u', ('[0-9A-Fa-f]'.r * 4).join).join // decode> True> False> None number = decimal | integer integer = ('-'.opt, integral).join // int decimal = ('-'.opt, integral, ((fract, exp).join) | fract | exp).join // float integral = '0' | '[1-9][0-9]*'.r fract = ('.', '[0-9]+'.r).join exp = (('e' | 'E'), ('+' | '-').opt, "[0-9]+".r).join space = '\s*'.r
Testing it out with some input, we can see it works as we would expect:
test_string = """ { "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": 10021 }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ] } """ import json print json_exp.parse(test_string) == json.loads(test_string) # True import pprint pp = pprint.PrettyPrinter(4) pp.pprint(json_exp.parse(test_string)) #{ 'address': { 'city': 'New York', # 'postalCode': 10021.0, # 'state': 'NY', # 'streetAddress': '21 2nd Street'}, # 'age': 25.0, # 'firstName': 'John', # 'lastName': 'Smith', # 'phoneNumbers': [ { 'number': '212 555-1234', 'type': 'home'}, # { 'number': '646 555-4567', 'type': 'fax'}]}
You can see that
json_exp parses that non-trivial blob of JSON into an identical structure as Python's in-built
json package. In addition, the source of the parser looks almost identical to the PEG grammar it is parsing, shown above. This parser makes good use of the
// and
>> operators to transform the output of its individual components, as well as using
rep_with method to easily parse the comma-separated JSON objects and arrays. This parser is almost fully compliant with the test cases found on the json.org website (it doesn't fail, as it should, for deeply-nested JSON arrays), which isn't bad for 50 lines of code.
As mentioned earlier, MacroPEG parsers also provide exceptions with nice error messages when the
parse method fails, and the JSON parser is no exception. Even when parsing larger documents, the error reporting rises to the challenge:
json_exp.parse(""" { "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": 10021 }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": 646 555-4567" } ] } """) # ParseError: index: 456, line: 19, col: 31 # json_exp / obj / pair / json_exp / array / json_exp / obj # "number": 646 555-4567" # ^ # expected: '}'
Pretty neat! This full example of a JSON parser demonstrates what MacroPEG provides to a programmer trying to write a parser:
Not bad for an implementation that spans 350 lines of code!
Below are a selection of macros which demonstrate the cooler aspects of MacroPy, but are not currently stable or tested enough that we would be comfortable using them in production code.
from macropy.case_classes import macros, case from macropy.experimental.pattern import macros, switch @case class Nil(): pass @case class Cons(x, xs): pass def reduce(op, my_list): with switch(my_list): if Cons(x, Nil()): return x elif Cons(x, xs): return op(x, reduce(op, xs)) print reduce(lambda a, b: a + b, Cons(1, Cons(2, Cons(4, Nil())))) # 7 print reduce(lambda a, b: a * b, Cons(1, Cons(3, Cons(5, Nil())))) # 15 print reduce(Nil(), lambda a, b: a * b) # None
Pattern matching allows you to quickly check a variable against a series of possibilities, sort of like a switch statement on steroids. Unlike a switch statement in other languages (Java, C++), the
switch macro allows you to match against the inside of a pattern: in this case, not just that
my_list is a
Cons object, but also that the
xs member of
my_list is a
Nil object. This can be nested arbitrarily deep, and allows you to easily check if a data-structure has a particular
shape that you are expecting. Out of convenience, the value of the leaf nodes in the pattern are bound to local variables, so you can immediately use
x and
xs inside the body of the if-statement without having to extract it (again) from
my_list.
The
reduce function above (an simple, cons-list specific implementation of reduce) takes a Cons list (defined using case classes) and quickly checks if it either a
Cons with a
Nil right hand side, or a
Cons with something else. This is converted (roughly) into:
def reduce(my_list, op): if isinstance(my_list, Cons) and isinstance(my_list.xs, Nil): x = my_list.x return x elif isinstance(my_list, Cons): x = my_list.x xs = my_list.xs return op(x, reduce(xs, op))
Which is significantly messier to write, with all the
isinstance checks cluttering up the code and having to manually extract the values you need from
my_list after the
isinstance checks have passed.
Another common use case for pattern matching is working with tree structures, like ASTs. This macro is a stylized version of the MacroPy code to identify
with ...: macros:
def expand_macros(node): with switch(node): if With(Name(name)): return handle(name) else: return node
Compare it to the same code written manually using if-elses:
def expand_macros(node): if isinstance(node, With) \ and isinstance(node.context_expr, Name) \ and node.context_expr.id in macros.block_registry: name = node.context_expr.id return handle(name) else: return node
As you can see, matching against
With(Name(name)) is a quick and easy way of checking that the value in
node matches a particular shape, and is much less cumbersome than a series of conditionals.
It is also possible to use pattern matching outside of a
switch, by using the
patterns macro. Within
patterns, any left shift (
<<) statement attempts to match the value on the right to the pattern on the left, allowing nested matches and binding variables as described earlier.
from macropy.experimental.pattern import macros, patterns from macropy.case_classes import macros, case @case class Rect(p1, p2): pass @case class Line(p1, p2): pass @case class Point(x, y): pass def area(rect): with patterns: Rect(Point(x1, y1), Point(x2, y2)) << rect return (x2 - x1) * (y2 - y1) print area(Rect(Point(1, 1), Point(3, 3))) # 4
If the match fails, a
PatternMatchException will be thrown.
print area(Line(Point(1, 1), Point(3, 3))) # macropy.macros.pattern.PatternMatchException: Matchee should be of type <class 'scratch.Rect'>
When you pattern match
Foo(x, y) against a value
Foo(3, 4), what happens behind the
scenes is that the constructor of
Foo is inspected. We may find that it takes
two parameters
a and
b. We assume that the constructor then contains lines
like:
self.a = a self.b = b
We don't have access to the source of Foo, so this is the best we can do.
Then
Foo(x, y) << Foo(3, 4) is transformed roughly into
tmp = Foo(3,4) tmp_matcher = ClassMatcher(Foo, [NameMatcher('x'), NameMatcher('y')]) tmp_matcher.match(tmp) x = tmp_matcher.getVar('x') y = tmp_matcher.getVar('y')
In some cases, constructors will not be so standard. In this case, we can use
keyword arguments to pattern match against named fields. For example, an
equivalent to the above which doesn't rely on the specific implementation of th constructor is
Foo(a=x, b=y)
<< Foo(3, 4). Here the semantics are that the field
a is extracted from
Foo(3,4) to be matched against the simple pattern
x. We could also replace
x with a more complex pattern, as in
Foo(a=Bar(z), b=y) << Foo(Bar(2), 4).
It is also possible to completely override the way in which a pattern is matched
by defining an
__unapply__ class method of the class which you are pattern
matching. The 'class' need not actually be the type of the matched object, as
in the following example borrowed from Scala. The
__unapply__ method takes as
arguments the value being matched, as well as a list of keywords.
The method should then return a tuple of a list of positional matches, and a dictionary of the keyword matches.
class Twice(object): @classmethod def __unapply__(clazz, x, kw_keys): if not isinstance(x, int) or x % 2 != 0: raise PatternMatchException() else: return ([x/2], {}) with patterns: Twice(n) << 8 print n # 4
from macropy.experimental.tco import macros, tco @tco def fact(n, acc=0): if n == 0: return acc else: return fact(n-1, n * acc) print fact(10000) # doesn't stack overflow # 28462596809170545189064132121198688901...
Tail-call Optimization is a technique which will optimize away the stack usage of functions calls which are in a tail position. Intuitively, if a function A calls another function B, but does not do any computation after B returns (i.e. A returns immediately when B returns), we don't need to keep around the stack frame for A, which is normally used to store where to resume the computation after B returns. By optimizing this, we can prevent really deep tail-recursive functions (like the factorial example above) from overflowing the stack.
The
@tco decorator macro doesn't just work with tail-recursive functions, but
also with any generic tail-calls (of either a function or a method) via trampolining, such this mutually recursive example:
from macropy.experimental.tco import macros, tco class Example(object): @tco def odd(n): if n < 0: return odd(-n) elif n == 0: return False else: return even(n - 1) @tco def even(n): if n == 0: return True else: return odd(n-1) print Example().even(100000) # No stack overflow # True
Note that both
odd and
even were both decorated with
@tco. All functions
which would ordinarily use too many stack frames must be decorated.
How is tail recursion implemented? The idea is that if a function
f would
return the result of a recursive call to some function
g, it could instead
return
g, along with whatever arguments it would have passed to
g. Then
instead of running
f directly, we run
trampoline(f), which will call
f,
call the result of
f, call the result of that
f, etc. until finally some
call returns an actual value.
A transformed (and simplified) version of the tail-call optimized factorial would look like this
def trampoline_decorator(func): def trampolined(*args): if not in_trampoline(): return trampoline(func, args) return func(*args) return trampolined def trampoline(func, args): _enter_trampoline() while True: result = func(*args) with patterns: if ('macropy-tco-call', func, args) << result: pass else: if ignoring: _exit_trampoline() return None else: _exit_trampoline() return result @trampoline_decorator def fact(n, acc): if n == 0: return 1 else: return ('macropy-tco-call', fact, [n-1, n * acc])
from macropy.experimental.pinq import macros, sql, query, generate_schema from sqlalchemy import * # prepare database engine = create_engine("sqlite://") for line in open("macropy/experimental/test/world.sql").read().split(";"): engine.execute(line.strip()) db = generate_schema(engine) # Countries in Europe with a GNP per Capita greater than the UK results = query[( x.name for x in db.country if x.gnp / x.population > ( y.gnp / y.population for y in db.country if y.name == 'United Kingdom' ).as_scalar() if (x.continent == 'Europe') )] for line in results: print line # (u'Austria',) # (u'Belgium',) # (u'Switzerland',) # (u'Germany',) # (u'Denmark',) # (u'Finland',) # (u'France',) # (u'Iceland',) # (u'Liechtenstein',) # (u'Luxembourg',) # (u'Netherlands',) # (u'Norway',) # (u'Sweden',)
PINQ (Python INtegrated Query) to SQLAlchemy is inspired by C#'s LINQ to SQL. In short, code used to manipulate lists is lifted into an AST which is then cross-compiled into a snippet of SQL. In this case, it is the
query macro which does this lifting and cross-compilation. Instead of performing the manipulation locally on some data structure, the compiled query is sent to a remote database to be performed there.
This allows you to write queries to a database in the same way you would write queries on in-memory lists, which is really very nice. The translation is a relatively thin layer of over the SQLAlchemy Query Language, which does the heavy lifting of converting the query into a raw SQL string:. If we start with a simple query:
# Countries with a land area greater than 10 million square kilometers print query[((x.name, x.surface_area) for x in db.country if x.surface_area > 10000000)\ # [(u'Antarctica', Decimal('13120000.0000000000')), (u'Russian Federation', Decimal('17075400.0000000000'))]
This is to the equivalent SQLAlchemy query:
print engine.execute(select([country.c.name, country.c.surface_area]).where(country.c.surface_area > 10000000)).fetchall()
To verify that PINQ is actually cross-compiling the python to SQL, and not simply requesting everything and performing the manipulation locally, we can use the
sql macro to perform the lifting of the query without executing it:
query_string = sql[((x.name, x.surface_area) for x in db.country if x.surface_area > 10000000)] print type(query_string) # <class 'sqlalchemy.sql.expression.Select'> print query_string # SELECT country_1.name, country_1.surface_area # FROM country AS country_1 # WHERE country_1.surface_area > ?
As we can see, PINQ converts the python list-comprehension into a SQLAlchemy
Select, which when stringified becomes a valid SQL string. The
?s are there because SQLAlchemy uses parametrized queries, and doesn't interpolate values into the query itself.
Consider a less trivial example: we want to find all countries in europe who have a GNP per Capita greater than the United Kingdom. This is the SQLAlchemy code to do so:
query = select([db.country.c.name]).where( db.country.c.gnp / db.country.c.population > select( [(db.country.c.gnp / db.country.c.population)] ).where( db.country.c.name == 'United Kingdom' ).as_scalar() ).where( db.country.c.continent == 'Europe' )
The SQLAlchemy query looks pretty odd, for somebody who knows python but isn't familiar with the library. This is because SQLAlchemy cannot
lift Python code into an AST to manipulate, and instead have to construct the AST manually using python objects. Although it works pretty well, the syntax and semantics of the queries is completely different from python.
Already we are bumping into edge cases: the
db.country in the nested query is referred to the same way as the
db.country in the outer query, although they are clearly different! One may wonder, what if, in the inner query, we wish to refer to the outer query's values? Naturally, there will be solutions to all of these requirements. In the end, SQLAlchemy ends up effectively creating its own mini programming language, with its own concept of scoping, name binding, etc., basically duplicating what Python already has but with messier syntax and subtly different semantics.
In the equivalent PINQ code, the scoping of which
db.country you are referring to is much more explicit, and in general the semantics are identical to a typical python comprehension:
query = sql[( x.name for x in db.country if x.gnp / x.population > ( y.gnp / y.population for y in db.country if y.name == 'United Kingdom' ).as_scalar() if (x.continent == 'Europe') )]
As we can see, rather than mysteriously referring to the
db.country all over the place, we clearly bind it in two places: once to the variable
x in the outer query, once to the variable ` | https://recordnotfound.com/macropy-lihaoyi-9369 | CC-MAIN-2020-40 | refinedweb | 8,902 | 63.59 |
We all know .
In .NET, every object is allocated using Managed Heap. We call it managed as every object that is allocated within the .NET environment is in explicit observation of GC. When we start an application, it creates its own address space where the memory used by the application would be stored. The runtime maintains a pointer which points to the base object of the heap. Now as the objects are created, the runtime first checks whether the object can be created within the reserved space, if it can, it creates the object and returns the pointer to the location, so that the application can maintain a Strong Reference to the object. I have specifically used the term Strong Reference for the object which is reachable from the application. Eventually the pointer shifts to the next base address space.
When GC strikes with the assumption that all objects are garbage, it first finds all the Strong References that are global to the application, known as Application Roots and goes on object by object. As it moves from object to object, it creates a Graph of all the objects that it finds from the application Roots, such that every object in the Graph is unique. When this process is finished, the Graph will contain all the objects that are somehow reachable to the application. Now as the GC already identified the objects that are not garbage to the application, it goes on Compaction. It linearly traverses to all the objects and shifts the objects that are reachable to non reachable space which we call as Heap Compaction. As the pointers are moved during the Heap compaction, all the pointers are reevaluated again so that the application roots are pointing to the same reference again.
On each GC cycle, a large number of objects are collected to release the memory pressure of the application. As I have already stated, it finds all the objects that are somehow reachable to the Application Roots. The references that are not collected during the Garbage Collection are called StrongReference, as by the definition of StrongReference, the objects that are reachable to the GC are called StrongReference objects.
StrongReference
StrongReference
This creates a problem. GC is indeterminate. It randomly starts deallocating memory. So say if one have to work with thousand bytes of data at a time, and after it removes the references of the object, it had to rely on the time when GC strikes again and removes the reference. You can use GC.Collect to request the GC to start collecting, but this is also a request.
Finalize
trackResurrection
true
false
A WeakReference object takes the Strong Reference of an object as argument which you can retrieve using Target property. Let us look into the example:
Target
To demonstrate the feature, let's create a class which uses a lot of memory.
public class SomeBigClass : List<string
{
public SomeBigClass()
{
this.LoadBigObject();
}
private void LoadBigObject()
{
for (int i = 0; i < 100000; i++)
this.Add(string.Format("String No. {0}", i));
}
}
Clearly the SomeBigClass is a list of 100000 strings. The code looks very straight forward, as I have just created an alternative to define List<string>. Now let's create another class to show the actual implementation of the WeakReference class.
SomeBigClass
List<string>
public class WeakReferenceUsage
{
WeakReference weakref = null;
private SomeBigClass _somebigobject = null;
public SomeBigClass SomeBigObject
{
get
{
SomeBigClass sbo = null;
if (weakref == null) //When it is first time or object
//weakref is collected.
{
sbo = new SomeBigClass();
this.weakref = new WeakReference(sbo);
this.OnCallBack("Object created for first time");
}
else if (weakref.Target == null) // when target object is collected
{
sbo = new SomeBigClass();
weakref.Target = sbo;
this.OnCallBack("Object is collected by GC,
so new object is created");
}
else // when target object is not collected.
{
sbo = weakref.Target as SomeBigClass;
this.OnCallBack("Object is not yet collected,
so reusing the old object");
}
this._somebigobject = sbo; //gets you a strong reference
return this._somebigobject;
}
set
{
this._somebigobject = null;
}
}
# region GarbageEvent
public event Action<string CallBack;
public void OnCallBack(string info)
{
if (this.CallBack != null)
this.CallBack(info);
}
# endregion
}
In the above class, we define a reference of WeakReference as weakref, which holds the object of SomeBigClass. Now the property SomeBigClass has little logic defined within it. It uses the existing WeakReference.Target to fetch the existing object. If the Target is null, the object will again be recreated and stored within the WeakReference Target again.
weakref
SomeBigClass
WeakReference.Target
null
WeakReference Target
WeakReference serves as an exception to the existing GC algorithm. Even though the object is reachable from the application, it is still left for GC collection. So if GC strikes, it will collect the object of SomeBigClass and the WeakReference.Target will lose the reference.
WeakReference.Target
To demonstrate the class, let's create a Console application and create the object of WeakReferenceUsage. The example class looks like:
WeakReferenceUsage
static void Main(string[] args)
{
WeakReferenceUsage wru = new WeakReferenceUsage();
wru.CallBack += new Action<string(wru_CallBack);
while (true)
{
//Access somebigclass
foreach (string fetchstring in wru.SomeBigObject)
Console.WriteLine(fetchstring);
//fetch complete.
wru.SomeBigObject = null;
GC.Collect(); // request to collect garbage.
ConsoleKeyInfo info = Console.ReadKey();
if (info.Key == ConsoleKey.Escape)
break;
}
}
static void wru_CallBack(string obj)
{
Console.WriteLine(obj);
Console.Read();
}
Here in the Main method, I have created an object of WeakReferenceUsage, and registered the callback so that whenever we try to retrieve the object, the message will be displayed in the console.
Main
By setting:
wru.SomeBigObject = null;
GC.Collect(); // request to collect garbage.
will destroy the strong application reference and hence the object will be exposed for Garbage Collection. The call GC.Collect will request the garbage collection to collect.
Thus on first run, you will see:
The object is created for the first time.
After you fetch all the data, you might either receive the second message, saying that the object is not yet collected and the object is fetched from the existing WeakReference, or if you wait for a long time, you might receive the 3rd message which says that the object is Collected by GC and object is recreated.
You can download the sample application here.
I hope the article will help you to workaround on large objects. Thank you for reading.
Looking. | http://www.codeproject.com/Articles/100201/Garbage-Collection-Algorithm-with-the-use-of-WeakR?msg=3612470 | CC-MAIN-2015-22 | refinedweb | 1,041 | 57.98 |
Python Programming, news on the Voidspace Python Projects and all things techie.
Mocking patterns: chained calls, partial mocking and open as context manager
In recent weeks I've received two requests for help with mocking (and testing) chained calls. The mock library makes this easy, but I'm guessing that it isn't immediately obvious. At the same time I had a use case today for partially mocking out a class, and a user on Testing in Python asked about mocking the builtin open when it is used as a context manager. This blog entry shows these three patterns.
Mocking chained calls
Mocking chained calls is actually straightforward with mock once you understand the return_value attribute. When a mock is called for the first time, or you fetch its return_value before it has been called, a new Mock is created. (It can't be created whenever a mock is instantiated as otherwise the return value Mock would also need its return value creating, and so on ad infinitum.)
This means that you can see how the object returned from a call to a mocked object has been used by interrogating the return_value mock:
>>> from mock import Mock >>> mock = Mock() >>> mock().foo(a=2, b=3) >>> mock.return_value.foo.assert_called_with(a=2, b=3)
From here it is a simple step to configure and then make assertions about chained calls. Of course another alternative is writing your code in a more testable way in the first place...
'file:
def test_something_method(): something = Something() mock_response = Mock(spec=file) mock_backend = Mock() get_endpoint = mock_backend.get_endpoint create_call = get_endpoint.return_value.create_call start_call = create_call.return_value.start_call start_call.return_value = mock_response # monkeypatch the backend attribute something.backend = mock_backend something.method() get_endpoint.assert_called_with('foobar') create_call.assert_called_with('spam', 'eggs') start_call.assert_called_with() # make assertions on mock_response about how it is used
Keeping references to the intermediate methods makes our assertions easier, and also makes the code less ugly.
Partial mocking
Ok, so the title here is a bit weird. In some tests I wanted to mock out a call to datetime.date.today() to return a known date [1],) ... ... ...
Note that we don't patch datetime.date globally, we patch date in the module that uses it. This is a point that seems to confuse people when they start using patch. Obviously a point that needs making more strongly in the intro docs..
Mocking open
The soon-to-be-out-of-beta-unless-you-find-any-bugs version 0.7.0 of mock supports mocking magic methods. One of the things you can now do is use Mock to mock out objects used as context managers in a with statement.
The specific question was, what is the best way to mock out the use of the builtin open function in code that looks like this:
with open('/some/path') as f: f.write('something')
The issue is that even if you mock out the call to open it is the returned object that is used as a context manager (and has __enter__ and __exit__ called). So there are two parts two this question and one of them comes back to the ever wonderful return_value.
So first the topic of creating a mock object that can be called, with the return value able to act as a context manager. The easiest way of doing this is to use the new MagicMock class,):
>>> from mock import Mock, MagicMock >>>:
>>> with patch('module.open', create=True) as mock_open: ... mock_open.return_value = MagicMock(spec=file) ... with open('/some/path', 'w') as f: ... f.write('something') ... <mock.Mock object at 0x...> >>> file_handle = mock_open.return_value.__enter__.return_value >>> file_handle.write.assert_called_with('something')
Job done.
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2010-10-08 15:54:26 | |
Categories: Python, Hacking Tags: mock, testing, patterns
Archives
This work is licensed under a Creative Commons Attribution-Share Alike 2.0 License.
Counter... | http://www.voidspace.org.uk/python/weblog/arch_d7_2010_10_02.shtml | CC-MAIN-2018-51 | refinedweb | 645 | 57.37 |
My thoughts on Web Services and .NET development
One scenario that is very common in ASP.NET MVC is to bind form data (data posted with the media type application/x-www-form-urlencoded) to individual parameters or a form collection in a controller action. However, that scenario does not work quite the same in ASP.NET Web API as the body content is treated a forward-only stream that can only be read once.
If you define an action with multiple simple type arguments such as the one shown bellow, the model binding runtime will try to map those by default from the request URI (query string or route data).
public void Post(int id, string value)
{
}
That data never comes from the body content unless you decorate the argument with the [FromBody] attribute. However, only one argument in the action can be decorated with this attribute, and you get an exception when you try to decorate more than one. Nevertheless, the desired effect is far from what you would expect.
If you define an action as follow,
public void Post([FromBody]int id)
{
}
And you POST a form with the following data,
METHOD: POST
CONTENT-TYPE: application/x-www-form-urlencoded
BODY: id=4
Nothing will be mapped. It does not matter you defined a single parameter with the same as the one posted in the body.
If you really want to have a single type argument mapped to the body content, you have to POST a message with the following content
BODY: =4
As you can see, no key defined so the whole is mapped to our argument in the action. That’s the default behavior for single types. If you want to change that behavior, the framework is completely extensible and you can replace the whole model binding infrastructure included out of the box for one that you find more useful as it is explained here by Mike Stalls (which shows how you can replicate the same model used by ASP.NET MVC).
For complex types, the framework includes two MediaTypeFormatter implementations. The first one is FormUrlEncodedMediaTypeFormatter, which knows how to map every key/value in the form data to a FormDataCollection or a JTokenType (a dynamic type for expressing JSON available as part of the Json.NET library). These two are useful when you want to get access to all the values in form in a generic manner. You define for example a controller that receives a FormDataCollection instance like this,
public void Post(FormDataCollection form)
{
}
The second one is JQueryMvcFormUrlEncodedFormatter, which derives from the first one and knows how to map the form data to a concrete type representing a model. For example, a model defined as follow will match a body content with the keys “Id” and “Value”
public class MyModel
{
public int Id { get; set; }
public string Value { get; set; }
}
Therefore, your controller action can either receive a generic form collection (or a JTokenType) or a complex model type as any of these two will handle the deserialization of the body content type into the expected model. | http://weblogs.asp.net/cibrax/archive/2012/08.aspx | CC-MAIN-2014-10 | refinedweb | 515 | 53.55 |
Introduction
Seaborn is one of the most widely used data visualization libraries in Python, as an extension to Matplotlib. It offers a simple, intuitive, yet highly customizable API for data visualization.
In this tutorial, we'll take a look at how to plot a Distribution Plot in Seaborn. We'll cover how to plot a Distribution Plot with Seaborn, how to change a Distribution Plot's bin sizes, as well as plot Kernel Density Estimation plots on top of them and show distribution data instead of count data.
Import Data
We'll be using the Netflix Shows dataset and visualizing the distributions from there.
Let's import Pandas and load in the dataset:
import pandas as pd df = pd.read_csv('netflix_titles.csv')
How to Plot a Distribution Plot with Seaborn?
Seaborn has different types of distribution plots that you might want to use.
These plot types are: KDE Plots (
kdeplot()), and Histogram Plots (
histplot()). Both of these can be achieved through the generic
displot() function, or through their respective functions.
Note: Since Seaborn 0.11,
distplot() became
displot(). If you're using an older version, you'll have to use the older function as well.
Let's start plotting.
Plot Histogram/Distribution Plot (displot) with Seaborn
Let's go ahead and import the required modules and generate a Histogram/Distribution Plot.
We'll visualize the distribution of the
release_year feature, to see when Netflix was the most active with new additions:
import matplotlib.pyplot as plt import pandas as pd import numpy as np import seaborn as sns # Load the data df = pd.read_csv('netflix_titles.csv') # Extract feature we're interested in data = df['release_year'] # Generate histogram/distribution plot sns.displot(data) plt.show()
Now, if we run the code, we'll be greeted with a histogram plot, showing the count of the occurrences of these
release_year values:
Plot Distribution Plot with Density Information with Seaborn
Now, as with Matplotlib, the default histogram approach is to count the number of occurrences. Instead, you can visualize the distribution of each of these release_years in percentages.
Let's modify the
displot() call to change that:
# Extract feature we're interested in data = df['release_year'] # Generate histogram/distribution plot sns.displot(data, stat = 'density') plt.show()
The only thing we need to change is to provide the
stat argument, and let it know that we'd like to see the density, instead of the
'count'.
Now, instead of the count we've seen before, we'll be presented with the density of entries:
Change Distribution Plot Bin Size with Seaborn
Sometimes, the automatic bin sizes don't work very well for us. They're too big or too small. By default, the size is chosen based on the observed variance in the data, but this sometimes can't be different than what we'd like to bring to light.
In our plot, they're a bit too small and awkwardly placed with gaps between them. We can change the bin size either by setting the
binwidth for each bin, or by setting the number of
bins:
data = df['release_year'] sns.displot(data, binwidth = 3) plt.show()
This will make each bin encompass data in ranges of 3 years:
Or, we can set a fixed number of
bins:
data = df['release_year'] sns.displot(data, bins = 30) plt.show()
Now, the data will be packed into 30 bins and depending on the range of your dataset, this will either be a lot of bins, or a really small amount:
Another great way to get rid of the awkward gaps is to set the
discrete argument to
True:
data = df['release_year'] sns.displot(data, discrete=True) plt.show()
This results in:
Plot Distribution Plot with KDE
A common plot to plot alongside a Histogram is the Kernel Density Estimation plot. They're smooth and you don't lose any value by snatching ranges of values into bins. You can set a larger bin value, overlay a KDE plot over the Histogram and have all the relevant information on screen.
Thankfully, since this was a really common thing to do, Seaborn lets us plot a KDE plot simply by setting the
kde argument to
True:
data = df['release_year'] sns.displot(data, discrete = True, kde = True) plt.show()
This now results in:
Plot Joint Distribution Plot with Seaborn
Sometimes, you might want to visualize multiple features against each other, and their distributions. For example, we might want to visualize the distribution of the show ratings, as well as year of their addition. If we were looking to see if Netflix started adding more kid-friendly content over the years, this would be a great pairing for a Joint Plot.
Let's make a
jointplot():
df = pd.read_csv('netflix_titles.csv') df.dropna(inplace=True) sns.jointplot(x = "rating", y = "release_year", data = df) plt.show()
We've dropped null values here since Seaborn will have trouble converting them to usable values.
Here, we've made a Histogram plot for the rating feature, as well as a Histogram plot for the release_year feature:
We can see that most of the added entries are TV-MA, however, there's also a lot of TV-14 entries so there's a nice selection of shows for the entire family.
Conclusion
In this tutorial, we've gone over several ways to plot a distribution plot using Seaborn and Python.. | https://stackabuse.com/seaborn-distribution-histogram-plot-tutorial-and-examples/ | CC-MAIN-2021-17 | refinedweb | 895 | 61.97 |
I am using the svgwrite module in my Python code and I would like to set a background color. So far I have not been able to find anything. Is there a way to do it?
I was hoping for something during the initialization:
import svgwrite
canvas = svgwrite.drawing.Drawing(fill="#225566") # or background="#225566", or sth similar
canvas.save('image.png')
It seems that svg itself does not define how to set the background colour. For svgwrite I use this:
svg_size_width = 900 svg_size_height = 4500 dwg = svgwrite.Drawing(name, (svg_size_width, svg_size_height), debug=True) dwg.add(dwg.rect(insert=(0, 0), size=('100%', '100%'), rx=None, ry=None, fill='rgb(50,50,50)')) dwg.save() | https://codedump.io/share/w4ek3NAWonHg/1/python-svgwrite-module-background-color | CC-MAIN-2017-51 | refinedweb | 114 | 61.33 |
Every modern web application nowadays tends to have a requirement to upload files. This feature may be for uploading an avatar for a user profile or adding attachments.
File upload in GraphQL-ruby is a tricky problem. You can do file upload using multipart form request but GraphQL doesn’t allow multipart form request. I have spent countless hours to get multipart request working in GraphQL but the solution didn’t map the files properly in Active Storage so I had to let it go.
File upload can also be done using Direct Upload to the S3. We can achieve direct upload using two ways. We’ll discuss the best and the easiest way to achieve the direct upload in this blog.
Direct Upload using
@rails/activestorage
Firstly, install the Active Storage NPM package if not installed already.
yarn add @rails/activestorage # OR npm install @rails/activestorage
Now let’s build a simple react component to upload the profile picture. In the following example, we would consider the following example:
class User < ApplicationRecord has_one_attached :avatar end
import React, { Fragment, useState } from "react"; import { DirectUpload } from "@rails/activestorage"; const </Fragment> ) }
In the above component you need to take care of the following things:
- We have considered the
Usermodel with
avatarassociation. Please make sure to update the hidden input
nameattribute.
- If multiple files are attached, then direct upload all the files and generate the
ActiveStorage::Bloband send it with the
form_dataon form submit.
- The
form_dataon form submit should have
avatar: <blob.signed_id>value to associate the uploaded file in the database.
Happy Coding!! | https://www.abhaynikam.me/posts/active-storage-direct-file-upload-graphql-ruby/ | CC-MAIN-2020-40 | refinedweb | 261 | 54.63 |
ASF Bugzilla – Bug 39088
StandardWrapper getRootCause() infinite loop
Last modified: 2007-01-19 18:48:17 UTC
The "// Extra aggressive rootCause finding" in StandardWrapper.java is an
understatement. It causes an infinite loop in certain cases. For example, the
semantics of the following exception class are that getRootCause() returns the
one and only root cause of the exception chain, which in this case can be the
exception itself. It is not derived from ServletException, thus is not bound to
return null at the end of the chain as ServletException does. Its not safe to
use reflection to call an arbitrary method of an arbitrary Exception class, just
because it happens to have the same name as the method in ServletException.
public class MyException
extends Exception
{
public MyException(Throwable cause) {
this.cause = cause;
}
Throwable cause;
public Throwable getCause() {
return cause;
}
public Throwable getRootCause() {
if (cause instanceof VCOMException) {
return ((VCOMException) exception).getRootCause();
}
return cause == null ? this : cause;
}
}
Suggested patch?
(In reply to comment #1)
> Suggested patch?
Break out of the loop if cause == exception.
The problem is user code:
return cause == null ? this : cause;
If the root cause is null, then it should return null, not itself.
(In reply to comment #3)
> The problem is user code:
> return cause == null ? this : cause;
>
> If the root cause is null, then it should return null, not itself.
You can't control every exception class that could be thrown in user code. This
is getRootCause(), not getCause(). Lots of java code was written before Sun
added getCause() to Throwable and standardized exception chaining.
Tomcat calling getRootCause() of an arbitrary exception class is dangerous, as
the infinite loop demonstrates. It should either only call it on descendants of
ServletException and a few other known types, or at a minimum protect against
the infinite loop condition.
At best - here is the patch if any (not me) is interested ...
/container/catalina/src/share/org/apache/catalina/core/StandardWrapper.java
@@ -627,13 +627,14 @@
/**
* Extract the root cause from a servlet exception.
- *
+ *
* @param e The servlet exception
*/
public static Throwable getRootCause(ServletException e) {
Throwable rootCause = e;
Throwable rootCauseCheck = null;
// Extra aggressive rootCause finding
+ int recursionKlugeDetector = 20;
do {
try {
rootCauseCheck = (Throwable)IntrospectionUtils.getProperty
@@ -644,6 +645,16 @@
} catch (ClassCastException ex) {
rootCauseCheck = null;
}
+
+ /*
+ We've done this 20 times .. if you've nested more than
+ 20 levels of exceptions. Tomcat throwing the wrong exception
+ is the least of your concerns.
+ */
+
+ if (recursionKlugeDetector-- == 0) {
+ return rootCause;
+ }
} while (rootCauseCheck != null);
return rootCause;
}
see
Perhaps Tomcat should use the commons-lang ExceptionUtils root cause finding
that already fixes this problem... It appears to be superior to the // Extra
aggressive rootCause finding remification.
This issue has caused a production incident for us. It was rather tough to debug
given the fact that one would not expect that a getRootCause() method in a
non-Tomcat exception actually implements a (hidden) Tomcat interface. IMHO this
is very bad style.
A recursion detector does not address these issues:
1. Tomcat has no business calling a getRootCause() method in user code. That
method may have a very different contract than what Tomcat expects. It may have
side effects or it may be illegal to call the method in some cases. Because it
is not clear to a user that his getRootCause() method is called by Tomcat and
because exception paths are usually not tested that well, production incidents
are likely to still happen to some users.
2. The user still does not know that he is implementing a hidden Tomcat interface.
3. 20 recursions (or any arbitrary number) of reflection, with calls to a method
of unknown specifications may cause performance issues.
I believe that a similar fix to the one for bug 37038 is the best solution. That
fix would result in code that does not surprise Java developers, without the
problems outlined above. It is also unlikely that it would result in breakage,
since I don't think that it's likely that anyone took advantage of this
'feature' to implement some functionality.
Wouter, unfortunately nothing ever gets fixed in Tomcat. The people who can
make the changes think there shit doesn't stink, and unless they find the bug
and it affects them, it doesn't exist. The patch for this would be like 1
line of code, and the one Tim provided above (with the typical Tomcat
developer sarcastic asshole mentality) is almost worse than the current code.
I won't write a patch, and you shouldn't either. Noone will incorporate one
into the Tomcat codebase, ever, or let you put it in. They will give excuses
like, "if we fix it, it could break code that depends on it being broken".
Good luck.
it is for a called game Bots
I have fixed the infinite loop issue in svn by breaking out of the loop as
Jonathan suggested in comment 2. The fix will be in 5.5.21 onwards.
There are certainly more comprehensive ways of doing this, the commons-lang
approach is just one of them. If someone would like to provide a patch then I
would be happy to review it.
Mark,
Thanks for working on this issue. Your change still results in potentially
dangerous invocations of getRootCause on third-party classes, though. This fix
does not have that flaw and is much cleaner overall:
public static Throwable getRootCause(ServletException e) {
Throwable rootCause = e.getRootCause();
if (rootCause instanceof ServletException
&& rootCause != e) {
rootCause = getRootCause((ServletException) rootCause);
}
return rootCause;
}
Could you please review it?
Thanks for the suggested patch. Whilst it is safer, it also less likely to get
at the true root cause and I'd like to keep the behaviour of getting at the root
cause wherever possible.
Using commons-lang is one option but I'd rather not add yet another jar to the
build process. It should be possible to add the ExceptionUtils class to
o.a.c.util and use that. It looks like there might be some dependencies on other
commons-lang classes that would need to be coded around. If you want to take a
look at this - that would be great. If not, no problem and I'll look at it later
Mark,
If you really want the root cause, you should do this:
public static Throwable getRootCause(ServletException e) {
Throwable rootCause = e.getRootCause();
if (rootCause instanceof ServletException
&& rootCause != e) {
rootCause = getRootCause((ServletException) rootCause);
} else {
Throwable deepRootCause;
do {
deepRootCause = rootCause.getCause();
if (rootCause == deepRootCause) {
return rootCause;
} else if (deepRootCause != null) {
rootCause = deepRootCause;
}
} while (deepRootCause != null);
}
return rootCause;
}
This code is actually far more likely to find the true root cause and as an
added bonus, it uses API's whose implementation you should be able to trust.
That won't work since JspException does not extend ServletException and
JspException is typically the reason we wish to delve deeper into the real root
cause.
This issue is fixed in tomcat6 since getCause() and getRootCause() are
imlpemented as one in the same (since 1.5 jdk is required) but since tomcat
needs to be able to run on java 1.3 (shudders) - the getCause may not be
available for 1.3 implementations.
Remarking as fixed for now lness a better patch arrives.
Here is some code that works for both ServletException and
JspException:
public static Throwable getRootCause(ServletException e) {
Throwable rootCause = e.getRootCause();
return processRootCause(e, rootCause);
}
private static Throwable processRootCause(Exception e, Throwable rootCause) {
if (rootCause == null || rootCause == e) {
return e; //The root cause is a ServletException or JspException
}
if (rootCause instanceof ServletException) {
rootCause = getRootCause((ServletException) rootCause);
} else if (rootCause instanceof JspException) {
JspException jspRootCause = (JspException)rootCause;
Throwable deeperRootCause = jspRootCause.getRootCause();
rootCause = processRootCause(jspRootCause, deeperRootCause);
}
return rootCause; //The root cause is not a ServletException or JspException
}
Thanks for the new patch. I have committed a variation to svn and will be in
5.5.21 onwards. | https://bz.apache.org/bugzilla/show_bug.cgi?id=39088 | CC-MAIN-2015-32 | refinedweb | 1,300 | 55.84 |
A Halfedge has a double meaning. In the global incidence structure of a
Nef_polyhedron_3 it is an oriented edge going from one vertex to another.
A halfedge also coincides with an svertex of the sphere map of its source
vertex. Because of this, we offer the types Halfedge and SVertex
which are the same. Furthermore, the redundant functions center_vertex()
and source() are provided. The reason is, that we get the same vertex
either if we want to have the source vertex of a halfedge, or if we want to
have the vertex in the center of the sphere map a svertex lies on.
Figure
and
figure
illustrate the incidence of a svertex on a sphere map and of
a halfedge in the global structure.
As part of the global incidence structure, the member fuctions source and target return the source and target vertex of an edge. The member function twin() returns the opposite halfedge.
Looking at the incidence structure on a sphere map, the member function out_sedge returns the first outgoing shalfedge, and incident_sface returns the incident sface.
#include <CGAL/Nef_polyhedron_3.h>
The following types are the same as in Nef_polyhedron_3<Traits>.
There is no need for a user to create a Halfedge explicitly. The class Nef_polyhedron_3<Traits> manages the needed halfedges internally.
CGAL::Nef_polyhedron_3<Traits>::Vertex
CGAL::Nef_polyhedron_3<Traits>::SHalfedge
CGAL::Nef_polyhedron_3<Traits>::SFace
CGAL::Nef_polyhedron_S2<Traits>::Sphere_point | http://www.cgal.org/Manual/3.2/doc_html/cgal_manual/Nef_3_ref/Class_Nef_polyhedron_3-Traits---Halfedge.html | crawl-001 | refinedweb | 229 | 56.05 |
CodePlexProject Hosting for Open Source Software
As you may or may not have known, the new Task Parallel Library for .Net 4.0 is not currently available for the new .Net Compact Framework 3.7, which is what will be used on XBox360 and Windows Phone for the XNA 4.0 release. This library can't be installed
as a standalone library on either XBox360 nor WP7, so if you would like to see it make it to .NetCF3.7 as a pre-installed library (for example, to be able to use it in Box2D.XNA/Farseer for concurrency optimizations), then please vote for this XNA suggestion
on connect.microsoft.com:
Cool, they put together an Rx extensions installer for xna 3.1 xbox due to this feature request! Thanks everyone for voting!
Wait they made Rx for Xna 3.1, that's so awesome! Rx is amazing!
Yep. It's also available in Windows Phone 7 under a different namespace, but not yet for XBox in XNA 4.0.
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | http://farseerphysics.codeplex.com/discussions/222619 | CC-MAIN-2016-44 | refinedweb | 206 | 86.1 |
29 June 2012 18:56 [Source: ICIS news]
HOUSTON (ICIS)--Tronox has slowed production at its pigment plants as modest price increases for titanium dioxide (TiO2) are not enough to offset higher ore feedstock costs, the US-based producer said in an update on Friday.
Tronox CEO Tom Casey said that second-quarter ore costs are about $600/tonne (€480/tonne) above the first-quarter level.
“These added costs are not expected to be fully offset by the modestly higher average selling prices and essentially level sales volumes that the company is experiencing,” Casey said.
“Although we expect to realise modestly higher average selling prices sequentially in second quarter, we have seen prices in Europe, the Asia Pacific and to a lower degree other regions soften as a result of the demand in those regions lessening and supply not declining commensurately,” Casey said.
“We believe the largest contributing factors to the relative softness in demand stem from customer reactions to the continued macroeconomic slowdown in, and risks arising from, ?xml:namespace>
“In light of these sales trends and in order to control inventory levels, we have slowed production at our pigment plants resulting in less fixed-cost absorption,” he said.
As a result, Tronox estimates that its second-quarter adjusted earnings before interest, tax, depreciation and amortisation (EBIDTA) will be about 20% below the $151m it reported in the first quarter.
However, for the full year 2012 Tronox expects its pigment business to achieve average year-on-year selling price increase of about 15%, Casey said.
Casey added that outside of the Chinese market, which accounted for about 8% of Tronox’s sales over the last five years, the company has not seen any substantial lost sales to Chinese suppliers.
Also on Friday, the company announced a share repurchase programme.
While Tronox does not have a specific timetable or price targets for the programme, it expects to repurchase up to $150m worth of shares in the shorter term, followed by additional purchases following a new debt financing, it said.
“We believe our stock is undervalued at the present trading levels and therefore the best use of corporate resources is to invest in ourselves at these prices by repurchasing our shares," Casey said.
Tronox's share price was down $4.70, or 3.77%, to $119.91 at 12:42 on the New York Stock Exchange (NYSE).
The company returned to the stock exchange only last week after emerging from bankruptcy protection, but it immediately saw a sharp drop in its share price.
Additional reporting by Al Greenwood
( | http://www.icis.com/Articles/2012/06/29/9574204/us-tronox-slows-tio2-production-as-prices-lag-ore-costs.html | CC-MAIN-2013-48 | refinedweb | 427 | 56.89 |
Post your Comment
changing Chunk Color
changing Chunk Color
... is a method of FontFactory. We are changing the
color of the chunk...
change the color of chunk color .This example tell you how you can change
itext chunk
the contents of the Chunk are of the same font, fontsize, style,
color, etc... itext chunk
In this free tutorial we are going to tell you about
chunk in iText
Uses Of Chunk Object
Uses Of Chunk Object
... change
the background color and how we can create ...) and setBackground(Color
color) method to set the position of text
changing Background Color
changing Background Color
...
of any chunk with the help of setBackground(Color color).
In this example, we are creating a chunk then we use
setBackground(Color
jframe background color not showing
jframe background color not showing jframe background color is not showing. please suggest.
Just add the background color to JPanel and then add it to JFrame. For example ..
JFrame myFrame = new JFrame();
JPanel
changing selection color of
changing selection color of dear all,
i have loaded image in border less button tag when button is selected with tab key i get brown color rectangle around image. how do i change color of that rectangle from brown to white
HTML - table background color.
HTML - table background color.
Description :
Here, you will see how to specifies the table back ground color in html page.
The <table > is a html... the
background color of table.
Code :
<!DOCTYPE html PUBLIC "
random color fill
random color fill Hi I am trying to create a randomly color filled oval but the outcome is a black filled oval this is the code: package...);
g.fillOval(x, y, 200, 200);
Color randomColor = new Color(r, g1, b
uitableviewcell selected color
uitableviewcell selected color HI,
How to add uitableviewcell selected color?
Thanks
Hi,
Here is the code:
UIView *viewSelected = [[[UIView alloc] init] autorelease];
viewSelected.backgroundColor = [UIColor
Tetris Color - Swing AWT
Tetris Color I have created Tetris game in Swing but I want to delete row when 6 blocks of same colors so how can i retrieve color from different classes an t how to check condition
color changing - Java Beginners
color changing sir how to change the color of the selected tab in java swing Hi Friend,
Try the following code:
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.
How to set the Gradient Color as a background color for Java Frame?
How to set the Gradient Color as a background color for Java Frame? How to set the Gradient Color as a background color for Java Frame
HTML Color Code for White
HTML Color Code for White
In this page you will find the hexadecimal color code for White
color.
The hexadecimal color code for white is #FFFFFF or #ffffff.
For most website white color is used as the background of the web page
Java Code Color Function Error
Java Code Color Function Error Java Code Color Function Error
Post your Comment | http://roseindia.net/discussion/18403-changing-Chunk-Color.html | CC-MAIN-2016-18 | refinedweb | 500 | 60.95 |
QA utils library provides methods compatibility with all python versions
Project description
Python tested versions
How to install ?
- Install from PIP file : pip install qautils
- Install from setup.py file : python setup.py install
How to exec tests ?
- Tests from setup.py file : python setup.py test
Getting Started
Just starting example of usage before read Usage Guide.
from qautils.files import settings # file_path = './' by default SETTINGS = settings( file_path="/home/user/config/dir/", file_name="settings.json" ) KEY_TO_CHECK = "some_json_key_name" try: print(SETTINGS[KEY_TO_CHECK]) except Exception as err: print("ERROR: {}".format(err)) finally: bot.close()
Contributing
We welcome contributions to qautils! These are the many ways you can help:
- Submit patches and features
- Make qautils ( new updates for community )
- Improve the documentation for qautils
- Report bugs
- And donate !
Please read our documentation to get started. Also note that this project is released with a code-of-conduct , please make sure to review and follow it.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
qautils-0.0.2.tar.gz (28.0 kB view hashes) | https://pypi.org/project/qautils/ | CC-MAIN-2022-21 | refinedweb | 195 | 53.98 |
Hi Thomas,
Currently tracking data was minimum and was only used for statistics. For example, search keyword that client typed in search textbox, what's in search result that client clicked on,...
"IP-adresses stored when not using tracking?" - For your question, the answer is yes in history, no for now.
And for supporting GDPR, we already had a task for creating new APIs that query all information we tracked. So please wait for that.
Hope this help.
/Son Do
We've been asked some questions about the tracking that is used when enabling statistics in EPiFind:
These are visible on links in the search results whenever we enable the Track clicking:
The main issue here is the namespace and the IP-adress which can, contain sensitive information and our customer asked us to remove at least the IP-address. But this will break the tracking.
Can we send the trackingdata on the backend side in some programatic way so we can keep the URL clean? One idea was to make an async call to the above URL after user clicked but wondered if there was a more elegant way? | https://world.episerver.com/forum/developer-forum/EPiServer-Search/Thread-Container/2018/5/gdpr-and-epifind-tracking/ | CC-MAIN-2019-39 | refinedweb | 190 | 79.8 |
A new version of Toptal’s design system was released recently which required that we make changes to almost every component in Picasso, our in-house component library. Our team was faced with a challenge: How do we ensure that regressions don’t happen?
The short answer is, rather unsurprisingly, tests. Lots of tests.
We will not review the theoretical aspects of testing nor discuss different types of tests, their usefulness, or explain why you should test your code in the first place. Our blog and others have already covered those topics. Instead, we will focus solely on the practical aspects of testing.
Read on to learn how developers at Toptal write tests. Our repository is public, so we use real-world examples. There aren’t any abstractions or simplifications.
Testing Pyramid
We don’t have a testing pyramid defined, per se, but if we did it would look like this:
Toptal’s testing pyramid illustrates the tests we emphasize.
Unit Tests
Unit tests are straightforward to write and easy to run. If you have very little time to write tests, they should be your first choice.
However, they are not perfect. Regardless of which testing library you choose (Jest and React Testing Library [RTL] in our case), it won’t have a real DOM and it won’t allow you to check functionality in different browsers, but it will allow you to strip away complexity and test the simple building blocks of your library.
Unit tests don’t just add value by testing the behavior of the code but also by checking the overall testability of the code. If you can’t write unit tests easily, chances are you have bad code.
Visual Regression Tests
Even if you have 100% unit test coverage, that doesn’t mean the components look good across devices and browsers.
Visual regressions are particularly difficult to spot with manual testing. For example, if a button’s label is moved by 1px, will a QA engineer even notice? Thankfully, there are many solutions to this problem of limited visibility. You can opt for enterprise-grade all-in-one solutions such as LambdaTest or Mabl. You can incorporate plugins, like Percy, into your existing tests, as well as DIY solutions from the likes of Loki or Storybook (which is what we used prior to Picasso). They all have drawbacks: Some are too expensive while others have a steep learning curve or require too much maintenance.
Happo to the rescue! It’s a direct competitor to Percy, but it’s much cheaper, supports more browsers, and is easier to use. Another big selling point? It supports Cypress integration, which was important because we wanted to move away from using Storybook for visual testing. We found ourselves in situations where we had to create stories just so we could ensure visual test coverage, not because we needed to document that use case. That polluted our docs and made them more difficult to understand. We wanted to isolate visual testing from visual documentation.
Integration Tests
Even if two components have unit and visual tests, that’s no guarantee that they’ll work together. For example, we found a bug where a tooltip doesn’t open when used in a dropdown item yet works well when used on its own.
To ensure components integrate well, we used Cypress’s experimental component testing feature. At first, we were dissatisfied with the poor performance, but we were able to improve it with a custom webpack configuration. The result? We were able to use Cypress’s excellent API to write performant tests that ensure our components work well together.
Applying the Testing Pyramid
What does all this look like in real life? Let’s test the Accordion component!
Your first instinct might be to open your editor and start writing code. My advice? Spend some time understanding all the features of the component and write down what test cases you want to cover.
What to Test?
Here’s a breakdown of the cases our tests should cover:
- States – Accordions can be expanded and collapsed, its default state can be configured, and this feature can be disabled
- Styles – Accordions can have border variations
- Content – They can integrate with other units of the library
- Customization – The component can have its styles overridden and can have custom expand icons
- Callbacks – Every time the state changes, a callback can be invoked
How to Test?
Now that we know what we have to test, let’s consider how to go about it. We have three options from our testing pyramid. We want to achieve maximum coverage with minimal overlap between the sections of the pyramid. What’s the best way to test each test case?
- States – Unit tests can help us assess if the states change accordingly, but we also need visual tests to make sure the component is rendered correctly in each state
- Styles – Visual tests should suffice to detect regressions of the different variants
- Content – A combination of visual and integration tests is the best choice, as Accordions can be used in combination with many other components
- Customization – We can use a unit test to verify if a class name is applied correctly, but we need a visual test to make sure that the component and custom styles work in tandem
- Callbacks – Unit tests are ideal for ensuring the right callbacks are invoked
The Accordion Testing Pyramid
Unit Tests
The full suite of unit tests can be found here. We’ve covered all the state changes, the customization, and callbacks:
it('toggles', async () => { const handleChange = jest.fn() const { getByText, getByTestId } = renderAccordion({ onChange: handleChange, expandIcon: <span data- }) fireEvent.click(getByTestId('accordion-summary')) await waitFor(() => expect(getByText(DETAILS_TEXT)).toBeVisible()) fireEvent.click(getByTestId('trigger')) await waitFor(() => expect(getByText(DETAILS_TEXT)).not.toBeVisible()) fireEvent.click(getByText(SUMMARY_TEXT)) await waitFor(() => expect(getByText(DETAILS_TEXT)).toBeVisible()) expect(handleChange).toHaveBeenCalledTimes(3) })
Visual Regression Tests
The visual tests are located in this Cypress describe block. The screenshots can be found in Happo’s dashboard.
You can see all the different component states, variants, and customizations have been recorded. Every time a PR is opened, CI compares the screenshots that Happo has stored to the ones taken in your branch:
it('renders', () => { mount( <TestingPicasso> <TestAccordion /> </TestingPicasso> ) cy.get('body').happoScreenshot() }) it('renders disabled', () => { mount( <TestingPicasso> <TestAccordion disabled /> <TestAccordion expandIcon={<Check16 />} /> </TestingPicasso> ) cy.get('body').happoScreenshot() }) it('renders border variants', () => { mount( <TestingPicasso> <TestAccordion borders='none' /> <TestAccordion borders='middle' /> <TestAccordion borders='all' /> </TestingPicasso> ) cy.get('body').happoScreenshot() })
Integration Tests
We wrote a “bad path” test in this Cypress describe block that asserts the Accordion still functions correctly and that users can interact with the custom component. We also added visual assertions for extra confidence:
describe('Accordion with custom summary', () => { it('closes and opens', () => { mount(<AccordionCustomSummary />) toggleAccordion() getAccordionContent().should('not.be.visible') cy.get('[data-testid=accordion-custom-summary]').happoScreenshot() toggleAccordion() getAccordionContent().should('be.visible') cy.get('[data-testid=accordion-custom-summary]').happoScreenshot() }) // … })
Continuous Integration
Picasso relies almost entirely on GitHub Actions for QA. Additionally, we added Git hooks for code quality checks of staged files. We recently migrated from Jenkins to GHA, so our setup is still in the MVP stage.
The workflow is run on every change in the remote branch in sequential order, with the integration and visual tests being the last stage because they are most expensive to run (both in regard to performance and monetary cost). Unless all tests complete successfully, the pull request can not be merged.
These are the stages GitHub Actions goes through every time:
- Dependency installation
- Version control – Validates that the format of commits and PR title match conventional commits
- Lint – ESlint ensures good quality code
- TypeScript compilation – Verify there are no type errors
- Package compilation – If the packages can’t be built, then they won’t be released successfully; our Cypress tests also expect compiled code
- Unit tests
- Integration and visual tests
The full workflow can be found here. Currently, it takes less than 12 minutes to complete all the stages.
Testability
Like most component libraries, Picasso has a root component that must wrap all other components and can be used to set global rules. This makes it harder to write tests for two reasons—inconsistencies in test results, depending on the props used in the wrapper; and extra boilerplate:
import { render } from '@testing-library/react' describe('Form', () => { it('renders', () => { const { container } = render( <Picasso loadFavicon={false} <Form /> </Picasso> ) expect(container).toMatchSnapshot() }) })
We solved the first problem by creating a TestingPicasso that preconditions the global rules for testing. But it’s annoying to have to declare it for every test case. That’s why we created a custom render function that wraps the passed component in a TestingPicasso and returns everything available from RTL’s render function.
Our tests are now easier to read and straightforward to write:
import { render } from '@toptal/picasso/test-utils' describe('Form', () => { it('renders', () => { const { container } = render(<Form />) expect(container).toMatchSnapshot() }) })
Conclusion
The setup described here is far from perfect, but it’s a good starting point for those of you adventurous enough to create a component library. I’ve read a lot about testing pyramids, but it’s not always easy to apply them in practice. Therefore, I invite you to explore our codebase and learn from our mistakes and successes.
Component libraries are unique because they serve two kinds of audiences: the end users who interact with the UI and the developers who use your code to build their own applications. Investing time in a robust testing framework will benefit everyone. Investing time in testability improvements will benefit you as a maintainer and the engineers who use (and test) your library.
We didn’t discuss things like code coverage, end-to-end tests, and version and release policies. The short advice on those topics is: release often, practice proper semantic versioning, have transparency in your processes, and set expectations for the engineers that rely on your library. We may revisit these topics in more detail in subsequent posts.
Understanding the basics
A component library has two user groups: the engineers who build the UI with your library and the end-users who interact with it. Users care about good UI/UX, whereas developers need to be able to write integration tests between their apps and your components. As a maintainer, you must cater to both parties.
Changing a line of code can unexpectedly affect functionality that you didn't expect (a regression). Sometimes, though, the regression is only visual; the UI still works, but it doesn't look the same (a visual regression). Unit tests or E2E tests won't catch the bug, but a visual regression test should.
Keeping the UI consistent between releases is important for UX. Most automated tests don't interact with the UI, they manipulate it programmatically. They won't notice if a button changes color or if an image overflows the page. A user would notice though, and so would a visual regression test. | https://www.toptal.com/react/picasso-component-testing-library | CC-MAIN-2022-27 | refinedweb | 1,826 | 52.9 |
XPath and Regular Expressions
XPATHHello board members,
I need your help once more. I have an XML tag in my result structures that represents the "Date". The value of this tag
changes every time a new request comes to my server process. I added the Xpath to my global properties. In particular
my Xpath contains
/Envelope/Body/SomeWhere/In/Time/Date/,
/Envelope/Body/Eisai/Kati/Magiko/Date/,
/Envelope/Body/Opoios/Einai/Vazelos/Date/,
/Envelope/Body/Test/Date/
/Envelope/Body/Ekei/Ekei/Sthn/B_Ethniki/Date/
and so on, or sometimes "Date" is between two other tags for example
/Envelope/Body/Lefteris/Date/SOAP/
To be honest I would like to have my Xpath properties more compact. Eg */Date. Or /Envelope/*/Date but it is not working.
Do you know any other way that simplifies the representation of XPath?
Lefteris
0
The wild card replaces a specific (parent) element. Using /Envelope/*/Date, implies Date element is the third nested child, but that's not the case. You should use /Envelope/*/*/*/*/Date to replace the first Xpath in your list (/Envelope/Body/SomeWhere/In/Time/Date). You can then use /Envelope/*/*/*/Date to replace the second and third in your list, and so forth.
Hope that helps
You don't need to know the exact structure of the document or exactly how deep the Date element may be in the document. You don't need to use regular expressions, just use an XPath that is defined to search within any depth.
This will find an element with the tag name "Date" anywhere in the document.
//Date
Alternatively, you could use this:
/descendant::Date
If there are multiple Date elements in the document, the XPath will return a sequence of all of the elements.
There is a subtle difference between // and /descendant if you use indexes. If there are multiple Date elements in your document and you want to get only the first one, use this:
/descendant::Date[1]
The XPath //Date[1] could return multiple elements for subtle reasons that I won't touch here on unless someone asks.
If the Date element has a namespace, then the simplest XPaths you create can simply ignore the namespace using the prefix:tag format with "*" for the tag:
//*:Date
Or:
/descendant::*:Date
These will match elements with the tag name "Date" regardless of the namespace. | https://forums.parasoft.com/discussion/comment/7080/ | CC-MAIN-2019-43 | refinedweb | 390 | 60.55 |
#include <expression.h>
List of all members.
This context is passed along to the example::Driver class and fill during parsing via bison actions.
Definition at line 299 of file expression.h.
type of the variable storage
Definition at line 304 of file expression.h.
free the saved expression trees
Definition at line 314 of file expression.h.
References clearExpressions().
free all saved expression trees
Definition at line 320 of file expression.h.
References expressions.
Referenced by main(), and ~CalcContext().
check if the given variable name exists in the storage
Definition at line 330 of file expression.h.
Referenced by example::Parser::parse().
return the given variable from the storage.
throws an exception if it does not exist.
Definition at line 337 of file expression.h.
Referenced by example::Parser::parse().
variable storage. maps variable string to doubles
Definition at line 307 of file expression.h.
Referenced by existsVariable(), getVariable(), and example::Parser::parse().
array of unassigned expressions found by the parser.
these are then outputted to the user.
Definition at line 311 of file expression.h.
Referenced by clearExpressions(), main(), and example::Parser::parse(). | http://panthema.net/2007/flex-bison-cpp-example/flex-bison-cpp-example-0.1/doxygen-html/classCalcContext.html | CC-MAIN-2013-20 | refinedweb | 185 | 54.08 |
ASF Bugzilla – Bug 16001
Tag.release() not invoked
Last modified: 2005-05-23 04:34:06 UTC
I have a simple jsp page with a customer tag. During jsp execution, the release
method of the tag did not get invoked, which conflicts with J2EE spec.
The JSP spec requires that the release method is called before the tag is
allowed to pass to GC. With the default settings to enable tag-pooling, the
tag is returned to the pool, so the release method can't be called.
To get the behavior that you want, disable tag-pooling in
$CATALINA_HOME/conf/web.xml.
*** Bug 16031 has been marked as a duplicate of this bug. ***
The following is regarding bug 16031:
I assume you are referring to the tag handler's release() method when you talk
about resetting its state?
Note that according to the spec, the release() method is guaranteed to
be called on any tag handler, "but there may be multiple invocations
on doStartTag() and doEndTag() in between."
Therefore, your tag handler should not rely on its release() method to
reset any private invocation-specific state. This state is best
initialized in doStartTag(). This means that in your specific example, you
should clear your "key" and "value" objects in your tag handler's doStartTag()
method.
See important tips for tag-handler lifecycle management at
According to the spec, the release() method is guaranteed to be called on any
tag handler, this is to say, even when the tag handler instance is pooled, it
still should invoke release() to release any state the tag handler may posess.
In my case, I have a tag handler super class that needs to get a state value
from session and set it for the child class to construct business view object.
I agree that it is feasible to clean it up in doStartTag() since my tag is not
an iteration tag. But still it would be ideal to use release() to clean up
private invocation-specific state.
*** Bug 16071 has been marked as a duplicate of this bug. ***
Created attachment 4464 [details]
A war containing an example of the scenario in which the bug is exposed
I think that Tag.release is not invoked between two uses of the same tag, now
that it is extracted from the pool.
If the tag store a value in an internal variable, depending on a required
attribute, you'll find the previuos value in the next use even if you set it to
null in release.
I don't know if the life-cycle model of custom tags is changed in last
specifications, but I expect to have a clean instance of the object every time I
use it, especially if I've implemented release.
I've posted an attachment containing a small war with a simple tag and a page of
example. Try it.
You cannot put it to null. You have to make a call to removeValue(). Really you
SHOULD NOT do this, because we think that has to be done automatically :P
Lets see if I can get through to you guys, Jan Luehe's fine post was
apparently not enough.
From the Tag.release() javadoc:
"...there may be multiple invocations on doStartTag and doEndTag in between."
This is plain english and means that on the same page the tag can be taken out
of the pool, and then used several times _WITHOUT_ .release() being called in
between AND THIS IS NOT A BUG. Ergo, Tag.release can NOT be used for resetting
states between uses of tags.
If you need to reset your internal values that SHOULD be done in doEndTag for
instance.
I think that from a progammers view :
The programmers should not care about how internal things are done. That is, if
tomcat uses pools of objects for performance improvements or any other approach,
programmer should not care about it, it should only use a tag and if later it is
reused, asume a initial state.
Should not be this the right approach as done on other servers ?
As with any API, the programmer is supposed to understand how it works. I
didn't write the spec, but it is pretty obvious to me that it is working as
intended.
*** Bug 16171 has been marked as a duplicate of this bug. ***
As I understand the api, it does not talk about custom tag pools, it only speaks
about tags, if you use a pool, it should be transparent.
And in other servers it works as we think it should work.
Your tag does not comply with the JSP specification, and, as a result it may or
may not work. This issue WILL NOT be fixed in Tomcat.
Thanks, and DO NOT REOPEN THIS BUG.
Ismael,
Please take a look at section 10.5 in the 1.2 spec and section 12.4 in the 2.0
spec :
"Below is a somewhat complete example of the way one JSP container could
choose to do some tag handler management. There are many other strategies that
could be followed, with different pay offs.
The example is as below.."
As you can see pooling IS Mentioned. If you take a look at the example code that
follows this section you will see that release() is NOT called between tag
invocations.
The only thing that the spec says has to happen is that release() is called
before the tag is gc'd. This could potentialy only occur when an webcontainer is
shutdown.
I would suggest you take a look at a custom tag library like struts that
demontrates how custom tags should cleanup when used in a pooled environment.
Consider reading the rest of the spec as well...
Yes tags are meant to be pooled. However .release() is NOT intended to be
called between reuses of a tag... as the javadoc clearly states.
Even the name "release" tells us that this is not a "reinit".
Ok guys. You're right.
I found the book (about JSP 1.1) in which a flow-chart of the life-cycle of a
tag has driven me in error.
More, there are some JSP engine (such as Weblogic that has implemented the pool
before Tomcat) where release is invoke just after the return of doEndTag, even
if specification says different.
But specs rule!
A note from Hans Bergsten, for reference.
I'm in the EG and we had a long discussion about this again for JSP 2.0.
The end result is that the current behavior (do _not_ call release()
between invocations) will stay. A confusing arrow from the "released"
state to the "initialized" state in the state diagram will be removed,
however. This state transition came with lots and lots of restrictions,
but it seems like some vendor (and developers) saw it as a requirement
to call release() between invocations, even though the text clearly
state that that's not the case.
This is being discussed pretty much everywhere these days and I hope
people eventually will get it. I wrote about it in an article just
after JSP 1.2 was released. Feel free to point people to it if you
get tired of rehashing the same arguments over and over ;-)
<>
Page 2, the "Tag handler life cycle and instance reuse" section
Ok, thank you for your responses, I misinterpretted the specification. But I was
confused because on previous version of tomcat (4.1.12 I think) it seemed to
work as I thought it should work. I also tested on another servers and I got the
same behaviour.
Sorry, next time I will reread the specification before posting :)
*** Bug 17130 has been marked as a duplicate of this bug. ***
OK guys, release() method is NOT guaranteed to be called on any tag handler, so
..there may be multiple invocations on doStartTag and doEndTag in between.
But programmers needs a method to initialize the tag between uses. Initializing
it at doStartTag method is not OK because setters are called before doStartTag
so programmer could clear the setted variables.
We need a method to initialize the tag before it's called, Maybe changing the
get method get() at TagHandlerPool.java
If not, please great gurus, how can we use tag pooling without this
initialization issues. JSP spec is not clear about this!
public synchronized Tag get(Class handlerClass) throws JspException {
Tag handler = null;
if (current >= 0) {
handler = handlers[current--];
// If handler is already in the cache release it
// It cannot be done at startTag not at EndTag because closed tags can
// return a java object
handler.release();
} else {
try {
return (Tag) handlerClass.newInstance();
} catch (Exception e) {
throw new JspException(e.getMessage(), e);
}
}
return handler;
}
*** Bug 18349 has been marked as a duplicate of this bug. ***
I agree that initializing variables in doStartTag() doesn't make sense, since
the property sets are already called BEFORE doStartTag() according to the
spec. So, where does this leave the programmers a place to re-initialize the
veriables (most importantly the optional custom tag variables). I figure that
doAfterBody() is no good because it is called multiple times for BodyTag
handlers. So, the only place left is to override setPageContext() and have it
call super.setPageContext() AND release().
This is obviously a hack and doesn't seem like a good answer, but I don't see
any other choice. Is there one?
If you look through the comments for this "bug", the solution is defined by the
JSP spec: a tag handler instance can _not_ be reused for occurances of the
corresponding custom action that specify different optional attributes. Hence,
there's no risk that a tag handler that has been used with an optional attribute
is later used without that optional attribute. See this article for details:
<>
Page 2, the "Tag handler life cycle and instance reuse" section
Chris,
# doFinally() *is* always called for tag handlers that implement
TryCatchFinally, so this method should be used if any invocation- specific
resources need to be released
You could try using this to clear variables.
According to the JSP 1.1 Errata published on 5/31/00
( see under "Issue 14")
the behavior exhibited by Jasper (regarding tag pooling) is not in accordance
with the specification for JSP 1.1. The errata recognizes the shortcoming of the
original spec, which did not provide any mechanism for clearing the tag
handler’s state between uses, and it states that tag instances cannot be reused
if they don't correspond to actions with the same attributes, unless release()
is called between uses.
So, the same instance of the handler can be used for
<x:foo
<x:foo
but for
<x:foo
<x:foo
you either have to use different instances, or you have to call release() before
second use.
I would assume the same applies for JSP 1.2, unless the specification explicitly
states otherwise.
The errata is there for everyone to see right along side of the original final
specification
It's true that the 1.1 errata was included in the 1.2 Spec. However, it's not
relevent to this report. Jasper will use seperate instances of the "foo" tag
handler, which you've already agreed is valid.
Yep, you are right. I guess we're left with turning tag pooling off.
Many thanks!
*** Bug 26527 has been marked as a duplicate of this bug. ***
*** Bug 32957 has been marked as a duplicate of this bug. ***
*** Bug 34986 has been marked as a duplicate of this bug. *** | https://issues.apache.org/bugzilla/show_bug.cgi?id=16001 | CC-MAIN-2014-23 | refinedweb | 1,912 | 71.75 |
Finding Missing Value
By Malkit-Oracle on May 25, 2011
Often times it is required to find a missing number in large set, say of 32-bit integers (n), in random order. For example, integer numbers used as keys for some records and the missing key(s) could be reused for new allocations or to find missing data/holes in the data-set.
So, what is optimal way to find the missing value. Well, it depends. We have to further define the constraints. What is the size of data-set, how much virtual memory do we have - can the numbers be loaded into memory? What if we are constrained by the amount of memory but we have plenty of disk space. How about the case where we have some (limited) memory to partially fit in the input in memory. The optimal solution, as you might have guessed, depends on these constraints and this blog present various techniques that can be used to find the missing value for each of these cases. Mainly, following solutions for following three cases will be discussed. Also, we will note the running time for each.
- Plenty of virtual memory
- Very little virtual memory but plenty of disk space
- Some memory
Plenty of Virtual Memory
Solution 1
We can define a bit vector of size equal to n + 1 all initialized to 0. Then by looping through the input numbers, for a given number set the corresponding position in the bit set to 1. Finally, scanning the bit set for a value that is not set to 1 will give us the missing number. This solution of course assume that plenty of virtual memory available to represent the input set in bit array. The running time of this algorithm is O(n), not counting the time it takes to build the bit set.
Solution 2
Sort the input array and then using binary search find the missing value.
Solution 3
Another possible solution for the case where only one number is missing in a range of numbers would be to take sum of numbers (can be obtained using arithmetic series - S = n/2(a1 + an)) and then subtract each number from the sum of the range. The result would be missing number. We of course need to be careful that the sum does not overflow the maximum allowed for the data-type.
Very Little Virtual Memory
When we are limited by virtual memory and cannot load the input array into memory, we cannot do either bit check or sort, hence these solutions will not work. Assuming we have plenty of disk space, a solution similar to binary search (without the sort step) can be used to find missing number(s).
We will successively divide the input into two files half the size of input and write each to the disk. The trick is to divide the input into two halves based on most significant bit (MSB). One file will have all numbers with MSB value of 1 and other file with numbers starting with 0 as MSB. Each successive iteration will reduce the input array into half and the MSB for dividing the file will also move one step to right (towards least significant bit or LSB).
Since we know the maximum capacity for a given number of bits, the max elements for each half is known. Finding out the size of each file and knowing the total capacity, we can pick the half which has number of items less than the capacity and discard the other file. Note that it is possible that the other half also have missing numbers (the size less than the capacity), but since we are interested in finding a missing value (not all missing values), it does not matter which file (if the size of both is less than the capacity) we choose. Repeat the process over the selected file (now approx half the size) now considering the next MSB. Continue doing this till we have reached all but the last bit (LSB). At this point the input will have only one (or none) element remaining. Knowing the the possible values that can be represented for already found MSB, and the original item(s) remaining (for this range), we can easily find the missing number(s).
Also, note that in case there are range of missing values adjacent to each other, the solution may converge earlier and there is no need to traverse from MSB all the way to LSB.
Lets understand the above solution using simple example. Assume 4-bit integer (range 0 - 16) with missing value of 12 (1100). Here is the input set
input (integer) {5 7 15 8 1 9 4 0 3 10 13 6 14 2 11}
input (binary) {0101 0111 1111 1000 0001 1001 0100 0000 0011 1010 1101 0110 1110 0010 1011}
In the first pass, we serially read the input and divide it into two arrays based on most significant bit and write them to the disk
first file (bit 1xxx) {1111 1000 1001 1010 1101 1110 1011}
second file( bit 0xxx) {0101 0111 0001 0100 0000 0011 0110 0010}
Thus the two files sizes obtained are 7 (with MSB as 1) and 8 (MSB of 0). The max capacity of each being 8 (the total capacity ignoring the MSB).
Thus looking at the size of two files, it is clear that the first file contains the missing number. At this point we can discard the second file and repeat the above process for the first file using the second most significant bit to obtain two files:
first file (bit 11xx) {1111 1101 1110}
second file (bit 10xx) {1000 1001 1010 1011}
Above clearly suggests that the missing number must be in the range 1100 - 1111. Discarding the second file and repeating the same using the third most significant bit, we obtain following:
first file (bit 111x) {1111 1110}
second file (bit 110x) {1101}
This we conclude that the missing value is 1100 (the only remaining value for second file above).
In conclusion, the using the above mechanism we successively divided the input array into half. Thus for array of size n, we can find the missing value using log(n) passes, with each pass reducing the input size to n, n/2, n/4.....(geometric series sum = n/(1-1/2)= 2n) producing running time proportional to n.
Refer code at the end for implementation of above idea.
Some Memory
Where we do have some memory to work with, the solution could be hybrid of above. Check first few significant bit to reduce the problem size (input array) so that it is able to fit in the memory. Then you can employ any of the solution listed in Case 1 above. For example, for an input size of 232 (approx 4 billion values), checking 10 most significant bit can reduce the input to the order of 1000 (approx 4 million values) which might fit into memory.
Code
/* *. */ import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * The following program finds missing a value in input array. It takes an input * array and the bit size of the maximum value (the number of bits needed to * represent the represent max value) and returns missing number, if any. The * algorithm fully loads the input in memory and require additional memory of * size equal to input, however can be modified to work in limited memory * environment (refer comments in the end). * * Also, note the following: 1. In certain cases, the implementation might * return two contiguous missing values (as the case might be). 2. The utility * does not return all the missing values, but at least one value (assuming list * has missing values). 3. The bitSize parameter can be derived from input, but * that would require scanning the input to find the maximum value. * * The implementation works by inspecting the Most Significant bit and work like * binary search in that the input arrays is successively reduced to two halves * during iteration and then selects the one that is guaranteed to have at least * one missing value. * * The running time (asymptotic) of this algorithm is O(log(n)) which is much * better than sort followed by binary search (total of O(nlog(n) + log(n)). * * Another value of this algorithm is that for the case where the virtual memory * is limited and the input array cannot be fit into memory, modification of * this algorithm can be used to read the input stream and write the reduced * files back to file system with each step reducing the input size by half. * * @author Malkit S. Bhasin */ public class MissingNumber { /** * Returns a missing value (if any) in the input array. If none * is found, empty set is returned. * * @param input array of integers * @param bitSize the size of maximum value in input array * @return */ static Set
findMissing(int[] input, int bitSize) { if (bitSize < 0) { throw new IllegalArgumentException("bitSize value cannot be nagative"); } // convert the input array into list List list = asList(input); StringBuilder result = new StringBuilder(bitSize); // this represents the maximum capacity of half array // during successive iteration int maxCapacity = -1; // binary representation of int value String binary = null; // traversing from most significant bit (msb) to least significant bit (lsb) for (int i = 0; i < bitSize; i++) { // temp arrays to store values beginning with 1 bit and 0 bit // (for current bit index -> i) List ones = new ArrayList (); List zeros = new ArrayList (); // Calculate max number of values that can fit in 'ones' and 'zeros' array maxCapacity = (int) Math.pow(2, bitSize - (i + 1)); for (int j = 0; j < list.size(); j++) { binary = toBinaryString(list.get(j), bitSize); if (binary.charAt(i) == '1') { ones.add(list.get(j)); } else { zeros.add(list.get(j)); } } if (ones.size() < maxCapacity) { // this indicate that there is definitely at least one missing value // in this array (ones array). Note that this does not mean // that there is no missing value in zeros array. Since we just // to find a missing value, we dont have to check other array.. // As we progress through the msb to lsb, we collect the bits // in result which will be used later to find the missing value result.append("1"); list = ones; } else if (zeros.size() < maxCapacity) { // indicate that the missing value in zeros array result.append("0"); list = zeros; } else { // no missing element.. return empty set return new HashSet (); } // this means that successive reduction of input array // has resulted in array of size 1 or even 0 (the case // where both the elements are missing - see test3 below..) if (list.size() <= 1) { return getMissingInt(list, result.toString(), bitSize); } } return new HashSet (); } /** * Here the passed list is the values for a narrow range which has * other value(s) missing. The logic works by find all the values * that will fit in this range then striking off the values that * are already present in this range (as identified by list). * * @param list * @param result * @param bitSize * @return */ private static Set getMissingInt(List list, String result, int bitSize) { Set resultSet = getValuesForRange(result, bitSize); for (Integer i : list) { resultSet.remove(i); } return resultSet; } /** * Returns all possible values for a given partially filled most significant bits. * The method is passed binary string containing most significant bits for total bitSize. * For example, if the result value is "110" and bitSize is 4, this means * that the possible values that can fit in are "1100" and "1101" and these * will be returned as result. * * @param result * @param bitSize * @return */ private static Set getValuesForRange(String result, int bitSize) { String start = padRight(result, bitSize).replace(' ', '0'); String end = padRight(result, bitSize).replace(' ', '1'); int startInt = Integer.valueOf(start, 2); int endInt = Integer.valueOf(end, 2); Set resultSet = new HashSet (); for (int i = startInt; i <= endInt; i++) { resultSet.add(i); } return resultSet; } private static List asList(int[] input) { List list = new ArrayList (); for (int index = 0; index < input.length; index++) { list.add(input[index]); } return list; } private static String padRight(String s, int n) { return String.format("%-" + n + "s", s); } /** * Converts the input integer to equivalent binary string representation. * Also, the returned value is left padded with 0's. * @param value * @param bitSize * @return */ private static String toBinaryString(int value, int bitSize) { String binary = Integer.toBinaryString(value); binary = (String.format("%" + bitSize + "s", binary)).replace(' ', '0'); return binary; } private static void printResult(String testName, Set result) { System.out.printf("%6s: %-10s %n", testName, result); } /** * @param args */ public static void main(String[] args) { // the following test has one element (2) missing, 2 bits are sufficient to // represent largest value (3) int[] input1 = {0, 1, 3}; printResult("test1", findMissing(input1, 2)); // the following test has one element - 12 missing int[] input2 = {5, 7, 15, 8, 1, 9, 4, 0, 3, 10, 13, 6, 14, 2, 11}; printResult("test2", findMissing(input2, 4)); // the list has two elements - 12, 13 missing int[] input3 = {5, 7, 15, 8, 1, 9, 4, 0, 3, 10, 6, 14, 2, 11}; printResult("test3", findMissing(input3, 4)); // the list has maximum value of 31, which means it needs at least 5 bits. The missing value is 15 int[] input4 = {5, 7, 8, 1, 9, 4, 0, 3, 10, 13, 6, 14, 2, 11, 12, 16, 17, 19, 18, 21, 20, 23, 22, 25, 24, 27, 26, 29, 28, 31, 30}; printResult("test4", findMissing(input4, 5)); // here all the values from 0 - 28 are present, but the input array needs 5 bits (because // maximum value is 28). The utility returns missing value(s) that can fit in this // bit range (29, 30, 31). This is by design. If strictly values between the // lower and upper values of input are needed, the implementation can scan through // the input to find the min and max and return missing values between this range. int[] input5 = {5, 7, 8, 1, 9, 4, 0, 3, 10, 13, 6, 14, 2, 11, 12, 16, 17, 19, 18, 21, 20, 23, 22, 25, 24, 27, 26, 28}; printResult("test5", findMissing(input5, 5)); } } | https://blogs.oracle.com/malkit/category/Algorithms | CC-MAIN-2016-22 | refinedweb | 2,334 | 58.82 |
How do you secure the larger stand-alone developments that run within Smart Office? This is a question that I have had to ask on some developments. Because your development isn’t native M3 code you can’t secure it through the traditional SES400 or SES003 methods.
So how do you allow some users access to some functions but not others, or just read access, rather than read/write?
We can build our own security model, but then we have to store this information somewhere. Creating a whole database UI and associated webservices is horribly expensive. We can store it in a configuration file on the M3 UI Adapter server – but this makes maintaining it pretty difficult.
Or we can use the MNS405 roles. This had been something that I had traditionally ignored as IFL didn’t use MNS405 (or SES400 security) – we were stuck using SES003 and menu security. But when I was engaged on another customer project I decided to take a little time to investigate.
Under the UserContext.Roles we have a list of the roles that a user is in from MNS410. So what I tend to do these days is create roles for my applications in MNS405, and then assign the operator to that role in MNS410. You application can query the UserContext.Roles to see if the desired role(s) exist and provide or restrict access as appropriate.
A user can belong to multiple roles.
Figure 1 – the roles that an user can be assigned to
Figure 2 – a user assigned to a role in MNS410
You can add roles and associations without using role based security. And it means that your customer can manage your applications security within familiar M3 panels and programs and it really provides an extremely quick and easy way for you to add and check security.
And to test
I’m only assigned to one role, but if I was assigned to multiple roles I would see them listed.
And of-course, a post wouldn’t be complete without some code…
import System; import System.Windows; import System.Windows.Controls; import MForms; package MForms.JScript { class viewRoles { public function Init(element: Object, args: Object, controller : Object, debug : Object) { debug.WriteLine(UserContext.Roles.Count); for(var i = 0; i < UserContext.Roles.Count; i++) { debug.WriteLine("Role: " + UserContext.Roles[i].Role + " Name: " + UserContext.Roles[i].Name + " Description: " + UserContext.Roles[i].Description); } } } }
As Thibaud notes below in the comments, this isn’t designed as a method to replace M3 security as it can be circumvented.
Indeed, that is a quick and easy way to check “security”; more specifically it’s authorization (who has access to what).
For the disadvantages of this way (you probably already know this but readers may not), by design users have the ability to disable personalizations which includes scripts, unless the administrator disables that ability but that would defeat the purpose of personalizations. You could use MForms extensions instead, but they don’t apply to H5 Client nor M3 APIs, . The best and only solution is still M3 security with SES400 (or whatever the new name these days). It’s an endeavor to setup. Infor Smart Data Tool has spreadsheets that make it less of a burden to setup.
Quite right. I was pitching the technique to secure your own developments, typically stand-alone, which you cannot secure through SES003 or SES400.
I’ve updated the article to be a little clearer. 🙂
Thanks Thibaud.
what is a good ways to get report from MNS405/410/ses400 all together..like what user role connected to which user and how many functions he has access….other than creating SQL query from DB
I’m not aware of any predefined reports to get this information.
You might be able to pull something out of the adhoc reporting (AHS100) but I haven’t taken a good look.
thank you I’ll check….. | https://potatoit.kiwi/2015/09/15/adding-security-to-your-development/ | CC-MAIN-2017-39 | refinedweb | 650 | 56.55 |
SPOKA Night Light controlled from and Android Phone
January 13, 2012 133 Comments
You people must have been wondering “what the heck was going on” and why haven’t I posted anything for the last 3 months or so… keep reading and you’ll find out more !
Some of you must have already seen something like this:
It’s an Ikea Spoka night light and my wife really loves them… to the point that a while back she bought several of them, “just in case”…
We obviously only use one, so I’ve gotten her permission a few months ago to open another one up and play with it.
This project started actually back at the beginning of October 2011, but after doing the hardest part of it (reverse engineering the simple circuit) I had to abandon it in favour of the Stanford Artificial Intelligence and Machine Learning courses, which took most of my week-ends !
Then my son was born at the end of November, and here I am, more than 3 months later, having decided that I need to do whatever it takes to finish the project and post it.
I’m trying to do this while waiting for some special “mega servos” that I plan to use to automate my baby’s bouncer (those of you that have babies, know how important it is to rock them while they try to fall asleep, and what is the phonic price to be paid if not careful… 🙂 ).
So here we go…
Originally, the lamp has 2 modes, that you can select with a switch at the top (which can also turn it off):
- slowly change between the 3 available colours (blue, red and orange) while dimming the intensity
-.
It could also lead to having more than 1 lamp synchronised, but this would be for another project…
The first idea was to use these 2 simple wireless transceivers and control the Spoka from my PC.
Then it dawned on me that it would be much nicer to control it from my phone, and what better choice than the IOIO to interface Android with the serial transceiver… ?
And then, I can’t remember how, I found these ultra cheap serial bluetooth transceivers… There are plenty of them on various sites (I got mine from ebay for 5£) and they all seem more or less the same…
Not only it’s much cheaper than a IOIO + the RF transceivers, but it’s also quite small and especially, it doesn’t require anything to be wired to the phone (since then the IOIO also supports bluetooth, but then it would mean to integrate one in the Spoka which is not an option…).
However, as you’ll see later in this post (and as Ytai told me from the beginning 🙂 ), this advantages come at a price, as the module seems more fiddly and there’s hardly any documentation out there !
Anyhow, the thought of having this little thing integrated in the Spoka and then being able to remotely control it from my phone, felt worth the effort !
1. Reverse engineer the light
Thank you Ikea for having easily hackable, through hole boards !
2. Replace the IC with a custom one
The original IC was a 8 pin one and I would have really liked to be able to just “drop” in my own ATtiny45 or 85. This however proved impossible due to a different pin layout.
There was also the need for serial communication with the bluetooth module and 3 independent PWM for the 3 colours. While I’m sure an experienced AVR engineer could fit all this on an ATtiny 45, the thought of implementing software serial and struggle with the conflicts with the PWM timers, didn’t sound good and hence I opted for a 20pin ATtiny2313 that I had lying around and that provides hardware serial.
The job of the new MCU will be quite simple:
- wait for incoming serial data containing the intensity of each colour (and a checksum)
- provide some acknowledgement on the serial line
- update the PWM values accordingly
And here’s the C code.
Notice that I have actually implemented 2 modes:
- if the first character is a ‘#’ then you simply provide the intensity for each colour
- if the first character is a ‘*’ then you provide a delay only, and the MCU does the transitioning from one colour to the other (similarly to what the original setup was doing, but with the extra feature of being able to change the speed of transition)
/* * uart.h * * Created: 09/10/2011 Author: trandi */ #ifndef UART_H_ #define UART_H_ //BRR = (F_CPU / 16 / BaudRate ) - 1 #define BAUD_RATE_38400 (F_CPU / 16 / 38400 ) - 1 #define BAUD_RATE_4800 (F_CPU / 16 / 4800 ) - 1 #define BAUD_RATE_2400 (F_CPU / 16 / 2400 ) - 1 void uart_init(unsigned char baudrate); uint8_t uart_isCharAvailable(); unsigned char uart_getChar(); void uart_putChar(unsigned char data); void uart_putStr(const char* str); //void uart_putw_dec(uint16_t w); #endif /* UART_H_ */ /* * uart.c * * Created: 02/10/2011 Author: trandi */ #include <avr/io.h> #include <util/delay.h> void uart_init(unsigned char baudrate) { UBRRL = baudrate; // Set the baud rate UCSRB = _BV(RXEN) | _BV(TXEN); // Enable UART receiver and transmitter UCSRC = _BV(UCSZ1) | _BV(UCSZ0); // set to 8 data bits, 1 stop bit DDRD |= _BV(PD1); // TZ is output DDRD &= ~_BV(PD0); // RX is input } uint8_t uart_isCharAvailable() { return (UCSRA & _BV(RXC)); } unsigned char uart_getChar() { while(! uart_isCharAvailable()) _delay_ms(10); char result = UDR; //useful echo uart_putChar(result); return result; } void uart_putChar(unsigned char data){ /* Wait for empty transmit buffer */ while (!(UCSRA & _BV(UDRE))); /* Start transmission */ UDR = data; } void uart_putStr(const char* str) { while(*str){ uart_putChar(*str++); } } /* void uart_putw_dec(uint16_t w) { uint16_t num = 10000; uint8_t started = 0; while(num > 0){ uint8_t b = w / num; if(b > 0 || started || num == 1){ uart_putChar('0' + b); started = 1; } w -= b * num; num /= 10; } }*/ /* * SpokaLight.cpp * * Created: 01/10/2011 Author: trandi */ #define F_CPU 8000000UL #include <avr/io.h> #include <util/delay.h> #include "uart.h" #define PWM1 OCR0A //PB2 #define PWM2 OCR1B //PB3 #define PWM3 OCR1A //PB4 #define BLUE 0 #define RED 1 #define ORANGE 2 #define BUTTON_PORT PORTB // PORTx - register for button output #define BUTTON_PIN PINB // PINx - register for button input #define BUTTON_BIT PB1 // bit for button input/output /* n = (f / prescaler) * t Where n is the the number of timer ticks (as written in ICR1, OCR1A, OCR1B above). f is the frequency you run the AVR at. t is the wanted time. You can compute this with f in Hz and t in seconds or often better with f in MHz and t in microseconds. Notice for an 8MHz AVR with /8 prescaler this becomes n = 8/8*t -> n = t */ void init_pwm(){ // OC1A, OC1B, OC0A outputs DDRB |= (1<<PB4)|(1<<PB3)|(1<<PB2); // TIMER 0 // Fast PWM mode 3, Clear on compare, clear at TOP // TOP set for 255 TCCR0A = (1<<COM0A0)|(1<<COM0A1)|(1<<WGM01)|(1<<WGM00); TCCR0B = (1<<CS00); // TIMER 1 // TOP, set for 255Hz ICR1 = 255; // Fast PWM mode 14, Clear on compare, clear at TOP TCCR1A = (1<<COM1A0)|(1<<COM1A1)|(1<<COM1B0)|(1<<COM1B1)|(1<<WGM11); TCCR1B = (1<<WGM13)|(1<<WGM12)|(1<<CS10); } void set_pwm(uint8_t colour, uint8_t value){ uint8_t mapped_value = 255 - value; if(colour == BLUE) PWM3 = mapped_value; else if(colour == RED) PWM1 = mapped_value; else if(colour == ORANGE) PWM2 = mapped_value; } uint8_t button_is_pressed() { // the button is pressed when BUTTON_BIT is clear if (bit_is_clear(BUTTON_PIN, BUTTON_BIT)) { _delay_ms(25); // debounce time if (bit_is_clear(BUTTON_PIN, BUTTON_BIT)) { // wait for it to unclear before releasing... ! while(bit_is_clear(BUTTON_PIN, BUTTON_BIT)) _delay_ms(10); return 1; } } return 0; } // mode 0 - off / 1 - static colours / 2 - dynamic colours volatile uint8_t _mode = 1; volatile uint8_t _blue = 50, _red = 50, _orange = 50; volatile uint8_t _currCol = BLUE, _currVal = 1, _dirUp = 1; volatile uint16_t _interval = 30, _count = 0; void update_status(){ if(_mode == 0 ){ set_pwm(BLUE, 0); set_pwm(RED, 0); set_pwm(ORANGE, 0); }else if(_mode == 1){ set_pwm(BLUE, _blue); set_pwm(RED, _red); set_pwm(ORANGE, _orange); }else if(_mode == 2){ set_pwm(BLUE, 0); set_pwm(RED, 0); set_pwm(ORANGE, 0); } } void update_dynamics(){ // after 100 the intensity of LEDs seems to level off if(_currVal == 100) _dirUp = 0; else if(_currVal == 0) { _dirUp = 1; _currCol = (_currCol + 1) % 3; } _count ++; if(_count >= _interval){ _count = 0; _currVal = _dirUp ? _currVal + 1 : _currVal - 1; if(_mode == 2){ set_pwm(_currCol, _currVal); } } } uint8_t percToByte(uint8_t perc){ uint16_t temp = perc * 255; return temp / 100; } int main(void){ init_pwm(); uart_init(BAUD_RATE_38400); while(1){ // 1. check for instructions over serial line if(uart_isCharAvailable()){ uint8_t temp = uart_getChar(); if(temp == '#'){ _mode = 1; uart_putStr("BRO "); uint8_t blue = uart_getChar(); uint8_t red = uart_getChar(); uint8_t orange = uart_getChar(); uint8_t checksum = uart_getChar(); //very basic check sum, it simply has to be = to the SUM of prev values, modulo 100 if(checksum == ((uint16_t)blue + (uint16_t)red + (uint16_t)orange) % 100){ uart_putStr("OK"); _blue = percToByte(blue); _red = percToByte(red); _orange = percToByte(orange); update_status(); }else{ uart_putStr("Nok"); } }else if(temp == '*'){ // go in mode "dynamic" _mode = 2; uart_putStr("Interval "); _interval = ((uint16_t)uart_getChar()) * 50; _currCol = BLUE; _currVal = 1; update_status(); } } // 2. check for button pressed or not if(button_is_pressed()){ _mode = (_mode + 1) % 3; update_status(); } // 3. do whatever periodic action is needed update_dynamics(); // 4. get some rest //_delay_ms(1); } }
3. Connect the bluetooth transceiver
4. Program the Android phone
This was (and still is) quite frustrating…
I love Android and its ease of programming in Java ! They really make your life much easier by providing everything one needs … Unless something doesn’t work as expected that is !
In my case, it was a matter of hours before I put together a simple view, like a joystick with 3 axes. It’s a simple gray dot that the user can move relative to 3 coloured circles, each corresponding to a set of LEDs on the lamp, which is supposed to update its intensity accordingly.
All the “back end” needs to do, is to measure the distance between the gray circle and the other 3 “reference” ones, transform this into a percentage and send it across the serial bluetooth line to the MCU.
Everything works nicely, EXCEPT the bluetooth serial port profile connection.
First of all, when I test the connection from the PC, there are no issues what so ever.
On Android however, I get garbled characters most of the time and sometimes the right one. It really feels like a timing issue…
I’ve based my code on the example coming with the Android SDK. The sending of bytes is done in the main thread, but the receiving has its own dedicated one.
The really strange thing is that depending on how and when I transform the bytes into a String, the code works or not…
If I disable the receiving thread and I only send data from the phone to the MCU, then it works 95% of the time, which again makes me think that it’s a timing issue on the Android side.
That’s for now the status, I basically send the instructions from the phone, and do NOT wait for the acknowledgement from the ATtiny.
Here’s the code. Ytai, you must have spend quite a lot of time on this yourself when bluetooth enabling the IOIO, if you have any idea or suggestion, it would be hugely appreciated !
BTDeviceListActivity.java ------------------------------------------------------- package trandi.spokalightbluetooth; import java.util.Set; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; /** * This Activity appears as a dialog. It lists any paired devices and * devices detected in the area after discovery. When a device is chosen * by the user, the MAC address of the device is sent back to the parent * Activity in the result Intent. */ public class BTDeviceListActivity extends Activity { // Debugging private static final String TAG = "BTDeviceListActivity"; // Return Intent extra public static String EXTRA_DEVICE_ADDRESS = "device_address"; // Member fields private BluetoothAdapter _btAdapter; private ArrayAdapter<String> _pairedDevicesArrayAdapter; private ArrayAdapter<String> _newDevicesArrayAdapter; // The BroadcastReceiver that listens for discovered devices and changes the title when discovery is finished private final BroadcastReceiver _receiver = new BroadcastReceiver() { @Override); // If it's already paired, skip it, because it's been listed already if (device.getBondState() != BluetoothDevice.BOND_BONDED) { _newDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } // When discovery is finished, change the Activity title } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { setProgressBarIndeterminateVisibility(false); setTitle(R.string.select_device); if (_newDevicesArrayAdapter.getCount() == 0) { _newDevicesArrayAdapter.add(getResources().getText(R.string.none_found).toString()); } } } }; // The on-click listener for all devices in the ListViews private OnItemClickListener _deviceClickListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<!--?--> av, View v, int arg2, long arg3) { // Cancel discovery because it's costly and we're about to connect _btAdapter.cancelDiscovery(); // Get the device MAC address, which is the last 17 chars in the View String info = ((TextView) v).getText().toString(); String address = info.substring(info.length() - 17); // Create the result Intent and include the MAC address Intent intent = new Intent(); intent.putExtra(EXTRA_DEVICE_ADDRESS, address); // Set result and finish this Activity setResult(Activity.RESULT_OK, intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Setup the window requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.device_list); // Set result CANCELED incase the user backs out setResult(Activity.RESULT_CANCELED); // Initialize the button to perform device discovery Button scanButton = (Button) findViewById(R.id.button_scan); scanButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { doDiscovery(); v.setVisibility(View.GONE); } }); // Initialize array adapters. One for already paired devices and one for newly discovered devices _pairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name); _newDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name); // Find and set up the ListView for paired devices ListView pairedListView = (ListView) findViewById(R.id.paired_devices); pairedListView.setAdapter(_pairedDevicesArrayAdapter); pairedListView.setOnItemClickListener(_deviceClickListener); // Find and set up the ListView for newly discovered devices ListView newDevicesListView = (ListView) findViewById(R.id.new_devices); newDevicesListView.setAdapter(_newDevicesArrayAdapter); newDevicesListView.setOnItemClickListener(_deviceClickListener); // Register for broadcasts when a device is discovered & discovery has finished this.registerReceiver(_receiver, new IntentFilter(BluetoothDevice.ACTION_FOUND)); this.registerReceiver(_receiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)); // Get the local Bluetooth adapter _btAdapter = BluetoothAdapter.getDefaultAdapter(); // Get a set of currently paired devices Set pairedDevices = _btAdapter.getBondedDevices(); // If there are paired devices, add each one to the ArrayAdapter if (pairedDevices.size() > 0) { findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); for (BluetoothDevice device : pairedDevices) { _pairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } } else { _pairedDevicesArrayAdapter.add(getResources().getText(R.string.none_paired).toString()); } } @Override protected void onDestroy() { super.onDestroy(); // Make sure we're not doing discovery anymore if (_btAdapter != null) { _btAdapter.cancelDiscovery(); } // Unregister broadcast listeners this.unregisterReceiver(_receiver); } /** * Start device discover with the BluetoothAdapter */ private void doDiscovery() { (_btAdapter.isDiscovering()) { _btAdapter.cancelDiscovery(); } // Request discover from BluetoothAdapter _btAdapter.startDiscovery(); } } MainActivity.java ------------------------------------------------------- package trandi.spokalightbluetooth; import java.io.IOException; import trandi.spokalightbluetooth.MainView.ColValues; import trandi.spokalightbluetooth.MainView.JoystickListener; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Window; import android.widget.TextView; import android.widget.Toast; /** * Main activity to control the hacked Spoka light. * * @author trandi */ public class MainActivity extends Activity { // Debugging private static final String TAG = "SpokaLightBluetooth_MainActivity"; // Intent request codes private static final int REQUEST_CONNECT_DEVICE = 1; private static final int REQUEST_ENABLE_BT = 2; private TextView _title; private BluetoothAdapter _bluetoothAdapter; private Spoka _spoka; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.e(TAG, "+++ ON CREATE +++"); // Set up the window layout requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.main); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title); // register this activity with the View, to listen to Joystick events ((MainView)findViewById(R.id.myMainView)).addJoystickListener(new JoystickListener() { @Override public void onMove(ColValues newColours) { if(_spoka != null){ final String result = _spoka.updateColours(newColours.red, newColours.blue, newColours.orange) ? "OK" : "NOK"; Log.d(TAG, "Update Colours " + result + " (" + newColours + ")"); } } }); // Set up the custom title _title = (TextView) findViewById(R.id.title_left_text); _title.setText(R.string.app_name); _title = (TextView) findViewById(R.id.title_right_text); // Get local Bluetooth adapter _bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // If the adapter is null, then Bluetooth is not supported if (_bluetoothAdapter == null) { Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show(); finish(); return; } } @Override public void onStart() { super.onStart(); Log.d(TAG, "++ ON START ++"); if (!_bluetoothAdapter.isEnabled()) { // If BT is not on, request that it be enabled. Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // Asynchronous, the onActivityResult will be called back when finished startActivityForResult(enableIntent, REQUEST_ENABLE_BT); }else { // Bluetooth is already enabled // Launch the BTDeviceListActivity to see devices and do scan Intent serverIntent = new Intent(this, BTDeviceListActivity.class); startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE); } } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "++ ON DESTROY ++"); if(_spoka != null) _spoka.disconnect(); } public void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, "onActivityResult " + resultCode); switch (requestCode) { case REQUEST_CONNECT_DEVICE: // When BTDeviceListActivity returns with a device to connect if (resultCode == Activity.RESULT_OK) { // Get the device MAC address String address = data.getExtras().getString(BTDeviceListActivity.EXTRA_DEVICE_ADDRESS); // Create a business object which attempts to create to the Spoka ! //ensureDiscoverable(_bluetoothAdapter); try { _spoka = new Spoka(_bluetoothAdapter, address); } catch (Exception e) { Toast.makeText(this, "Can't connect to the SPOKA", Toast.LENGTH_SHORT).show(); finish(); } } break; case REQUEST_ENABLE_BT: // When the request to enable Bluetooth returns if (resultCode == Activity.RESULT_OK) { // Bluetooth is now enabled // Launch the BTDeviceListActivity to see devices and do scan Intent serverIntent = new Intent(this, BTDeviceListActivity.class); startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE); } else { // User did not enable Bluetooth or an error occured Log.d(TAG, "BT not enabled"); Toast.makeText(this, "User did not enable Bluetooth or an error occured", Toast.LENGTH_SHORT).show(); finish(); } } } private void ensureDiscoverable(BluetoothAdapter bluetoothAdapter) { if (bluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) { Log.d(TAG, "Force discoverable"); Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); startActivity(discoverableIntent); } } } MainView.java ------------------------------------------------------- package trandi.spokalightbluetooth; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class MainView extends View { private static final Point _red = new Point(50, 100); private static final Point _blue = new Point(250, 100); private static final Point _yellow = new Point(150, 300); private final List<JoystickListener> _joystickListeners = new ArrayList(); private Point _joystick = new Point(150, 200); private final int _r = 30; private boolean _move = false; private long _lastMove = 0; public MainView(Context context, AttributeSet attrs) { super(context, attrs); } public synchronized void addJoystickListener(JoystickListener listener) { _joystickListeners.add(listener); } @Override public boolean onTouchEvent(MotionEvent me) { // are we trying to move the "joystick" if(Math.abs(me.getX() - _joystick.x) <= _r && Math.abs(me.getY() - _joystick.y) <= _r){ if(me.getAction() == MotionEvent.ACTION_DOWN){ _move = true; }else if(me.getAction() == MotionEvent.ACTION_UP){ _move = false; }else if(me.getAction() == MotionEvent.ACTION_MOVE && _move && (System.currentTimeMillis() - _lastMove > 50)) { _lastMove = System.currentTimeMillis(); // call all the listeners new Thread(){ @Override public void run(){ ColValues updatedColours = new ColValues(); for(JoystickListener listener : _joystickListeners){ listener.onMove(updatedColours); } } }.start(); } } if(_move){ _joystick.set(Math.round(me.getX()), Math.round(me.getY())); // force to redraw this.invalidate(); } return true; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // draw the fixed circles Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.RED); canvas.drawCircle(_red.x, _red.y, 20, paint); paint.setColor(Color.BLUE); canvas.drawCircle(_blue.x, _blue.y, 20, paint); paint.setColor(Color.YELLOW); canvas.drawCircle(_yellow.x, _yellow.y, 20, paint); // draw the moving circle (the "joystick") paint.setColor(Color.GRAY); canvas.drawCircle(_joystick.x, _joystick.y, _r, paint); } public static interface JoystickListener { void onMove(ColValues newColours); } public class ColValues { public final int red; public final int blue; public final int orange; public ColValues(int red, int blue, int orange){ this.red = red; this.blue = blue; this.orange = orange; } /** * Calculates the distances from the position of the joystick and base colour circles */ public ColValues(){ final double maxDist = getDist(_red, _blue); this.red = 100 - (int)Math.round(getDist(_joystick, _red) * 100.0 / maxDist); this.blue = 100 - (int)Math.round(getDist(_joystick, _blue) * 100.0 / maxDist); this.orange = 100 - (int)Math.round(getDist(_joystick, _yellow) * 100.0 / maxDist); } private int getDist(Point a, Point b) { return (int)Math.round(Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2))); } @Override public String toString() { return "ColValues [red=" + red + ", blue=" + blue + ", orange=" + orange + "]"; } } } Spoka.java ------------------------------------------------------- package trandi.spokalightbluetooth; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.util.Log; public class Spoka { // Debugging private static final String TAG = "SPOKA"; // Unique UUID for this application // has to be this precise value for SERIAL port profile (SPP) private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // private static final UUID MY_UUID_SECURE = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66"); // private static final UUID MY_UUID_INSECURE = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66"); private BluetoothSocket _btSocket; private InputStream _socketIS; private OutputStream _socketOS; // will need to SYNCHRONISE on this as it's used from multiple threads ! // private Queue<String> _incomingData = new ConcurrentLinkedQueue<String>(); // private String _incomingDataStr = ""; public Spoka(BluetoothAdapter bluetoothAdapter, String address) throws IOException{ Log.d(TAG, "++ CONNECT SPOKA ++"); // Get the BluetoothDevice object BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address); // Get a BluetoothSocket for a connection with the given BluetoothDevice try { _btSocket = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (IOException e) { Log.e(TAG, "createRfcommSocketToServiceRecord() failed", e); throw e; } // Attempt to connect to the device // Always cancel discovery because it will slow down a connection bluetoothAdapter.cancelDiscovery(); // Make a connection to the BluetoothSocket try { // This is a blocking call and will only return on a successful connection or an exception _btSocket.connect(); Log.d(TAG, "++ connectED SPOKA ++"); } catch (IOException e) { disconnect(); Log.e(TAG, "Can't connect to the Spoka", e); throw e; } // !!! COMMENTED OUT THE WHOLE INCOMING SERIAL DATA READ, AS THIS SEEMS TO CAUSE THE RECEIVED BYTES TO BE GARBLED !!! // start a separate thread that monitors any incoming data, and stores it in a queue // this is done so, because we don't seem to have an asynchronous read() on the BluetoothSocket InputStream // new Thread(){ // @Override // public void run(){ // byte[] buff = new byte[100]; // while(true){ // try{ // if(_socketIS == null) _socketIS = new BufferedInputStream(_btSocket.getInputStream(), 1024); // // if(_socketIS != null){ // // blocking on the read when there's nothing... // int readCount = _socketIS.read(buff); // // for some VERY SILLY reason, if we store the bytes here, they come garbled... // _incomingData.add(new String(buff, 0, readCount)); // } // } catch (Exception e) { // Log.e(TAG, "Can't read message from the Spoka", e); // } // } // } // }.start(); } public void disconnect() { try { if(_btSocket != null) _btSocket.close(); } catch (IOException e) { Log.e(TAG, "Unable to close() socket during connection failure", e); } } public boolean updateColours(int redPerc, int bluePerc, int orangePerc) { byte red = checkPerc(redPerc); byte blue = checkPerc(bluePerc); byte orange = checkPerc(orangePerc); // 1. send the special char "#" indicating to the Spoka that we want to manually update the colours sendBytes((byte)'#'); // 2. check that we receive back the "BRO " acknowledgement( Blue, Red, Orange) //if(waitForIncomingData("BRO", 100)){ // 3. send the values & the check sum sendBytes(blue, red, orange, (byte)(((int)blue + (int)red + (int)orange) % 100)); // 4. check that we receive back confirmation //return waitForIncomingData("OK", 100); //} return false; } private byte checkPerc(int perc){ return (byte)(perc < 0 ? 0 : (perc > 100 ? 100 : perc)); } private void sendBytes(byte...bytes) { try{ if(_socketOS == null) _socketOS = new BufferedOutputStream(_btSocket.getOutputStream(), 1024); if(_socketOS != null){ _socketOS.write(bytes); _socketOS.flush(); } } catch (IOException e) { Log.e(TAG, "Can't send message to the Spoka", e); } } private boolean waitForIncomingData(String expectedData, int timeoutMillis){ final long startTime = System.currentTimeMillis(); byte[] buff = new byte[100]; String incomingData = ""; try{ if(_socketIS == null) _socketIS = new BufferedInputStream(_btSocket.getInputStream(), 1024); if(_socketIS != null){ while((! incomingData.contains(expectedData)) && (System.currentTimeMillis() - startTime < timeoutMillis)) { // blocking on the read when there's nothing... int readCount = _socketIS.read(buff); // for some VERY SILLY reason, if we store the bytes here, they come garbled... incomingData += new String(buff, 0, readCount); } } }catch(IOException e){ Log.e(TAG, "Can't receive incoming data", e); } Log.d(TAG, "RECV: " + incomingData); if(incomingData.contains(expectedData)){ return true; } return false; } // private boolean waitForIncomingData(String expectedData, int timeoutMillis){ // final long startTime = System.currentTimeMillis(); // // while((! _incomingDataStr.contains(expectedData)) // && (System.currentTimeMillis() - startTime < timeoutMillis)) // { // final String head = _incomingData.poll(); // if(head != null) _incomingDataStr += head; // Thread.yield(); // } // // if(_incomingDataStr.contains(expectedData)){ // // REMOVE the expected data (and whatever was before) from the string buffer // final int pos = _incomingDataStr.indexOf(expectedData) + expectedData.length(); // _incomingDataStr = _incomingDataStr.substring(pos); // // return true; // } // // Log.d(TAG, "RECV: " + _incomingDataStr); // return false; // } // /** // * @return true if the expected incoming data has been received, false if timeout // */ // private boolean waitForIncomingData(String incomingData, int timeoutMillis){ // final long startTime = System.currentTimeMillis(); // // wait until received expected data or timeout // while(! peekIncomingData().contains(incomingData) && (System.currentTimeMillis() - startTime < timeoutMillis)){ // try { // Thread.sleep(10); // } catch (InterruptedException e) { // // nothing to do // } // } // // final int position = peekIncomingData().indexOf(incomingData); // if(position > 0){ // // now remove the data from the incoming queue // for(int i=0; i < position + incomingData.length(); i++){ // _incomingData.poll(); // } // return true; // found the expected string // }else{ // Log.e(TAG, peekIncomingData()); // } // // return false; // NOT found the expected string and timed out // } // // private String peekIncomingData() { // Byte[] data = _incomingData.toArray(new Byte[]{}); // byte[] dataChars = new byte[data.length]; // for(int i=0; i // dataChars[i] = data[i]; // } // return new String(dataChars); // } }
And here are all the XML configuration files, specific to Android platforms:
custom_title.xml ------------------------------------------------------- <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns: <TextView android: <TextView android: </RelativeLayout> device_list.xml ------------------------------------------------------- <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns: <TextView android: <ListView android: <TextView android: <ListView android: <Button android: </LinearLayout> device_name.xml ------------------------------------------------------- <?xml version="1.0" encoding="utf-8"?> <TextView xmlns: main.xml ------------------------------------------------------- <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns: <FrameLayout android: <trandi.spokalightbluetooth.MainView android: </FrameLayout> </LinearLayout> strings.xml ------------------------------------------------------- <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Spoka Light Bluetooth</string> <!-- BTDeviceListActivity --> <string name="scanning">scanning for devices...</string> <string name="select_device">select a device to connect</string> <string name="none_paired">No devices have been paired</string> <string name="none_found">No devices found</string> <string name="title_paired_devices">Paired Devices</string> <string name="title_other_devices">Other Available Devices</string> <string name="button_scan">Scan for devices</string> </resources>
hi trandi,
its a really great project and i like it very much!
can you please post the schematic or send it by mail?
thanks.
andi
I really like your project. I’m almost done, the only thing that isn’t running fine is the app. So I wonder if it would be possible to send the apk to me?
Hello, I ‘m a student.Can you give me more information? I want to try. THX ~
I really like your project. I am almost done with the whole thing. But there’s still a problem: I don’t know much about programming in C. So would it be possible to send me the uart header file?
Thanks, no worries, the C code is all in the post, after the “And here’s the C code.”
Hope this helps,
Dan
Thank you very much.
Pingback: TM1638 Display Driver for Stellaris Launchpad « Robotics / Electronics / Physical Computing
Hi trandi,
just found your project. I’m a student an would love to start with Android and some BT programming.
Could you please also send me the files?
I’ll report as I was successful 🙂
Thank you
i just need the ac adapter for mine! I bought it from a thrift store not knowing an adapter was needed!
Hi! I’ve tried hard to get this working, but I don’t get it. Can you please send me your sourcecodes for attiny and your app?
hey i’m from China , i can’t speak very well.. don’t mind….
can you send me this app..?
I use ECLIPSE to try but found many errors…
thx !
Hey.. great project !!!
m a student in India…
m planning on making a bluetooth tag kind of something …which is to b controlled by a smartphone….after pairing it up with a application which ill develop on the smartphone….if the tag is taken apart say about more than 5m from the phone….it should trigger a alarm on the phone……can u plzzz guide me on that …….i wud love to b guided by u….
Hi Utsav,
I know you would love me to do your homework for you, but unsurprisingly I have other priorities…:)
On a more serious note, if you have any SPECIFIC and PRECISE technical question about your project, then please don’t hesitate to ask.
Dan
thnx for the reply…how do make a bluetooth tag using a module..that can b paired up with a smartphone???
Is it possible to post the hex file? I’m having a difficulty compiling.
Hi Trandi !
Awesome project , really !
I am about to create something similar with 2 or3 spokas.
could you provide me with your code (zip)
thanks alot
mike
Done.
Can’t wait to see some pictures/details of your project ! Keep me updated…
dan
Pingback: SPOKA Night Light & Android – RETURNS « Robotics / Electronics / Physical Computing
Hey there,
i’m a student in Germany.
For a project in school I want to realize that project on my own.
But i’m focusing on the MCU-Part and not on programming on the Android-platform.
It would be very nice if you could send me the apk you created.
Thank you very much!!
Greets
Soenke
Done, sent to your e-mail.
I would love to see some pictures of your project…
Dan
Hi trandi,
can you also send me the android code for the bluetooth connection? Thanks in advance.
done, check your e-mail… hope it will help you !
Do let me know if you create anything interesting…
Dan
could I also have a copy of the android code. Would like to break it down and see how it works. thanks in advance
Hi Soenke,
i’m a student in Taiwan.
I want try it.
Can you also send me the android code for the bluetooth connection? Thanks in advance.
My E-mail:sdestiny20a@gmail.com
Good work there! You’ve have inspired me with your SPÖKA mod to do something similar myself. I have modified a SPÖKA light to be controlled over USB:
I have used the other SPÖKA model and I found it a little surprising that IKEA actually used different PCBs inside of the two SPOKA models.
Wow, this is really great work !
I don’t think the PCB’s are so different because you have the taller SPOKA model, but simply because you bought it at another time (mine was bought several years ago !) and they must have updated the design… I could check as I have a tall light too, but I don’t think my wife would let me hack the other one too … 🙂
Dan
Hi,
I have submitted your work to hack a day, and here you are, featured on their website :
Now we have to keep up the SPOKA light hacks chain… lol…:)
Dan
excellent,
What license are this code under?
there’s not really a “license” : the code is posted for everybody to use as they see fit, but obviously WITHOUT ANY GUARANTEE, explicit or implicit !
dan
thanks for your reply.
I need the bluetooth part of android program.
thank you so much
It’s in there ! Right at the beginning of the big chunk of pasted code there is something starting with “BTDeviceListActivity.java”…
dan
Hi,
Sorry this is a bit off-topic, but:
Does your modified (or virgin) SPOKA stay on during a power-cut?
If mine is on and mains-powered, and then I turn off the mains power at the wall, the light goes out (rather than automatically switching to battery power): I wanted a nightlight for my son that would stay on during a power cut (he is badly scared of the dark), so the out-of-the-box functionality is no good for me.
I loved your hack by the way, I’d love to see a row of those responding to music at a party:)
Yes it does.
Funny, I had never noticed that before, the fact that when you unplug the power the original Spoka goes off.
Yeah, this idea of having several of them connected to the same phone and lighting up in sync seems to be one of the most interesting… However, I don’t feel like going through all the soldering again several times… 🙂
Dan
Pingback: IKEA Nightlight Hacked for Android-based Control | The Copy Paste Blog
Pingback: 床頭燈變迷幻燈,全靠 Android 改做 | UNWIRE.HK 流動科技生活
Pingback: IKEA Nightlight Hacked for Android-based Control : LinuxBuzz.net
Pingback: IKEA Nightlight Hacked for Android-based Control | CisforComputers
Pingback: IKEA Nightlight Hacked for Android-based Control | iPhone 2 die 4
Pingback: DIY 用手機控制燈光不是夢? App-Goog-les
Pingback: Android también puede gobernar lámparas: ¡Aquí la prueba en vídeo! | TecnoBlog
Pingback: Android también puede gobernar lámparas: ¡Aquí la prueba en vídeo! | Vida-gamer.com
Pingback: Android también puede gobernar lámparas: ¡Aquí la prueba en vídeo! | Tecno BLog celulares nuevos, descargas de temas juegos y aplicaciones,todo sobre nuevos modelos de celulares
Pingback: Lámparas de Ikea podrán controlarse con Android | Universo Digital Noticias
Pingback: Android también puede gobernar lámparas: ¡Aquí la prueba en vídeo! - Wayerless
Pingback: DIY用手機控制燈光不是夢? | TechOrange
1st, came here via heise.de too 🙂
2nd, went to IKEA got one of the lights myself to try this nice mod 🙂
Reverse engineered the PCB and asked myself: what the heck do they do with Q1??!!
Do you have any idea what this piece of circuit is for?
How did you connect IC.3 and IC.4 to your uC?
Have no idea about Q1, I haven’t spent too long understanding everything, I simply assumed all the transistors were there to drive the LEDs.
ALL I did, was to connect 3 of the pins of my new MCU to the lines controlling the LEDs (1 per colour) and 1 extra pin to the switch button at the top of the Spoka.
For pins 3 & 4, as you can see from my little diagram (the only one 🙂 ) IC3 was connected to the switch which is now connected to PB1 on the ATTiny2313 and the old IC4, is not connected to anything, I think it just pulls up IC3.
Dan
Ha! Most important for now to me is, that I can simply/safely ignore Q1 surroundings, great 🙂
After the mod, did you encounter a significant decrease of battery lifetime?
YES, indeed, now the battery only lasts for a couple of days, even if the lights are off ! You can see that my simple hack doesn’t deal with any “sleep mode” for the ATTiny, so it keeps running in the background all the time… worst probably, is the bluetooth module though.
Normally, I should have a mode where both the MCU and the bluetooth board go to sleep (I think it’s supported by both, but I couldn’t be bothered… lol… 🙂 )
dan
Judging from the circuitry surrounding Q1 my first thought was that it is some sort of switch. The idea is that it shuts down power to the µc when it is put into off mode. Pressing the pushbutton turns q1 on for the time of the button press. the µc then initializes and pulls an output-pin to ground level so that Q1 will remain conductive after the button has been released. I might be wrong about this, as i did not verify this yet. I’m putting some more time in improving the C code which is quite difficult as i never did anything in C before, only Perl. I thought about porting to the atmega8, including obdev.at’s v-usb stack and add some features like RFM12-radio relay support(so you can control multiple lights wirelessly from one master light that is controlled by usb or bluetooth) but this is easier to do in asm than in C (at least to me it is 🙂 )
Initially the switch had 3 modes (so NOT only on /off) : off, on and constant light, on and changing colours… so I’m not sure about the Q1 used to put the uC in off mode… but I’m really not an expert…lol…
Dan
Pingback: IKEA Spoka Lamp Controlled By Android Smartphone (Video) - IT Lounge
Pingback: IKEA Spoka Lamp Controlled By Android Smartphone (Video) - Mobile Magazine
Pingback: Controla una lampara de Ikea con tu dispositivo Android [VIDEO]
Pingback: CoCoLink - Tu Web de Electronica!..
Pingback: Controla una lámpara de Ikea con tu móvil Android - La Isla Buscada
Awesome job Ytai, before we know it everything will be Android controlled!
I have had pretty much exactly the same problem while making my Android controlled LED shirt (). I ended up only using unidirectional SPP communication on my Android HTC INC2 using the BlueSmirf modules from Sparkfun, so you can feel good that spending more money wouldn’t have solved the problem. Most of my BT code came from the example from the SDK.
I think we’re onto the right track on concatenating the results of different read operations. I had my best results reading one byte at a time without a timeout in a separate thread, and padding all transmissions with a start string (say ***) and an end string (say &&&). This way I would keep reading until I saw an end string and the length was correct. This got pretty close, but still wasn’t perfect.
And as the Halloween party I was going to wear the shirt to came closer, I came to the same conclusion as you that ACKs weren’t really necessary.
I hope sometime in the future someone figures this out and shares the code. If I do, I’ll keep you up to date, and I hope you’ll do the same.
Cheers,
Great video, and great T-Shirt !
So you’re saying that you have the same problems with the BlueSmirf module from Sparkfun… interesting…
Ytai mentioned that his does indeed uses bi-directional SPP over bluetooth for IOIO, and it works OK without him having done anything special …
I’ll definitely be interested if you find a solution, and will obviously post an update here if I find one myself !
Dan
I think you meant “Awesome job, Dan”, but thanks anyway 🙂
That shirt is just awsome!!! I’ve made a similar project with IOIO here:
The code is there too, in case it helps…
Would be great if your shirt could take audio input from the Android and sync to the music 🙂
Ooops, yea I meant “Awesome job, Dan”. That will teach me to stay up late posting comments. I am planning on upgrading the shirt soon to sync with music using the Android mic. Hoping I can adapt the code from here () I’ll take a look at Ytai’s code when I do.
Pingback: Spoka light controlled from Android phone « Ikea « Cool Internet Projects
Pingback: Hack an ikea night light to be controlled from your phone - BuildLounge » BuildLounge
Pingback: Ikea Night Light controlled by an Android Phone « « SNAP-DIYSNAP-DIY
Pingback: Ikea Night Light controlled by an Android Phone | iGadgetView.com
I picked up your project on heise.de and was fascinated as i am building led lights for quite some time and this seems like a perfect device for starting something new. I think you can replace the LEDs with red, green and blue ones. As the voltages of typical blue almost matches the built in purple and typical green almost matches the built in orange, this shouldn’t be too much of a problem. I also thought about replacing the mcu with something similar to . But your project is even better as it can be used as a wireless notifier, even from a pc 🙂 However i’d still prefer the wireless transceivers (RFM12, about €5 each on various sources). They have a much greater range than bluetooth.
Thanks for your comment !
Wow, the light cube you link to is quite nice… I like the minimalistic approach, small MCU that must be doing the USB in software, etc. … I was too lazy to implement even software UART, even less USB… hence the ATtiny2313 as opposed to a an ATtiny45 (which was also my initial idea).
Regarding you wireless transceivers, again that was my initial idea, and I had even got 2 of them (see this post) specifically for this task…
However, bluetooth is so much cleaner on the phone side… otherwise I would have had to have the transceiver AND a IOIO or similar hanging from the phone.
With bluetooth, you can use ANY phone, no need to attach any extra hardware…
Dan
Pingback: Ikea Night Light controlled by an Android Phone - Free Plans, Hacks, Howto's and other DIY stuff - Free Plans Online
Pingback: Ikea Night Light controlled by an Android Phone - Amazing! Gadgets
Pingback: Ikea Night Light controlled by an Android Phone | Price Gadget Reviews
Pingback: Ikea Night Light controlled by an Android Phone » Geko Geek
Pingback: Ikea Night Light controlled by an Android Phone - Hacked Gadgets – DIY Tech Blog
Hi,
brilliant idea.
can you upload the connection scheme/wiring diagram so we can rebuild it on our own??
Thanks a lot! One again: Brilliant idea! I really like it!
best regards!
Hi Hans,
Thank you.
For the schematic, I don’t have any formal drawing (and I won’t open the lamp again now to draw it retrospectively… lol… 🙂 ) but it’s quite simple.
You can find some more details in one of the other comments…
Thats a really nice project. While I know my way around electronics a little bit I never created an app on Android. Can you outline how to create an app using your source code? Do I need additional tools like an SDK?
Kind regards from Munich, Germany, Andreas
PS I came to your site by the portal
Yes you don need an Android SDK.
Here is really not the place to go into details about how to get started with Android, if you do a search on the internet you’ll find literally thousands of articles about it…
This is the official site: so it might be a good start.
Once you have the SDK, here on the post you have all the necessary Java code (split into separate files) and configurations (xml files).
The only one little missing thing is the icon 🙂
Dan
I started working with the SDK and Eclipse. I created an AVD for Android 2.2 , API level 8. In Eclipse i have the 4 java files under src/trandi.spokalightbluetooth, the 4 XMLs under res/layout and strings.xml under res/values. I got errors for BTDeviceListActivity.java and MainActivity.java and exclamation marks for the other 2 java files as well as for custom_title.xml, main.xml and strings.xml.
Could it be that with Android 2.2 I use the wrong version and this beeing the reason for the errors?
Andreas
“exclamation marks for the other 2 java files” is not that helpful… 🙂 You need to be more specific, about the EXACT ERROR message
dan
I checked further with eclipse and found a lot of syntax errors in the BTDeviceListActivity.java like:
public void onItemClick(AdapterView av, View v, int arg2, long arg3) {
Is there still something wrong with the code as mentioned by others?
Another question is which Android Version do you use.
Thanks for you help, Andreas
PS If its easy for you to mail the code it would be nice to receive it at
Done, I’ve just sent you a zip with all the code.
Actually it has one little improvement: a button that if toggled will automatically generate random movements of the “joystick” and hence random colours, every 1 seconds.
Dan
P.S. also, it’s never a great idea to post your e-mail in clear on a blog as you’ll receive plenty of spam from web crawlers… hence I’ve deleted it from your comment…
I have the same problems in Eclipse. I use like Andras Eclipse with the Android 2.2 SDK
ahh I forgot. I just have errors in BTDeviceListActivity.java
I had to import the R.java. in the MainActivity.java, because it was not imported there, but needed. My first Error in BTDeviceListActivity.java is in line 68 following.
” private OnItemClickListener _deviceClickListener = new OnItemClickListener() {
@Override”
Same thing, check your e-mail.
HOWEVER, let me make this clear: the code bits in this post are “snippets” and are not meant to be directly “compilable” ! It’s meant to give you an idea (and serve as a reminder for myself 🙂 ) but it does require some work to put together.
The post itself is NOT an instructable where you follow some exact steps and voila you get the final result… it’s provided as information only, and you are supposed to provide some extra work to have a functioning prototype…
In any case I’m curious to see if you guys can get other working Spokas, do let me know or send me photos as soon as you get to something !!!
Dan
Can’t you upload the compiled App or the whole sourcecode? I guess you already compiled an app. Would be really nice!
I have great problems to compile the Android sources!
Please send it to me 🙂
Thank you!
Hi Nils,
As already mentioned, the code provided here is for indication only, it’s not meant to be directly downloaded and work out of the box…
I’ve sent you a zip with all the code that works for me, but again it’s up to you to compile and fine tune it.
Dan
I’m a totally Android beginner but after I got the source and upgraded JAVA to 1.6 (or 6) I have been able to create an app and put it on my phone (HTC Desire with 2.2) even if the app is 2.3. With JAVA 1.5 (or 5) the code won’t work.
I go step by step and the first step is completed. I just ordered a bluetooth transceiver from EBAy but that will take some time.
Kind regards from Germany
Andreas
Nice!
I want to build the same as well.
As mentioned above the code (C, java and xml) is truncated. Can you provide the same?
Thanks, frank
Fixed BOTH the XML and the AVR code in the post.
Have a look and let me know if you’re still seeing anything wrong.
dan
AVR code is compiling now!
Initially was confused, because my evaluation board hooks up a 90s2312 which is different.
Have to get a ATTiny2312 immedeately.
Thanks
Glad to hear it compiles 🙂 Yes, it probably won’t do what expected if you have a different MCU on the board… 🙂
Dan
I installed AVR Studio 4.19 and AVR Toolchain 3.2.3. During build I got 4 warnings:
c:\program files (x86)\atmel\avr tools\avr toolchain\bin\../lib/gcc/avr/4.5.1/../../../../avr/include/util/delay.h:89:3: warning: #warning “F_CPU not defined for ”
../uart.c: In function ‘uart_getChar’:
../uart.c:28:2: warning: implicit declaration of function ‘uart_putChar’
../uart.c: At top level:
../uart.c:32:6: warning: conflicting types for ‘uart_putChar’
../uart.c:28:2: note: previous implicit declaration of ‘uart_putChar’ was here
../uart.c:69:0: warning: “F_CPU” redefined
c:\program files (x86)\atmel\avr tools\avr toolchain\bin\../lib/gcc/avr/4.5.1/../../../../avr/include/util/delay.h:90:0: note: this is the location of the previous definition
Is this a serious problem?
@Frank: Do you get warnings as well? Which version did you use from AVR?
Regards, Andreas
It should be ok. To be honest I don’t pay much attention to the warnings myself, so can’t be sure.
I’ve sent you my .hex compiled binary, in case it helps.
As mentioned, this is experimental code and I’m working on other projects right now(the kind that need their nappies changed every 3 hours and scream when hungry… 🙂 ) so don’t have time to look into the details…
It’s also an occasion for you to learn more and debug the code… lol 🙂
Dan
I finished “my” Spoka 🙂
I replaced the PCB and put the AVR with SMD5050 RGB LEDs on the same, these give nice colored bright light. Iapplied some “improvements” to the code w.r.t. deep sleep mode and the color change (dynamic) mode.
Thanks again for the nice Idea. I can share my mods and some snaps if you are interested.
Frank
Wow, great ! Of course, I would love to see some pictures / video of your device !
dan
I want,too.
As mentioned above the code (C, java and xml) is truncated. Can you provide the same?
Thanks, yang.
Pingback: A little Android automation turns SPOKA to SPOOKTACULAR! » IKEA FANS | THE IKEA Fan Community
please contact us:, ulrich.ranke@ceratecaudio
Trandi did a great job here I hope you are not aiming for a patent lawsuit.
🙂 NOT AT ALL !
I didn’t even think about it until you mentioned it… it’s crazy what a conflicting society we live in today… !
Great project! Very cool!
Could you please post a list of components needed excapt the BT tranciever? (processor…?) Thank you very much!
Hi Martin,
It’s really just the bluetooth board and the ATtiny2313 ! And some wires 🙂
The great thing about the Spoka is that it’s simple but has everything needed to drive the LEDs included… obviously given that the original MCU had to do the same thing.
You’ll have to keep in mind that it runs on 3 AAA rechargeable batteries, so you need an MCU that runs at 3.3 volts (as opposed to 5V).
It’s also good to have and MCU with hardware UART if you want to avoid having to implement it in software, as per my post…
Dan
Sorry for asking again: I’d like to start with programming hardware, and this project seems to be the best start for it.
OK, I got it, ATtiny2313 and BT board. Has the ATtiny2313 20 pins? What do you mean with you last sentence?
Yes, but it’s not relevant. The last sentence means that some microcontrollers (which is a CPU + hardware peripherals) have a hardware that does UART and others not, and you have to use a library…
But if you’re just starting with microcontrollers, there are plenty of better places on the net to learn about, I can’t go into that many details in a comment… (and I’m not an expert myself anyhow…)
dan
Perfect! – I’ve dissasembled the Spoka some month ago and just finished an microcontroller project ( Competition Pro – C64 Joystick on iPad for C64 Emulator ) and the Spoka has to be controlled with an iPhone soon! 🙂
Wow great !
I’m really NOT a “iFan”, but it can only be nice to see the Spoka work with an iPhone too… should be quite straight forward, it’s just a matter of programming the bluetooth …
Do let me know or send some pictures / info once it’s done !
Dan
Hi Dan,
this is really a cool project!
As I am an android beginner I wanted to download your java and xml files and understand them. Unfortunately the syntaxhighligher used on this page scamles the xml files, e.g. some tags and beginings of lines sterting with “<keyword … " are partly removed. In particular the main.xml file and device-list.xml are not usable anymore. Is there an alternative way to post the code? e.g. a link to a zip file which includes all source files unencoded?
no worries , check your e-mail I’ve sent you the whole thing.
Do come back and post your updates if you reproduce this on your own, I’d be curious to see what you obtain…
dan
I have fixed this on the post too, let me know if you find other issues.
Hey Dan,
congrats to your interesting project! Could you please provide a schematic of the whole circuit? Guessing it from the pictures is not that easy 🙂 Thanks a lot in advance!
Hi Thomas,
This is a fair point, I’ve never made a “formal” schematic given that the circuit is fairly simple :
– connect the 3 LEDs pins to 1 PWM pin of the micro-controller each
– connect the switch to a digital input pin
– connect the bluetooth module to the UART pins
– then all you need is to connect GND and VCC to both the MCU and the bluetooth board and that’s it you’re all settled
In my pictures you’ll see a 6 pin ISP header connected to the MCU, so that I can re-program it at will, but you don’t technically need that.
If you want the exact pin numbers, just have a look at the C code running on the ATtiny.
Hope this helps,
Dan
I was thingking about the same project many times.
I would love to use it as a wakeup light controlled and triggerd from the mobile phone.
but thats now only a software thing! Thanks for that!
the next free time i have will go into rebuilding you project.
Hi! Nice project. Could you say a few words on how you have removed the internals from the silicone skin? Did you use any tools for removing it?
Hi Jon,
You’re right it wasn’t that easy… I haven’t used any tools, just strong fingers ! Same for putting back.
Once you remove the plastic shell from the silicone skin however, you need some sort of screwdriver to open it up. It’s actually glued together so you have to be careful to slowly break the glue without damaging the plastic shell too much…
However you don’t need to glue it back again, as the 2 halfs fit well together and the silicone skin holds everything nicely in place.
Hope this helps,
Dan
mentioned on heise.de
yeah, didn’t even know about this German site before, but it seems to be quite a big thing… some of the guys there argue however (they certainly have a point) that it’s not recycling enough stuff to be worth mentioning… lol…:)
just found your project on heise.de. it is awesome!
heise is a great publisher in germany which publishes the c’t-magazine. it is one of the best known technical magazine in germany. (print run about 400.000 pieces)
congratulations for that! 😉
Wow, thanks ! I’m indeed impressed myself !
Now I’m waiting for feedback regarding how to imporove / evolve the project…
I came here from heise.de as well … nice project!
My idea would be to make the lamp glow/flash to music played on the android device or on a pc.
red = bass
green=mids
blue=highs
the colour / intensity should “mix” to the tone of the music and flash a little to the beat 🙂
… dont know if that is even possible but I think it would look nice though.
regards, hoschi
Indeed I thought about this too, as well as flashing different colours when you receive an e-mail or a tweet, etc. …
The flashing the lights bit is easy, what I don’t know is how hard it would be intercept and filter the music on the phone to extract some statistics in real time ?
The other thing is, would the music be played by the phone itself, or would it use its microphone to “listen” to it and de-compose its frequencies…?
Anyhow great idea, I don’t know if I’ll explore it as there’s far too much software programming involved, and I do enough of this during my day job…lol…:)
Dan
What a great idea! I think with more of those you can create a light orchestra show 🙂
Pingback: Controlling a cute Ikea night light with Android on the cheap « Hackaday « Cool Internet Projects
Hey, I’ve used the same bluetooth module here but I did not do any android programming though, I used an app which is very configurable, great for testing and prototyping before developing your own. So this is my suggestion to you, download that same app (QkCtrl) and use the terminal window to see if you receive garbage there also, then you know if it’s your app or not.,
Thank you Henrik, this is a good suggestion!
I’ve already tested the connection from the PC and it ALL works ok, but haven’t tried from the Android phone with a different bluetooth application…
Will try this when I have some time.
thanks,
dan
Pingback: Controlling a cute Ikea night light with Android on the cheap | My Blog
Re changing the pinout of your favorite 8-pin micro: just use 2 sockets, one atop of the other. On the upper one, clip all the legs and solder in short lengths of solid core wire. Plug the proto wire into the lower socket. Apply liberal hot glue inside the sandwich and the sides, and you would have the adapter you wanted.
Not that you need it here – the 2313 is more capable and better solution. But you presented the above pinout differences as a barrier.. there’s always a way. 🙂
Nice hack btw, especially with the cheapie bluetooth success.
That’s actually a surprisingly simple and effective idea !
Will definitely apply it in the future…
Thanks,
dan
Pingback: Controlling a cute Ikea night light with Android on the cheap » Geko Geek
Pingback: Controlling a cute Ikea night light with Android on the cheap | ro-Stire
Pingback: Controlling a cute Ikea night light with Android on the cheap - Hack a Day
I saw the bat-light 🙂
I don’t think your problems are Bluetooth-related. From my experience, once the socket is open, the connection is reliable. You’re doing some weird stuff in your reader thread. First, I don’t understand why you’re creating the BufferedIS inside the loop and not once before the look. Second, you’re segmenting your incoming data to Strings according to how many bytes a give read() operation has returned, which is absolutely arbitrary (i.e. if the remote end sends a 3-byte message, it might be received as a 1-byte read followed by a 2-byte read). So your “contains()” call is not likely to succeed in many cases. It is also very wasteful, since you’re checking the last string over and over…
What you really want here just is a read with timeout. For that purpose, you don’t need a thread and you don’t need a buffered IS. You can have a simple loop checking IS.available() and the elapsed time and sleeping shortly. A more elegant and slightly more complicated solution can involve a thread that notify()’s the main thread and an additional timeout timer that notify()’s is too. The main thread can simply wait() until either event occurs. But don’t go there unless you’re super-comfortable with multithreading.
Last, why do you need the ack? Why don’t you just do unidirectional communications?
Anyhow, very neat project. Hope it’ll help your baby sleep and get you some rest 🙂
Congrats!!!
Hi Ytai,
Thank you for your prompt reply / help !
I totally agree about the “weird” stuff in the reader thread… it’s actually shameful for a Java programmer by day… 🙂 However, here’s the story and why I ended up with that abomination:
– I started with no separate thread, exactly as you suggested, just reading the bytes, but I got crappy characters
– then after looking at the example that comes with the Android SDK I introduced the reading thread. Simply storing the bytes received in a thread safe list. To no avail !
– then after looking on the Internet for a while, I discovered that I had the exact same problem as THIS guy ! For obscure and un-comprehensible reasons, if I was creating the String in the reader thread and store than rather than the bytes, the text would be OK !!!
– however, again as you mention, the generated / stored strings are completely arbitrary, so I then attempted to put them together in one big string / array so that I can do “contains” on that. And then, again completely inexplicably, I stopped working, I get garbled text !!!
– this started to become quite frustrating, so I gave up and currently (as you can see all that code is commented out) I’m doing only unidirectional communication.
The perfectionist in me would have wanted the ACK, for the same reasons why I put that basic check-sum byte… to be able to re-send if necessary, and to have a more “robust” code (euphemism for “over engineering” 🙂 )
So, when you say “From my experience, once the socket is open, the connection is reliable.” were you using SPP over bluetooth, or something else ? If yes, then it might be some obscure problem with the native bluetooth driver on my specific phone model ??? (I know it’s always easy to blame others rather than your own code… 🙂 )
Thank you again ! Dan
An easy way to check if your phone’s Bluetooth is reliable is to check whether it works OK with the IOIO over Bluetooth. It indeed uses SPP as well.
Either way, as I said, I think the ACKs are completely redundant. The BT stack already takes care of providing a reliable connection, so you can assume that either your message got through, or the connection dropped and you’ll get an exception.
very nice,good job :d | https://trandi.wordpress.com/2012/01/13/spoka-night-light-controlled-from-and-android-phone/ | CC-MAIN-2018-34 | refinedweb | 10,267 | 56.05 |
This is a C++ Program to genrate random numbers using Naor-Reingold random function. Moni Naor and Omer Reingold described efficient constructions for various cryptographic primitives in private key as well as public-key cryptography. Their result is the construction of an efficient pseudorandom function. Let p and l be prime numbers with l |p-1. Select an element g ? {\mathbb F_p}^* of multiplicative order l. Then for each n-dimensional vector a = (a1, …, an)? (\mathbb F_{l})^{n} they define the function
where x = x1 … xn is the bit representation of integer x, 0 = x = 2^n-1, with some extra leading zeros if necessary.
Here is source code of the C++ Program to Implement Naor-Reingold Pseudo Random Function. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
#include <iostream>
#include <math.h>
#include <stdlib.h>
using namespace std;
int main(int argc, char **argv)
{
int p = 7, l = 3, g = 2, n = 4, x;
int a[] = { 1, 2, 2, 1 };
int bin[4];
cout << "The Random numbers are: ";
for (int i = 0; i < 10; i++)
{
x = rand() % 16;
for (int j = 3; j >= 0; j--)
{
bin[j] = x % 2;
x /= 2;
}
int mul = 1;
for (int k = 0; k < 4; k++)
mul *= pow(a[k], bin[k]);
cout << pow(g, mul)<<" ";
}
}
Output:
$ g++ Naor-Reingold.cpp $ a.out The Random numbers are: 2 4 16 4 2 4 16 16 4 2
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
Here’s the list of Best Reference Books in C++ Programming, Data Structures and Algorithms. | http://www.sanfoundry.com/cpp-program-implement-naor-reingold-pseudo-random-function/ | CC-MAIN-2017-22 | refinedweb | 268 | 64.3 |
ASLR on OSX is weak (useless)
RESOLVED INVALID
Status
People
(Reporter: tom, Unassigned)
Tracking
({sec-want})
Firefox Tracking Flags
(Not tracked)
Details
Attachments
(6 attachments)
If I run ./firefox from /Applications/Firefox.app/Contents/MacOS with export DYLD_PRINT_SEGMENTS=1 set in a terminal, twice, and diff the output, I should see different __TEXT addresses, because of ASLR. Locating the libraries at a random location is important as it makes building a ROP chain (to defeat NX/DEP) more difficult. However, only the libraries in the /Applications/Firefox.app/Contents/MacOS/ folder are located at different addresses. The System libraries are at the same address. I believe this is because OS.X prior to 10.7 had very weak ASLR[0] that did not randomize the System libraries. This is improved in 10.7, but you guys build using the 10.6 SDK..
The good news is that we have the 10.7 SDK on the build slaves, and we're just a mozconfig change away from being able to switch to it.
Testing this:
Tom, do you mind checking again with this build:
Flags: needinfo?(tom)
(In reply to Tom Ritter from comment #0) >. This is the real question here. If we can use the 10.7 SDK to get the ASLR benefit but still support 10.6 then this is a fairly easy fix. If targeting 10.6 keeps this behavior then we can't get it until we agree to drop 10.6 support.
Note the symptom, though, being that all libraries but Firefox's are not ASLRed would suggest it's prebinding/prelinking doing that. I don't now if ASLR is supposed to override prebinding in 10.7+, but the thing I *do* know is that ASLR is essentially disabled by prebinding, except library load address is still randomized, but it's per machine, not per application. If that's supposed to have changed and OSX changes its behaviour depending on what was used to build the application, that sounds very dumb.
And from a cursory look at the dyld 195.6 source (that's the version in 10.7.5), it looks like the default for the linker is to use shared regions and prebinding, and there are two ways to have prebinding ignored: executable has the MH_FORCE_FLAT flag (which you get when building with -force_flat_namespace), or the DYLD_IGNORE_PREBINDING environment variable is set to app or all. So, except if I missed something in the code, which I don't exclude considering I didn't really look deeply, I would expect the behaviour in comment 0 to be the expected (default) behaviour.
Mike: I don't believe that changed anything. I attached two runs and they have the same addresses for System libraries, but different for the Firefox libraries.
Flags: needinfo?(tom)
So let's test your theory from comment 0 entirely: This will build for 10.7. The resulting binary will be in in about an hour.
I ran the .dmg from the ftp site, buildconfig says Still no change though. =/
Summary: ASLR on OSX is weak (useless) because of 10.6 SDK → ASLR on OSX is weak (useless)
So, it may well be something we can't do anything about. Can you check with DYLD_IGNORE_PREBINDING=all?
Also, check other apps using the same system libraries
Actually, I just went ahead rebooting my mac under OSX. DYLD_SHARED_REGION=avoid is what triggers complete ASLR for all libs. The default is DYLD_SHARED_REGION=use and that means all applications are using a shared cache of, aiui, prebound system libraries. The cache is in /var/db/dyld.
Status: NEW → RESOLVED
Closed: 5 years ago
Resolution: --- → INVALID
Yea, after talking calling up a friend, I can confirm the system libraries' locations are randomized on boot and stay there consistently until reboot, and that this behavior is independent of the SDK used. Sorry!
Component: Build Config → General
Product: Firefox → Firefox Build System | https://bugzilla.mozilla.org/show_bug.cgi?id=1018210 | CC-MAIN-2019-30 | refinedweb | 652 | 66.33 |
Classic games are so much fun to play, and they are even more fun to try to recreate. A few months ago, I decided to build an asteriods clone in Silverlight in order to familiarize myself with the technology. I had so much fun with the project that I decided to build a Frogger clone this time. This article will walk you through the steps that I used to recreate this arcade classic.
Since I am by no means a graphic designer, I needed to find some pre-made images for my game. I figured that I would be able to at least find a few screenshots of an older Frogger game using Google image search. Luckily, I was able to find the Xbox live arcade screenshots which gave me the base images I needed. Now that I had something to work with, I opened the screenshot in GIMP and started cropping out images. This process took a while because I needed to crop out each unique image and make the background transparent. I ended up with five different vehicles, three different size logs, three different turtles, a frog, the frog head, and finally a plain background image. Here are some examples of the images that were cropped out:
froghead, tractor, and frog (our main character).
Now that I have the images out of the way, it is time to start coding. For my project I used Visual Studio 2008 with the Silverlight Tools Add-on. This add-on allows you to create Silverlight projects directly from Visual Studio, which means you do not have to download any of the Expression products.
Once you get the add-on installed, it is time to fire up Visual Studio and create a new project using the 3.5 Framework. Then, select either VB or C# as your language. Finally, choose to create a new Silverlight Application. Follow the prompts, and when the Add Silverlight Application dialog appears, choose the option to Automatically generate a test page to host Silverlight at build time. I like this option because when you run your project from Visual Studio, an Internet Explorer instance will appear so you can test out your application.
Now that your project has been created, you can navigate to the Solution Explorer and open up the design surface for Page.xaml. My first step was to take the background image that I created from the original and set it as the background image for the page. This was done by adding an Image element to the Canvas.
Image
Canvas
<Image Source="media/background.png" Stretch="None" Canvas.
I also wanted to add some space to the top and bottom of the page for displaying the score and some other information that is relevant to the game. Therefore, I changed the width and the height of the canvas to be large enough to contain the background image and also have enough margin for the footer and header. Now that the basic elements were on the page, I needed to think about how I was going to program the game. Just for some background information, the whole idea of the game is for the frog to safely make it to the “homes” shown at the very top of the screen. In order to get home, the frog has to make it through the five lane highway by avoiding contact with the cars. Then, the frog must hop on the logs to safely make it to home. So, with that bit of information, I figured I needed a way to define “lanes”. The lanes would basically create physical boundaries for the sprites to move in. I ended up using Rectangles (these are represented by the red outlines you see on the image to the left) to achieve this affect. After creating all the Rectangles, here is what my screen ended up looking like. Also, you will notice that there are some additional rectangles at the top which define the goals where you want the frog to end up once he crosses all the obstacles.
Rectangle
Now, it is time to discuss the mechanics of the game engine. Let me start by giving you the definition of a Sprite (from Wikipedia):
In computer graphics, a sprite is a two-dimensional/three-dimensional image or animation that is integrated into a larger scene..
More specifically, in my game, the logs, vehicles, and turtles are all considered sprites. In order to make my things simpler to program, I leveraged a common base class called SpriteBase. Using a common base class allows you to leverage code reuse and more importantly polymorphism. This is an important factor when you are trying to move around large amounts of objects and applying collision detection algorithms to each one. For example, if you want to move a sprite around on the screen, you need to do it by changing the X and Y coordinates of that object. Therefore, the SpriteBase class has an X and Y property:
SpriteBase
X
Y
/// <summary>
/// The Y position of the sprite
/// </summary>
public virtual double Y
{
get { return (double)this.GetValue(Canvas.TopProperty); }
set { this.SetValue(Canvas.TopProperty, value); }
}
Moving on, we have now established that the sprites are the basic building blocks of the game. So, the first step is to get the sprites on to the screen. Since we want the game to be challenging, we do not want to hard code the locations of each sprite; therefore, we will have to use a randomizer. The randomizer will be used to make the cars to move at different speeds, determine if items move left to right or right to left. In addition, we want a variety of different cars, logs, and turtles on the screen.
Previously, we discussed how I used Rectangles to create logical boundaries for how the various sprites would move within the game. Basically, what I did was overlay Rectangles on the background image to create “lanes” for the road and water. Each Rectangle was defined in the XAML file and has a unique name. I reference each unique name in my code and add it to an array inside my code. Now, I realize that I could have just dynamically created these items in code, but I like being able to see the layout of the game in design mode. Below is the section of the XAML file which creates the lanes on the road. You will notice that the lanes all have a red outline around them. This is so I can see the lines at design time. When the application loads, I loop over the Rectangles and set the Stroke to a transparent color.
Stroke
<Rectangle x:Name="StreetLane5" Stroke="Red"
StrokeThickness="1" Canvas.Left="0"
Canvas.
<Rectangle x:Name="StreetLane4" Stroke="Red"
StrokeThickness="1" Canvas.Left="0"
Canvas.
<Rectangle x:Name="StreetLane3" Stroke="Red"
StrokeThickness="1" Canvas.Left="0"
Canvas.
<Rectangle x:
<Rectangle x:Name="StreetLane1" Stroke="Red"
StrokeThickness="1" Canvas.Left="0"
Canvas.
Now that I have an array with the Rectangles added to it, I can rely on the X and Y coordinates of those Rectangles to control the placement of each sprite. Now, I create a nested for loop that iterates over each Rectangle and adds a random number of vehicles to each “lane”. Each lane is assigned a random speed and direction for the vehicles to move in. Also, the cars in each lane are randomly assigned. Here is the code:
for
private void CreateVehicles()
{
//add some vehicles to each lane using some random logic
for (int i = 1; i <= 5; i++)
{
Boolean rightToLeft = (_randomizer.Next(0, 11) % 2 == 0);
Double startX = _randomizer.Next(0, 150);
Double speed = (double)_randomizer.Next(5, 20) * .1;
for (int j = 0; j < 4; j++)
{
VehicleType vType = (VehicleType)_randomizer.Next(0, 5);
Vehicle vehicle = new Vehicle(vType, rightToLeft);
if ((startX + vehicle.ActualWidth) >= this.Width) break;
vehicle.Lane = i;
vehicle.X = startX;
vehicle.XSpeed = speed;
vehicle.Y = GetNewYLocation(vehicle, i);
this.LayoutRoot.Children.Add(vehicle);
_sprites.Add(vehicle);
int spacing = _randomizer.Next((int)(_frog.ActualWidth * 3),
(int)(_frog.ActualWidth * 4));
startX += (vehicle.ActualWidth + spacing);
}
}
}
You will notice that the cars are randomly spaced apart. I used the width of the frog as a basic unit of measure for this. After all, the frog needs to be able to fit between the cars if it wants to make across the road. Also, note that each new sprite is assigned a lane. This is important because it helps me determine what items are in which lane. Since the frog moves forwards or backwards only one lane at a time, I can easily determine which objects the frog can potentially collide with. The logs and turtles are created in a very similar fashion. The newly created sprites are all added to a private list named _sprites. Having the sprites in a collection allows me to easily iterate over them for animation and collision detection purposes.
_sprites
In order to animate the sprites, I create a new System.Windows.Threading.DispatcherTimer class and implement the Tick event. In the Tick event, I call a method called MoveSprites(). This method iterates over the list of sprites that were added to the screen and updates their X and/or Y coordinates. In addition, it also detects if a sprite moves off of the screen. When a vehicle, log, or turtle moves off the screen, they are replaced by a new random sprite. This makes the game a little more interesting. Finally, if the frog happens to be hopping across the river, I detect which object the frog is sitting on and move the frog at the same speed as that object. Let’s take a look at the code:
System.Windows.Threading.DispatcherTimer
Tick
MoveSprites()
private void MoveSprites()
{
for (int i = 0; i < _sprites.Count; i++)
{
Boolean remove = false;
SpriteBase sprite = _sprites[i];
double newX = sprite.X;
//check the direction of the sprite and modify accordingly
if (sprite.RightToLeft) {
newX -= sprite.XSpeed;
remove = (newX + sprite.ActualWidth < 0);
}
else {
newX += sprite.XSpeed;
remove = (newX > this.Width);
}
//when items go off the screen we replace them with a new random sprite
if (remove == true){
LayoutRoot.Children.Remove(sprite);
SpriteBase replacement;
if (sprite.GetType() == typeof(Vehicle))
replacement = new Vehicle((VehicleType)_randomizer.Next(0, 5),
sprite.RightToLeft);
else if (sprite.GetType() == typeof(Log))
replacement = new Log((LogSize)_randomizer.Next(0, 3), sprite.RightToLeft);
else
replacement = new Turtle((TurtleType)_randomizer.Next(0, 3),
sprite.RightToLeft);
//find the min or max X position of the sprite in the same lane
var query = from x in _sprites
where
x.Lane == sprite.Lane
orderby
x.X ascending
x;
SpriteBase lastSprite;
//right to left means you want the max because
//when the item wraps around the screen
//it will appear in the higher range of X values
if (sprite.RightToLeft){
lastSprite = query.Last();
if ((lastSprite.X + lastSprite.ActualWidth) >= this.Width)
newX = (lastSprite.X + lastSprite.ActualWidth) + _randomizer.Next(50, 150);
else
newX = this.Width;
}
else{
lastSprite = query.First();
if (lastSprite.X <= 0)
newX = (lastSprite.X) - _randomizer.Next(50, 150) - replacement.ActualWidth;
else
newX = 0 - replacement.ActualWidth;
}
replacement.XSpeed = sprite.XSpeed;
replacement.Lane = sprite.Lane;
replacement.Y = GetNewYLocation(replacement, sprite.Lane);
_sprites[i] = replacement;
sprite = replacement;
LayoutRoot.Children.Add(replacement);
}
//when items start to move off the screen we clip part of the object so we do
//not see it hanging off the screen
if ((newX + sprite.ActualWidth) >= this.Width){
if (sprite.X < this.Width) {
RectangleGeometry rg = new RectangleGeometry();
rg.Rect = new Rect(0, 0, this.Width - sprite.X, sprite.ActualHeight);
sprite.Clip = rg;
sprite.Visibility = Visibility.Visible; //forces a repaint
}
}
//if the frog is on a object in the river then move it at the same rate
if (_frog.WaterObject == sprite){
double frogX = _frog.X - (sprite.X - newX);
Point p = new Point(frogX, _frog.Y);
MoveFrog(p);
}
sprite.X = newX;
}
}
Since objects really only move in a horizontal direction, I never recalculate the Y position of a sprite after it is placed on the screen. I am only recalculating the X position. Towards the middle of the function, you see some LINQ code. The LINQ code is used to figure out where to position the “replacement” sprite when something moves off the screen. Because the sprites have different lengths, I have to dynamically determine how far to the left or right an object needs to be placed when it is added to the screen. If the objects in a lane are moving right-to-left, we need to find the maximum X value; if left-to-right, we will look for the minimum X value. The diagram below will help clarify this logic:
So, now that you understand how the objects move around the screen, lets talk about collision detection. Collision detection in this game is very simple. Since the frog can only be in one lane at a time, I only perform collision detection on a particular group of objects at a time. Once again, I use LINQ to simplify the task:
private bool CheckForCollisions()
{
//check only the current lane to see if the frog is being hit by any vehicles.
//rely on the X coordinates only since the frog basically sits in the middle of the lane.
var query = from x in _sprites
where
x.Lane == _currentRow &&
((_frog.X >= x.X) &&
(_frog.X <= (x.X + x.ActualWidth)) ||
((_frog.X + _frog.ActualWidth) >= x.X) &&
((_frog.X + _frog.ActualWidth) <= (x.X + x.ActualWidth)))
x;
return (query.Count() > 0);
}
My collision detection algorithm is primary concerned only with X coordinates. Because the frog sits in the middle of a lane, I can rely on the fact that objects in the same lane are already within the same Y range of values. As I mentioned before, when the frog is on the road, he will die if he is hit by a vehicle. Therefore, when the frog is in lanes 1 through 5 (the road) and the result of the CheckForCollisions() method is true, the frog is road kill. However, when the frog is in lanes 6 through 10 (the water) and a collision occurs, then the frog is OK because that means he is sitting on top of a log or turtle. For this reason, when the frog is moving through water, I have a method called GetObjectUnderFrog() which will return a reference to the sprite the frog is on top of. If the frog is not sitting on anything, the method will return null, which means the frog fell in the water. If a sprite is returned, then a property called WaterObject is set so I keep a reference to the object the frog is sitting on. This property is used in the MoveSprites() method (shown above) to help move the frog at the same rate as the object it is sitting on. This gives the appearance that the frog is taking a ride. Here is the code:
CheckForCollisions()
true
GetObjectUnderFrog()
null
WaterObject
void _mainLoop_Tick(object sender, EventArgs e)
{
MoveSprites();
//only check for collisions when the frog is on the road
if (_currentRow > 0 && _currentRow < 6) {
if (CheckForCollisions() == true){
//frog is a pancake
KillFrog();
}
}
//you are in the water
if (_currentRow > 6 && _currentRow < 12) {
_frog.WaterObject = GetObjectUnderFrog();
if (_frog.WaterObject == null) {
KillFrog();
}
if (_frog.X > this.Width || _frog.X < 0)
KillFrog();
}
else
{
_frog.WaterObject = null;
}
}
This concludes my article on Recreating Frogger in Silverlight. If you enjoyed this tutorial, then please leave a comment. I really appreciate. | https://www.codeproject.com/Articles/36337/Recreating-Frogger-in-Silverlight | CC-MAIN-2018-34 | refinedweb | 2,572 | 65.42 |
Ulf Dittmer wrote:What does "the applet is not able to be seen" mean, exactly? Are there any error messages in the Java Console?
Ulf Dittmer wrote:The question remains just about the same: what does this code do, and what did you expect it to do instead?
Edited: OK, I just ran it, and it seems fine. I could enter some numbers and it calculated something. So what's the issue?
On an unrelated note: You should get in the habit of using the @Override annotation; it can be a huge time saver by preventing bugs resulting from typos.
Ulf Dittmer wrote:So the code in your second post has nothing at all to do with the problem? If so, why did you post it?
As I understand it, you want to create an applet that can play AVI files; is that correct? if so, the simplest approach is probably to use the JMF library - it supports AVI, and does not require native code (which can be tricky to use in an applet). JMF sample code is available here.
JMF library does not have the following API
import javax.media.*;
import javax.media.protocol.*;
import javax.media.control.*;
import javax.media.format.*;
Ulf Dittmer wrote:For basic operations, JMF does not require any native libraries (and hence linking) - there is a pure-Java version of it.
JMF library does not have the following API
import javax.media.*;
import javax.media.protocol.*;
import javax.media.control.*;
import javax.media.format.*;
What are you basing this statement on? The javadocs indicate otherwise:
Ulf Dittmer wrote:Sorry, I don't understand what problem you're facing now. Can you rephrase it?
Ulf Dittmer wrote:The output is what I would expect from this line:
System.out.println("AudioPlayerApplet.class" + bgVideo);
What else are you expecting? | http://www.coderanch.com/t/598831/Applets/java/applet-fetched | CC-MAIN-2015-06 | refinedweb | 303 | 65.93 |
MFC ActiveX Controls: Adding Custom Events
Custom events differ from stock events in that they are not automatically fired by class COleControl. A custom event recognizes a certain action, determined by the control developer, as an event. The event map entries for custom events are represented by the EVENT_CUSTOM macro. The following section implements a custom event for an ActiveX control project that was created using the ActiveX Control Wizard.
Adding a Custom Event with the Add Event Wizard
The following procedure adds a specific custom event, ClickIn. You can use this procedure to add other custom events. Substitute your custom event name and its parameters for the ClickIn event name and parameters.
To add the ClickIn custom event using the Add Event Wizard
- Load your control's project.
- In Class View, right-click your ActiveX control class to open the shortcut menu.
- From the shortcut menu, click Add and then click Add Event.
This opens the Add Event Wizard.
- In the Event name box, type
ClickIn.
- In the Internal name box, type the name of the event's firing function. For this example, use the default value provided by the Add Event Wizard (
FireClickIn).
- Add a parameter, called
xCoord(type
OLE_XPOS_PIXELS), using the Parameter Name and Parameter Type controls.
- Add a second parameter, called
yCoord(type
OLE_YPOS_PIXELS).
- Click Finish to create the event.
Add Event Wizard Changes for Custom Events
When you add a custom event, the Add Event Wizard makes changes to the control class .H, .CPP, and .IDL files. The following code samples are specific to the ClickIn event.
The following lines are added to the header (.H) file of your control class:
This code declares an inline function called
FireClickIn that calls COleControl::FireEvent with the ClickIn event and parameters you defined using the Add Event Wizard.
In addition, the following line is added to the event map for the control, located in the implementation (.CPP) file of your control class:
This code maps the event ClickIn to the inline function
FireClickIn, passing the parameters you defined using the Add Event Wizard.
Finally, the following line is added to your control's .IDL file:
This line assigns the ClickIn event a specific ID number, taken from the event's position in the Add Event Wizard event list. The entry in the event list allows a container to anticipate the event. For example, it might provide handler code to be executed when the event is fired.
Calling FireClickIn
Now that you have added the ClickIn custom event using the Add Event Wizard, you must decide when this event is to be fired. You do this by calling
FireClickIn when the appropriate action occurs. For this discussion, the control uses the
InCircle function inside a WM_LBUTTONDOWN message handler to fire the ClickIn event when a user clicks inside a circular or elliptical region. The following procedure adds the WM_LBUTTONDOWN handler.
To add a message handler with the Add Event Wizard
- Load your control's project.
- In Class View, select your ActiveX control class.
- In the Properties window, click the Messages button.
The Properties window displays a list of messages that can be handled by the ActiveX control. Any message shown in bold already has a handler function assigned to it.
- From the Properties window, select the message you want to handle. For this example, select WM_LBUTTONDOWN.
- From the drop-down list box on the right, select <Add> OnLButtonDown.
- Double-click the new handler function in Class View to jump to the message handler code in the implementation (.CPP) file of your ActiveX control.
The following code sample calls the InCircle function every time the left mouse button is clicked within the control window. This sample can be found in the WM_LBUTTONDOWN handler function,
OnLButtonDown, in the Circ sample abstract.
Note When the Add Event Wizard creates message handlers for mouse button actions, a call to the same message handler of the base class is automatically added. Do not remove this call. If your control uses any of the stock mouse messages, the message handlers in the base class must be called to ensure that mouse capture is handled properly.
In the following example, the event fires only when the click occurs inside a circular or elliptical region within the control. To achieve this behavior, you can place the
InCircle function in your control's implementation (.CPP) file:
BOOL CSampleCtrl::InCircle(CPoint& point) { CRect rc; GetClientRect(rc); // Determine radii double a = (rc.right - rc.left) / 2; double b = (rc.bottom - rc.top) / 2; // Determine x, y double x = point.x - (rc.left + rc.right) / 2; double y = point.y - (rc.top + rc.bottom) / 2; // Apply ellipse formula return ((x * x) / (a * a) + (y * y) / (b * b) <= 1); }
You will also need to add the following declaration of the
InCircle function to your control's header (.H) file:
Custom Events with Stock Names
You can create custom events with the same name as stock events, however you can not implement both in the same control. For example, you might want to create a custom event called Click that does not fire when the stock event Click would normally fire. You could then fire the Click event at any time by calling its firing function.
The following procedure adds a custom Click event.
To add a custom event that uses a stock event name
- Load your control's project.
- In Class View, right-click your ActiveX control class to open the shortcut menu.
- From the shortcut menu, click Add and then click Add Event.
This opens the Add Event Wizard.
- In the Event Name drop-down list, select a stock event name. For this example, select Click.
- For Event Type, select Custom.
- Click Finish to create the event.
- Call
FireClickat appropriate places in your code.
See Also
MFC ActiveX Controls | MFC ActiveX Controls: Methods | COleControl | https://msdn.microsoft.com/en-us/library/d3b8fw6t(v=vs.71).aspx | CC-MAIN-2016-44 | refinedweb | 974 | 65.62 |
Hi
I have also been looking a bit on activemq-core, and the many JAR
dependencies it currently has.
Currently we have a mix of mandatory and optional JARs.
I suggest we work towards reducing this and moving pieces from the
core, into separate maven modules.
1)
For example the MQTT client could possible fit in a new activemq-mqtt module.
2)
Also there is a org.apache.activemq.util.XStreamFactoryBean that is
only used for an unit test.
I dont think its acitvemq-core business to have Spring factory beans
for the XStream library. That is either Spring or XStream business,
not ActiveMQ. I suggest to remove this dependency from the core. End
users can create their own factory bean or use some other way.
3)
LevelDB store. This is a bit more tricky. The implementation of the
store is in a separate module at
org.fusesource.mq.leveldb.LevelDBStore. But there is an adapter in the
activemq-core source code.
*
* @org.apache.xbean.XBean element="levelDB"
*
*/
public class LevelDBPersistenceAdapter extends LevelDBStore {
}
As you can see it used XBean to generate it into the broker schema file.
I wonder if we can come up with some may in the future to make this
more separated. So we can have "shallow" adapters in the
activemq-core, but that is not tied at compile time to the
implementation. This is how we do it in Camel, with for example
DataFormats (they get generated in the Camel XSD schema, but is not
runtime tied to the camel-core).
Ah look at the JDBC store, they have some FactoryFinder to find the
impl. Maybe we can use that for LevelDB?
This would allow us then to move the levelDB store to a
activemq-leveldb module, and therefore untie the activemq-core from
this.
4)
There is also the FTP support which uses commons net. We could
consider moving that into a separate module as well.
5)
Somehow activemq-core has dependency to Jettison. I cannot see a
reason why. Anyone ?
Sorry if I go overboard, but I want to make activemq-core a leaner
module. So its easier for people to slice and dice to use what they
need. And to make AMQ more appealing for users (eg its fewer JARs)
with plugin/optional features they can choose a la carte.
This also makes OSGi easier as today we got a bunch of optional OSGi
imports in the MANIFEST.MF of the activemq-core; this is not ideal.
--
Claus Ibsen
-----------------
FuseSource
Web:
Twitter: davsclaus, fusenews
Author of Camel in Action: | http://mail-archives.apache.org/mod_mbox/activemq-dev/201209.mbox/%3CCAGB5yNk+GbOxMKwkRjKnzkoNcA6tj1g+Dq1Fze9ie6W1TBWfeQ@mail.gmail.com%3E | CC-MAIN-2017-26 | refinedweb | 427 | 66.74 |
This Bugzilla instance is a read-only archive of historic NetBeans bug reports. To report a bug in NetBeans please follow the project's instructions for reporting issues.
Netbeans' hints generate the following equals() implementation:
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
According to Effective Java 2nd Edition Item 8 this is wrong because it violates the "Liskov substitution principle
[that] says that any important property of a type should also hold for its subtypes, so that any method written for the
type should work equally well on its subtypes". Joshua goes on to write:
"While there is no satisfactory way to extend an instantiable class and add a value component, there is a fine
workaround. Follow the advice of Item 16, 'Favor composition over inheritance.' Instead of having ColorPoint extend
Point, give ColorPoint a private Point field and a public view method (Item 5) that returns the point at the same
position as this color point"
(I unfortunately do not have Effective Java at hand, so this comment is based mostly on information from:
)
Well, in Java, composition is unusable in some cases (using the example: an instance of ColorPoint cannot be assigned to
variable of type Point). Also, I am not sure how much is this recommendation actually followed in the practice.
The advantage of getClass() != obj.getClass() is that if it fails, it is likely to fail much more predictably. If the
symmetry contract of equals is broken because of use of "instanceof", the behavior of Collections (for example) is
likely to be pretty unpredictable.
Anyway, your patch will be very welcome. But, please introduce an option for the user to choose the behavior.
I have no clue how to implement this. Is it possible to leave it open as an enhancement request and have someone in the
Netbeans team to add it?
Here is an excerpt from the first edition of the book on exactly this topic:
search for "There is simply no way to extend an instantiable class and add an aspect while preserving the equals contract"
In the second edition he goes to say:
"You may hear it said that you can extend an instantiable class and add a value component while preserving the equals
contract by using a getClass test in place of the instanceof test in the equals method:
// Broken - violates Liskov substitution principle (page 40)
@Override public boolean equals(Object o) {
if (o == null || o.getClass() != getClass())
return false;
Point p = (Point) o;
return p.x == x && p.y == y;
}
This has the effect of equating objects only if they have the same implementation class. While this may not seem so bad,
the consequences are unacceptable."
My understanding is that the "liskov substitution principle" simply states that object inheritance involves a "is-a"
relationship. When you use getClass() you violate the basic principal of object-oriented programming (inheritance).
Sure, the equals() contract doesn't explicitly discuss this, but it shouldn't have to: Java is a OOP language. Just my 2
cents.
Reassigning to the subcomponent owner since (as mentioned before) I have no experience working with the Netbeans code.
OK, we will have a look. This functionality should be optional.
Product Version: NetBeans IDE 6.7.1 (Build 200907230233)
In addition, Bloch J. also says that:
"For each "significant" field in the class, check to see if that field of the argument matches the corresponding field
of this.) "
Auto inserted equals() method does not do that:
public class Clazz {
float f;
double d;
public Clazz(float f, double d) {
this.f = f;
this.d = d;
}
}
Auto inserted equals() method: (Alt+Insert -> equals() and hashCode()... -> Select float -> Generate)
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Clazz other = (Clazz) obj;
if (this.f != other.f) {
return false;
}
if (this.d != other.d) {
return false;
}
return true;
}
To add a test case, using the Clazz class above:
Clazz x = new Clazz(Float.NaN);
System.out.print(x.equals(x)); // returns false
However, the Object equals() documentation [1] states that:
"The equals method implements an equivalence relation:
- It is reflexive: For any reference value x, x.equals(x) must return true"
[1]
Integrated into 'main-golden', will be available in build *201002120200* on (upload may still be in progress)
Changeset:
User: Jan Lahoda <jlahoda@netbeans.org>
Log: #156994: use Float.floatToIntBits and Double.doubleToLongBits to compare doubles and floats.
*** Bug 218064 has been marked as a duplicate of this bug. ***
Jan,
This issue was closed as FIXED back in 6.7 but it did not actually fix the problem I reported. It's nice that you fixed handling for float and double, but equals() is still wrong (violates Liskov's substitution principle).
Should I leave this issue as reopened or create a separate issue?
(In reply to comment #9)
> Jan,
>
> This issue was closed as FIXED back in 6.7 but it did not actually fix the
I don't see this issue to be marked as fixed or resolved, and history does not say it ever was. True, the Target Milestone is set to 6.7, which I am going to reset.
> problem I reported. It's nice that you fixed handling for float and double,
I have fixed float and double as the handling was wrong without any discussion.
but
> equals() is still wrong (violates Liskov's substitution principle).
First, I assume these are the equals methods you are proposing to generate:
--------------
public class Test {
public static void main(String... args) {
A a = new A();
B b = new B();
assert a.equals(b) == b.equals(a);
}
static class A {
private int i = 0;
@Override
public int hashCode() {
int hash = 7;
hash = 53 * hash + this.i;
return hash;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof A)) {
return false;
}
final A other = (A) obj;
if (this.i != other.i) {
return false;
}
return true;
}
}
static class B extends A {
private int j = 0;
@Override
public int hashCode() {
int hash = 3;
hash = 61 * hash + this.j;
return hash;
}
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) return false;
if (!(obj instanceof B)) {
return false;
}
final B other = (B) obj;
if (this.j != other.j) {
return false;
}
return true;
}
}
}
--------------
But, these equals methods fail to fulfil the symmetry contract, and the behaviour of such objects is quite unpredictable in Collections - how are we going to respond to bugs claiming (validly, IMO), that the equals implementation is wrong?
Having said that, I am not excluding possibility to eventually introduce a checkbox "Generate equals violating its contract" - you can make that happen faster by providing a patch, though.
Jan,
Can you please clarify how instanceof comparison violates equals() for
Collections?
Also, it's worth noting that the getClass() implementation of equals() violates
symmetry for sub-types that add convenience methods without modifying state.
(In reply to comment #11)
> Jan,
>
> Can you please clarify how instanceof comparison violates equals() for
> Collections?
It can cause surprising or hardly predictable behaviour. Consider this example (an extension of the above):
------
public static void main(String... args) {
A a = new A();
B b = new B();
List<Object> l1 = new ArrayList<Object>();
List<Object> l2 = new ArrayList<Object>();
addUnique(l1, a);
addUnique(l1, b);
addUnique(l2, b);
addUnique(l2, a);
System.err.println("l1.size=" + l1.size());
System.err.println("l2.size=" + l2.size());
}
private static <T> void addUnique(Collection<T> addTo, T toAdd) {
if (!addTo.contains(toAdd)) addTo.add(toAdd);
}
------
It prints this for me:
l1.size=2
l2.size=1
Which I would say is surprising at least. The example is artificial, because I tried to avoid dealing with hashcodes (which begs a question: should "a" and "b" from the example have the same hashcode or not?) - not following the hashcode&equals contracts for objects that are put into HashSet (or used as keys in HashMap) typically leads to hard-to-track bugs.
I realize there are usecases where the subclass is only modifying behavior, not data, where using instanceof is more or less OK. But in other usecases, it is likely to lead to "random" problems, and I prefer generating code that works in most cases, and fails more predictably (allowing to track and fix the failure) over code that works in most cases and fails less predictably.
Good example. I still think you're wrong and I think I've got the proof to back it up...
All object-oriented languages are bound by the rules of Liskov Substitution Principal (LSP) as defined here:. The principal is similar to Design by Contract.
Among other things, it states the following:
1. A method's specification (contract) consists of pre-conditions, post-conditions and invariants.
2. When a subclass inherits from a superclass, it cannot strengthen its pre-conditions, weaken its post-conditions or violate its invariants.
The equals() example you quoted is similar to the often-quoted "A square is not a rectangle" problem. Quoting
"According to geometry, a square is a rectangle, but when it comes to software design... it is not!
The basic problem is that a square has an additional invariant with respect to the rectangle, which is that all the sides are equal and because of that you cannot independently change the height and the width like you would do with a rectangle"
LSP states that square may not inherit from rectangle because replacing a Rectangle with a Square would violate its contract.
In your example, B.equals() violates Object.equals()'s contract because:
1. Object.equals()'s contract of symmetry requires that "A.equals(B) should return true if and only if B.equals(A) returns true".
2. LSP states that if B inherits from A, then you must be able to substitute A with B without any noticeable difference.
3. Taking these two into consideration, A.equals(C) should return the same result as B.equals(C), but it does not.
I'll give you a real-life example of why violating LSP is *very* bad. A few years ago I tried using the RXTX library for serial-port communication. Everything was fine until I wrapped their InputStream implementation in a BufferedInputStream. All of a sudden the code began to blow up at random locations (sometimes inside the JDK codebase!). The specification for InputStream.read() clearly states that -1 denotes the end of stream, but they decided that -1 should mean "there is no data for you to read right now, try again later". Now, because they violated LSP you could not substitute their implementation in place of InputStream. When BufferedInputStream saw -1 it naturally assumed that the end-of-stream had been reached. It would cache this result and never invoke -1 again. Because class inheritance cannot work without LSP.
Here is a final link to prove my point (taking an example from Collections):
.)"
Notice:
1. They remind you that Lists must be equal to other Lists and Sets must be equal to other Sets. They imply that when you implement equals(), you must ensure that this remains true (i.e. don't break symmetry!)
2. You can't break symmetry with respect to interfaces. For example, class "Collection" is not relevant to this discussion because it has no concrete implementation of equals().
3. All concrete classes (e.g. ArrayList, HashMap, TreeMap) extend base classes such as AbstractList or AbstractSet.
4. If you examine their implementation, you will discover that the base classes implement equals() using "instanceof" and none of the subclasses override equals(), precisely to avoid violating LSP.
Phew, that was a long post.
So in summary: code that violates LSP will cause unexpected behavior. equals() is just the tip of the iceberg. using getClass() in equals() is wrong because:
1. It violates LSP itself.
2. Programming errors (such as code that violates LSP) should fail-fast (the earlier the better). We shouldn't be accommodating them any more than we should be accommodating
int count = 5++;
throwing NullPointerException. They *should* cause the application to explode.
I strongly agree with gtzabari. The current equals() implementation generated by NetBeans is dangerous and simply broken, and teaches a wrong pattern. An equals() implementation should by default work like this:
if (obj == null)
return false;
if (obj instanceof ThisType) {
ThisType other = (ThisType) obj;
return this.field == null ? other.field == null : this.field.equals(other.field);
// extend the above to all relevant fields
}
return false;
(In reply to comment #14)
> I strongly agree with gtzabari. The current equals() implementation generated
> by NetBeans is dangerous and simply broken, and teaches a wrong pattern. An
> equals() implementation should by default work like this:
>
> if (obj == null)
> return false;
Correction; these two lines should be:
if (obj == this)
return true;
> if (obj instanceof ThisType) {
> ThisType other = (ThisType) obj;
> return this.field == null ? other.field == null :
> this.field.equals(other.field);
> // extend the above to all relevant fields
> }
> return false;
It would be nice to have this RFE implemented by having the checkbox (not checked by default) in the NetBeans 8.
feel why the fix should be disabled by default.
(In reply to comment #17)
> .
(In reply to comment #18)
>.
Jan,
You won't find Liskov substitution principle mentioned in any Javadoc. It is an architectural-level invariant of all object-oriented languages and affects much more than just Object.equals(). I encourage you to re-read comment #13 for a detailed explanation.
Here is an additional point (on top of comment #13 which I hope you've read by now):
"getClass() != obj.getClass()" prevents you from subclassing. Certainly you can extend a class and make equals() return false, but then you're not really subclassing. What you are doing is implementation inheritance, not behavior inheritance. What you *should* be using is composition:. This is true for C++ as much as it is true for Java.
(In reply to comment #18)
> instanceof of is in general breaking Object.equals contract.
It only does if the wrong type is used on the right-hand side of instanceof. You always have some interface type or common base class that specifies the concrete equals() contract (e.g. "two lists are equal if and only if..."). It's clear that this type is the one that must be used on the RHS of instanceof.
Generally, there are two types of situations:
1) You have a simple value class with just that one implementation. In general such a class should be final. In that case, instanceof is perfectly symmetric and cannot go wrong.
2) You have a base type that specifies an equals() contract with multiple concrete implementations. In this case, the "this.getClass() == obj.getClass()" is likely to be wrong, unless the subclasses happen to represent, without exception, a partioning of the value space of the base type, which in my experience is not too common. It's more likely to have special-case subclasses similar to how for List you have empty-list and singleton-list implementations without every empty or singleton list necessarily being an instanceof the respective class, or to have added-guarantee or added-functionality subclasses like for example how LinkedHashSet is to HashSet.
The problem I have with the "this.getClass() == obj.getClass()" implementation is that it prevents creating subclasses with a compatible and symmetric equals() implementation. Suppose for example that Set was a concrete class instead of an interface (with an implementation like HashSet) and whose equals() implementation would use this test. Then it wouldn't be possible to create a LinkedSet or EnumSet subclass that would be compatible with Set in terms of equals(). All these type-2 situations require use of instanceof.
To me, the rule when implementing equals() is quite simple: Determine which is the type that specifies the particular equals() contract. Then test for instanceof that type. This also has the added benefit that the implementation is self-documenting in which type is the anchor of the equals() contract. When you see "this.getClass() == obj.getClass()", you always have to wonder whether the author did really think things through.
Ideally, the IDE would ask the user for that base type, for the purpose of creating an equals() implementation. Furthermore, the IDE would warn the user if a super class other than Object already provides an equals() implementation.
> Using instanceof is (in general) breaking symmetry and symmetry *is* part of the
Object.equals contract.
I think this example will help get the point across:
1. I create class Rectangle which honors the Object.equals() contract.
2. I create class Square which extends class Rectangle. At this point, Square either violates Object.equals() or LSP.
3. If Rectangle.equals() uses instanceof, then Square violates symmetry.
4. If Rectangle.equals() uses getClass(), then Square violates LSP.
Why does violating LSP matter so much? Consider the following code:
class Test
{
public static void main(String[] args)
{
Square square = new Square(10);
// violates Square invariant which states that width == height
rectangle.setWidth(20);
}
}
Square is exposing implementation details, methods setWidth(), setHeight(), which violate its own invariants. What you should be doing instead is using composition:
class Square
{
private final Rectangle rectangle = ...;
public void setSize(int size)
{
rectangle.setWidth(size);
rectangle.setHeight(size);
}
}
(In reply to comment #21)
> 3. If Rectangle.equals() uses instanceof, then Square violates symmetry.
Huh, why should that be the case?
What would violate symmetry is if Square would override Rectangle's equals() implementation and test for "instanceof Square", because then "new Rectangle(5, 5).equals(new Square(5))" would yield true while "new Square(5).equals(new Rectangle(5, 5))" would yield false. However, there is no necessity for Square to override equals(); and if it does want to override equals(), it should test "instanceof Rectangle" and implement equals() in terms of shape equality to the other Rectangle.
>.)
Regarding LSP: let us imagine a property "an object is only 'equals' to itself". This is definitely true for j.l.Object. But is not true for many subclasses of j.l.Object, which implement their own equals - why is this *not* a violation of LSP?
Regarding Collection.equals and like: yes, (sometimes), there is a way to implement correct equals in that case using instanceof over a super interface. But that is generally not what this feature is doing: this feature is generating equals based on the fields, but doing Collection.equals-like comparison generally requires usage of methods (rather than fields) and very deep understanding of the desired behaviour (List's and Set's equals apparently must be different). This feature is simply intended to relieve the tedious task of creating equals for simple value-holding classes.
Regarding composition: I don't know how it relates to this discussion. Sure, creating Square like above is wrong. Does the IDE suggest to create such Square? How does it do so? What the IDE is trying to do (and should do that by default in the future, IMO) is creating a code that will be behave more predictably if misused. Or is this meant that the IDE should only generate equals for final classes, to encourage composition over inheritance (which seems to be the only feasible explanation for bringing this theme up over and over)? I doubt that would work very well.
Having said all that - I understand there are technologies that basically require instanceof based equals. But that is the only argument so far that seems valid to me to add an option like this.
?
Object provides a _default_ equals() implentation for all types that do not define a different equivalence relation. The contract of Object is NOT "an object is only equal to itself". Rather, that is just the default implementation provided by the Object class; it is not part of Object's interface contract. The contract of Object#equals() is specified by the five bullet points in the Javadoc of the method. Subtypes that, in their contract, define a more concrete equivalence relationship still conform to Object's contract, hence no LSP violation here.
[...]
> This feature is simply intended to relieve the tedious task
> of creating equals for simple value-holding classes.
In my opinion instanceof is perfectly correct for simple value-holding classes.
What I can understand to some degree is if you want to cater to inexperienced developers who don't really understand equals(), and provide a default implementation of equals() that is at least formally correct in the sense that it attempts to guarantee symmetry. However, this is to the detriment to developers like myself who use instanceof according to the principles I outlined in comment #20, and, more importantly, it teaches a pattern which is incorrect in the general case. It is almost never a good idea to have the getClass()-based equality test in a class designed for subclassing; at the same time the use of getClass() in the generated code suggests that it is in particular intended for the case of subclassing.
(In reply to comment #22)
> (In reply to comment #21)
> > 3. If Rectangle.equals() uses instanceof, then Square violates symmetry.
>
> Huh, why should that be the case?
My mistake. instanceof does not violate symmetry but this case would still violate LSP: "Invariants of the supertype must be preserved in a subtype."
> >?
You're confusing implementation details with the method contract. LSP only states that the class and its sub-types must implement the same contract. It does not state that the underlying implementation must remain the same. More specifically, can you provide an example where A is an Object and B is a sub-type, A.equals(B) but !B.equals(A)?
> Having said all that - I understand there are technologies that basically
> require instanceof based equals. But that is the only argument so far that
> seems valid to me to add an option like this.
No. You are missing a fundamental point here: implementations *must* honor LSP, otherwise you are breaking the basic premise behind OOP. The *only* time it is acceptable to use a getClass()-based equals is for final classes. That makes them the exception to the rule, not the opposite.
(In reply to comment #25)
> (In reply to comment #22)
> > .
For an immutable solution you simply wouldn't provide setters. The client code would pass the dimensions of any desired new instance to the constructor, and that's it.
(In reply to comment #26)
> For an immutable solution you simply wouldn't provide setters. The client code
> would pass the dimensions of any desired new instance to the constructor, and
> that's it.
Fair enough, but to reiterate my point: you should never use class inheritance for implementation reuse. In the aforementioned case, the design would be better off using composition and only exposing Square-specific methods. Using immutability doesn't protect you from having to expose Rectangle-specific methods to all subclasses. Once you add a couple of levels of implementation inheritance you end up with a method soup, as we have in Swing.
Getting back to the point. This issue is assigned to Jan and found the sound of it, he's yet to agree that LSP is a fundamental requirement of the Java language. Jan, if this is true, would it be possible to get two other high-ranking committers to weigh in (we need an odd number of people to break a tie)?
Let's not forget about it into the next NetBeans version.
*** Bug 163561 has been marked as a duplicate of this bug. ***
There is just no way to get equals() and hashCode() done right IF you do let JPA set the Id.
The only way it works is by either use a UUID or a manually managed sequence counter and set the Id yourself _before_ you do anything with that entity.
Thus I filed an issue to completely remove equals() and hashCode() at all.
@struberg,
I disagree for two reasons:
1. Non-JPA code is not affected (and it makes up the majority of Java code).
2. I consider JPA, as a technology, to be completely broken. See. As such, I don't use it at all. Take it from someone who used Hibernate for over 4 years, it will cause more pain than it'll solve.
Please update Target Milestone (it is now out of date).
This thread is tl;dr so here goes nothing:
I'd never consider two concrete classes of different `getclass()` types to be equal regardless of `instanceof` relationships.
Take for example EJ Item 8: I consider `Point` and `CounterPoint` instances as always different (`equals()` returns false) just because `Point` has two properties and `CounterPoint` in total has 3 properties.
Another example: I consider `JButton` to be different from `MyJButton extends JButton` even if I only add functionality and no extra properties. If I wanted to know if the properties of my `MyJButton` are the same as that of another `JButton`, I'd compare properties instead of using `equals()`. This also has the advantage of deciding which properties contribute to your definition of 'equality' instead of having the library designers decide that for you.
Zom,
I understand what it is you want, but this is not what equals() is designed for. What you are asking for violates equals() requirement of symmetry (JButton equals MyJButton but the latter is not true).
If you want to add sameClass() to all your implementations so be it, but you can't implement equals() this way without violating the specification. If you do so, you *will* run into problems.
This issue is about Netbeans respecting the Java Specification for Object.equals(). Users who want something different are welcome to declare a different method.
This was reported back in 09. Is there any way that we can get an option to generate the alternate version?
Still there's no conclusion to be implemented, most of the thread tries to present one of the options as the "optimal", but none of them is.
There probably is no good way to implement "correct equals". IMHO, arguments as "this is not what equals was desinged for" are misleading, because in the first place, the Object.equals contract was wrongly designed from the start, as Effective Java book and discussion in this thread shows: equals on subclasses will either break subtyping (use getClass()) or will break symmetry (equals contract - use instanceof).
Given that I do not consider this issue a defect, rather an enhancement because we lack features, the code as it is designed is working well.
In a very few selected cases, it is possible to instanceof compare to base class, but those cases are IMHO not detectable by the IDE.
So the here's the solution:
* add a fix that Object.equals generates instanceof. Add a checkbox to the 'generate hashCode and equals' feature. Add option to hint to choose from instanceof or getClass()
* issue a warning when generating an overriding equals(), while adding some new felds (it would be best to show the warning only if the superclass uses instanceof)
I would go even so far to suggest that the instanceof should be preferred, because for subclasses with not-important fields, instanceof works while getClass() not. But what is a key or unimportant key is a matter of design and THAT's why we choose fields to be included in equals().
It is not effective to add a hint/warning which would warn the user against equals() in a non-final class, since this is how we all write usually.
It COULD be possible to warn if an instance of class A extends B:
1/ is used in a collection, whose type parameter is a class B or superclass of B
2/ type parameter class defines equals
3/ A also defines equals
(4/ or some other subclass of B defines equals - requires index access)
In this case, it is just a matter of optimization of collection operations, whether A.equals(B) or B.equals(A) is called. Sure this does catch only a very few situations and is rather complex.
Svata,
+1. I like the overall direction you are taking this in.
Leave it up the user to decide which form of equals is correct / the one they want.
- A checkbox to use instanceof
- A checkbox to test against super
If instanceof is chosen, we can have a little warning message saying that it breaks the contract for equals / may have undesired side-effects. Also, retain the state of the checkboxes across the running NetBeans session -- in case the user is adding equals/hashCode for a batch of similar classes.
'test against super' checkbox would also apply to hashCode. It would be nice to have 'super' as an option when generating toString as well.
I can try writing a patch for this if someone can point me in the right direction.
I would suggest to not warn against instanceof, at least not unconditionally. Instead I would make instanceof the default as proposed by Svata. Warnings, if any, rather belong in the subclass, like for example FindBugs' EQ_OVERRIDING_EQUALS_NOT_SYMMETRIC and EQ_DOESNT_OVERRIDE_EQUALS.
One way I see it is this:
– Using getClass() prohibits equals()-compatible subclasses
– Using instanceof prohibits equals()-incompatible subclasses (unless the class is abstract)
– For final classes, it doesn't make a difference.
(By equals()-compatible, I mean the situation we have with subclasses of List or Set, for example. By equals()-incompatible, I mean the partitioning of the equality relation that results from using getClass().)
So which option anyone prefers depends on whether one prefers equals()-compatibility or equals()-incompatibility across subclasses. As I believe that classes should only be extended for implementing a subset of the value space of the super class (= LSP-compatible class specialization), and that implementation-only inheritance should be replaced by delegation, I am firmly in the equals()-compatibility camp.
Now, I don't expect to convince everyone to join that camp. But please recognize that it is a sound design philosophy, and that following it _requires_ using instanceof. Hence a general warning against it would be counterproductive.
I second matthies and svata's suggestion [1] but I suggest against using loaded terminology such as "equals-compatible" because users who favor getClass() dispute that their approach cannot be compatible (it is... but for a smaller subset of designs than instanceof).
The key difference between instanceof and getClass() is that the requirement that implementations be "symmetric" (if A equals B, then B must equal A). instanceof can be symmetric in some cases, getClass() can never be.
[1] I am in favor of:
1. Making "instanceof" the default.
2. Warning if a class uses "instanceof" and subclasses override equals/hashCode.
3. Allowing users to configure whether they prefer instanceof or getClass()-based implementations of equals/hashcode on a project-level.
4. Warning if a class uses "getClass()" and has any subclasses.
5. Warnings should appear on the subclasses, not the parent class.
What's being proposed, in terms of FB-style analysis and what not, sounds like a lot of work.
Just give the user the relevant options, with the established standard being the default. Correct me if I'm wrong, but generating equals() with getClass() seems to be the established standard across major Java IDEs -- it's the only option in NetBeans and the default option in Eclipse.
offbynull,
It's not that simple. The entirety of the JDK source-code and many libraries in the wild (e.g. Guava) contradict what you consider to be "standard". I encourage you to read the entire discussion thread to gain a better understanding of why that is.
I think the most important thing at this point is to just get an implementation going. We can worry about finer details later. | https://bz.apache.org/netbeans/show_bug.cgi?id=156994 | CC-MAIN-2020-16 | refinedweb | 5,272 | 55.54 |
First off thanks to anyone willing to give their time to help a newbie.
So im very new to java/programming and im having trouble with a program. I believe the while loop is messed up as im new to using them. The program is used to calculate inflation in price of an object. The user enters the price, amount of years, and percent inflation. When i try to run this, it cannot print my "finalamount" variable, and i cant figure out what i messed up. Any help/suggestions would be great.
import java.util.Scanner; public class inflationcalculator { public static void main(String[] args) { /*Gather user input*/ System.out.print("Input the current cost of the item, just the number:"); Scanner scan = new Scanner(System.in); int amount = scan.nextInt(); System.out.print("Input the rate of inflation, as a percentage without the percent sign:"); int inflat = scan.nextInt(); System.out.print("Input the number of years, must be a whole number:"); int numyear = scan.nextInt(); /*Calculate the inflation according to the users input*/ int counter = 0; double percent = (inflat/100); double amountedit = amount; while(counter < numyear){ double finalamount = (amountedit + (amountedit*percent)); counter++; } /*Print/results screen*/ System.out.print("At "); System.out.print(inflat); System.out.print(" percent inflation per year, the cost in "); System.out.print(numyear); System.out.print(" year(s) will be $"); System.out.print(finalamount); System.out.print("."); } } | http://www.javaprogrammingforums.com/loops-control-statements/14179-while-loop-messed-up.html | CC-MAIN-2014-41 | refinedweb | 233 | 50.12 |
Integrity
Just a simple scheme.
nc 202.120.7.217 8221
The
encrypt function in the scheme takes the username as input. It hashes the username with MD5, appends the name to the hash and encrypts with a secret key
, i.e.
. Then, the secret becomes
. Notably, the first block
contains the hash, but encrypted.
Recall how the decryption is defined:
So, what would happen if we input
as username? Then, we have encrypted
, but we want only
. As mentioned before, the hash fits perfectly into a single block. So, by removing the
,
becomes the new
(which has no visible effect on the plaintext anymore!). Then, we have
, which is all what we need.
The flag is
flag{Easy_br0ken_scheme_cann0t_keep_y0ur_integrity}.
OTP1
I swear that the safest cryptosystem is used to encrypt the secret!
We start off analyzing the code. Seeing
process(m, k) function, we note that this is actually something performed in
with the mapping that, for instance, an integer
is
in binary, which corresponds to a polynomial
. The code is doing
in
.
The
keygen function repeatedly calls
key = process(key, seed). The first value for
key is random, but the remaining ones does not.
seed remains the same. Define
to be the key and
the seed. Note that all elements are in
. The first stream value
is unknown.
So, we can compute the seed and key as
and
. The individual square roots exist and are unique.
def num2poly(num): poly = R(0) for i, v in enumerate(bin(num)[2:][::-1]): if (int(v)): poly += x ** i return poly def poly2num(poly): bin = ''.join([str(i) for i in poly.list()]) return int(bin[::-1], 2) def gf2num(ele): return ele.polynomial().change_ring(ZZ)(2) P = 0x10000000000000000000000000000000000000000000000000000000000000425L fake_secret1 = "I_am_not_a_secret_so_you_know_me" fake_secret2 = "feeddeadbeefcafefeeddeadbeefcafe" secret = str2num(urandom(32)) R = PolynomialRing(GF(2), 'x') x = R.gen() GF2f = GF(2**256, name='a', modulus=num2poly(P)) f = open('ciphertext', 'r') A = GF2f(num2poly(int(f.readline(), 16))) B = GF2f(num2poly(int(f.readline(), 16))) C = GF2f(num2poly(int(f.readline(), 16))) b = GF2f(num2poly(str2num(fake_secret1))) c = GF2f(num2poly(str2num(fake_secret2))) # Retrieve partial key stream using known plaintexts Y = B + b Z = C + c Q = (Z + Y**2) K = (Y + Q).sqrt() print 'flag{%s}' % hex(gf2num(A + K)).decode('hex')
This gives the flag
flag{t0_B3_r4ndoM_en0Ugh_1s_nec3s5arY}.
OTP2
Well, maybe the previous one is too simple. So I designed the ultimate one to protect the top secret!
There are some key insights:
- The
process1(m, k)function is basically the same as in previous challenge, but it computes the multiplication
with the exception that elements are in
this time. We omitt the multiplication symbol from now on.
- The
process2(m, k)function might look involved, but all that it does is to compute the matrix multplication between two
matrices (with elements in
), i.e.,
- We start with matrices
and
.
- Raising
to a power yields has a closed form formula:
.
- The
nextrand(rand)function takes the integral value of
, we call this
and computes
via a square-and-multiply type algorithm. In python, it would be
def proc2(key): AN = A**gf2num(N) return key*AN+(AN+1)/(A+1)*B
Let us look at the
nextrand(rand) function a little more. Let
be the random value fed to the function. Once
is computed, it returns
Define
. Adding this to the above yields
.
So,
. Note that given two elements of the key stream, all these elements are known. Once determined, we compute the (dicrete)
to find
. And once we have
, we also have
. Then, all secrets have been revealed!
From the plaintext, we can immediately get the key
by XORing the first part of the plaintext with the corresponding part of the ciphertext. This gives
.
R = PolynomialRing(GF(2), 'x') x = R.gen() GF2f = GF(2**128, name='a', modulus=num2poly(0x100000000000000000000000000000087)) A = GF2f(num2poly(0xc6a5777f4dc639d7d1a50d6521e79bfd)) B = GF2f(num2poly(0x2e18716441db24baf79ff92393735345)) G1 = GF2f(num2poly(G[1])) G0 = GF2f(num2poly(0x2fe7878d67cdbb206a58dc100ad980ef)) U = B/(A+1) Z = (G1+U)/(G0+U) N = discrete_log(Z, A, K.order()-1)
We can then run the encryption (the default code) with the parameters
fixed to obtain the flag
flag{LCG1sN3ver5aFe!!}.
2 thoughts on “0ctf’17 – All crypto tasks”
What library are you using that providers PolynomialRing and GF?
I run the Python code in Sage. Simply invoke sage -python mycode.py and it will do the job. | https://grocid.net/2017/03/20/0ctf17-all-crypto-tasks/ | CC-MAIN-2018-05 | refinedweb | 727 | 68.97 |
.
docs.python.org/library/profile.html
Thank for responding. I'll have to investigate further, as I'm not sure how to utilise this for an ST TextCommand. That is, am I able to create a separate command that issues the single instruction to 'cProfile.run('MyTextCommand') Praticularly as MyTextCommand is a class.
Actually, no worries
I just used **time.time() **in a couple of spots. It takes 1.35 secs to run my entire procedure, but 1.4 to then open a browser window.
Not the kind of stats I'm going to worry about: Python is pretty impressive
cProfile is great if you have a deep call stack though as it separates the time taken for each method called.
Just rename your current "run" method to "run_real" and create a new run method that does cProfile.run("self.run_real(whatever)", locals(), globals()) or similar.
Thank you. Trying to get this to work:
def run(self, edit, numbers):
cProfile.run("self.real_run(edit, numbers)", locals(), globals())
But receive error "TypeError: coercing to Unicode: need string or buffer, dict found". How can I pass edit (if necessary) and my "numbers" == true/false argument to the .run call please?
Andy.
Apologies, use cProfile.runctx rather than "run"
Hi, thank you. Got it working (it's globals first with runctx ). Andy. | https://forum.sublimetext.com/t/timing-python-execution/5503/6 | CC-MAIN-2016-44 | refinedweb | 219 | 69.58 |
From!...
Just a note: this board was for the QPD not the Bull's eye detector.
tcs_daq
#!/usr/bin/python
# a short script to output low frequency sine wave to EPICS channels
import epics
import math
import time
import os
import random
a =..
Here's the error:
Traceback (most recent call last):
.
Here are some pictures of the ring heater segments destined for the H2 Y-arm this year.
These still need to be put onto ResourceSpace.
For archive purposes, attached is a write-up of all the HWS measurements I've made to date for the SRM CO2 projector mock-up.).
I changed the HWS code to the new git.ligo HWS version.
I've set up some symbolic links to these directories to mimic the old directory structure, so ...
I checked the lab this morning. It was dry and there wall was in the same state as yesterday.
The 200W Thermopile power head from Thorlabs arrive today. The scanned delivery note and calibration info are attached..
Does this work?
Yes.
I noticed that the TCS lab temperature sensor batteries died. Apparently they died two days ago. I swapped in some new batteries this morning....
- Discussed the further project with Dr. Brooks.
-Tried to derive formula for the test mass inside cryogenic shield(infinitely long shield from one side)
-Continued with the same cryogenic model created and varied the length of outer shield and studied the temperature variation inside.
-Compared the temperature difference given by COMSOL with manually calculated one.
-Created a COMSOL model for cryogenically shielded test mass with compensation plate.
-Analyzed the behavior of the model in different size configurations.
-Created a COMSOL model for variation of temperature in two mass system.
-Used the above model for cryogenic conditions.
-checked it analytically.
-Derived formula for manual calculation of temperature due to total influx.
-Compared the results by COMSOL and by the formula.
-Discussed the project outline for next 6 weeks.
-made a write up for the tasks. (attached)
-Analyzed the variation of temperature of the test mass with input power for different lengths of the shield.
-Updated 3 week progress report with new additions and deletions.
-Attended LIGO lecture which was very interesting and full of information.
-Attented LIGO orientation meeting and safety session.
-Prepared 3 week report've started an 80C cure of two materials bonded by EPOTEK 353ND. The objective is to see (after curing) how much the apparent glass transition temperature is increased over a room-temperature cure. | http://nodus.ligo.caltech.edu:8080/TCS_Lab/?new_entries=0&rsort=Subject | CC-MAIN-2022-21 | refinedweb | 414 | 59.8 |
blah blah blah
This is a discussion on need an example within the C++ Programming forums, part of the General Programming Boards category; blah blah blah...
blah blah blah
Last edited by sjcc; 05-07-2009 at 04:21 PM.
What have you done so far? We do not do other homework for you, but we will advice you, if you show us that you are working on it.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
here you go..here you go..Code:#include <iostream> #include <vector> using namespace std; double average(const vector<double>& a); double median(const vector<double>& a); int main() { vector<double> z; z.push_back(32); z.push_back(31); z.push_back(29); z.push_back(30); z.push_back(32); z.push_back(31.4); cout << "The average of the data set is: " << average(z) << ".\n"; cout << "The median of the data set is: " <<median(z) << ".\n"; return 0; } double average(const vector<double>& a) { double sum = 0; unsigned int i; for( i = 0; i < a.size(); i++ ) sum += a[i]; double avg = 0; if (a.size() > 0) avg = sum / a.size(); return avg; } double median(const vector<double>& a) { //first create a duplicate of the vector. //Sort the duplicate, and not the original vector. vector<double> dup = a; sort(dup.begin(), dup.end()); int med_index = dup.size() / 2; double med; if (dup.size()%2 > 0) //odd number of elements: 2 5 10 med = dup[ med_index ]; else { //even number of elements: 3, 4, 9, 10 med = (dup[med_index] + dup[med_index - 1])/2.0; } return med; }
parts of the prob. is to find the median and avg. and no i was not expecting you to do it for me... I was just asking for an example
And is there a problem?
Perhaps the median function should check for empty vector too.
I might be wrong.
Quoted more than 1000 times (I hope).Quoted more than 1000 times (I hope).Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
Second try... The first got lost when I fumbled the touch-pad on my work-laptop...
What is not working with your median/average functions? The look accurate enough to me.
I don't really see the point of passing the vector by reference to median, and then duplicating it. It would be simpler coding wise to just pass it by value and thus creating a copy immediately.
We get A LOT (like a few every day) of people asking similar "can someone give me an example to of ..." in an effort to solve their homework without themselves doing any work, so you have to understand that it's easy to assume that your question is of the same kind.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers. | http://cboard.cprogramming.com/cplusplus-programming/115666-need-example.html | CC-MAIN-2014-10 | refinedweb | 509 | 68.16 |
We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello everybody,recently i am programming with Processing. I want to find interest_points from two image and compare them.But now i meet some questions,my interest_points all draw in the first image. i don't know how to export code with rows,so sorry.
import gab.opencv.*; import surf.*; ArrayList interest_points; ArrayList interest_points_r; float threshold = 640; float balanceValue = 0.9; int octaves = 4; PImage leftimg; PImage rightimg; void setup(){ size(800,800); leftimg=loadImage("left.png"); rightimg=loadImage("right.png"); leftimg.filter(GRAY); rightimg.filter(GRAY); image(leftimg, 0, 0); loadPixels(); SURF_Factory mySURF = SURF.createInstance(leftimg, balanceValue, threshold, octaves, this); Detector detector = mySURF.createDetector(); interest_points = detector.generateInterestPoints(); Descriptor descriptor = mySURF.createDescriptor(interest_points); descriptor.generateAllDescriptors(); drawInterestPoints(); image(rightimg, leftimg.width, 0); SURF_Factory mySURF_r =SURF.createInstance(rightimg, balanceValue,threshold, octaves,this); Detector detector_r = mySURF_r.createDetector(); interest_points_r = detector_r.generateInterestPoints(); Descriptor descriptor_r = mySURF_r.createDescriptor(interest_points_r); descriptor_r.generateAllDescriptors(); drawInterestPoints_r(); } void drawInterestPoints(){ println("Drawing Interest Points..."); for(int i = 0; i < interest_points.size(); i++){ Interest_Point IP = (Interest_Point) interest_points.get(i); IP.drawPosition(); } }
//SURF_Factory mySURF_r =SURF.createInstance(rightimg, balanceValue,threshold, octaves,this);
The"this" controls drawing interest point . In JAVA, I think i should use new to change the point of "this". But the code really confused me . surf.* library is from
Answers
I have corrected the code formatting above to get rid of duplicate code.
@quark I don't know if what you did was helpful. They were trying to do the same thing twice, and so duplicated code might have been showing off what they were trying to accomplish. Without a way to see what your edit was, I am at a loss as to what their actual problem is.
To answer your question, joke,
thisrefers to the object that contains it. In this case, it's the parent PApplication that all your sketch's code is being run inside. There's a bunch of technical things happening under the hood that Processing has just got covered for you, and that you don't need to worry about... and this is one of them. What I'm really trying to say is that the problem isn't with the use of the
thiskeyword. The problem is that you're always drawing interesting points at positions that are over the left image.
My guess, since I can't exactly run this code, is that the position of an interesting point is relative to the top-right corner OF THE IMAGE - not the SKETCH.
So if this is the code that draws interesting points over the left image:
Then this should be the code that draws them over the right image:
Notice how there is a
translate()statement in there? This moves where (0,0) is to the upper left corner of the drawn image, essentially adjusting for the fact that the image is being displayed shifted over to the right a bit. The push/popMatrix() functions save and restore the position without this adjustment.
@TfGuy44 Thank you so much,you are so nice .I have solved my question
@quark I can't see your code,sorry
I think quark means he edited the code in your post...?
@TfGuy44 The OP had trouble formatting the code for the forum so created a new comment with the code in i..e. duplicated code (no change there then !!!)
I simply corrected the formatting in the original comment and deleted the comment with the duplicate code.
@joke I did not add any code, so there was none to see! | https://forum.processing.org/two/discussion/27413/how-to-change-the-point-of-this | CC-MAIN-2021-10 | refinedweb | 600 | 50.73 |
Let’s say it again: Python is a high-level programming language with dynamic typing and dynamic binding. I would describe it as a powerful, high-level dynamic language. Many developers are in love with Python because of its clear syntax, well structured modules and packages, and for its enormous flexibility and range of modern features.
In Python, nothing obliges you to write classes and instantiate objects from them. If you don’t need complex structures in your project, you can just write functions. Even better, you can write a flat script for executing some simple and quick task without structuring the code at all.
At the same time Python is a 100 percent object-oriented language. How’s that? Well, simply put, everything in Python is an object. Functions are objects, first class objects (whatever that means). This fact about functions being objects is important, so please remember it.
So, you can write simple scripts in Python, or just open the Python terminal and execute statements right there (that’s so useful!). But at the same time, you can create complex frameworks, applications, libraries and so on. You can do so much in Python. There are of course a number of limitations, but that’s not the topic of this article.
However, because Python is so powerful and flexible, we need some rules (or patterns) when programming in it. So, let see what patterns are, and how they relate to Python. We will also proceed to implement a few essential Python design patterns.
Why Is Python Good For Patterns?
Any programming language is good for patterns. In fact, patterns should be considered in the context of any given programming language. Both the patterns, language syntax and nature impose limitations on our programming. The limitations that come from the language syntax and language nature (dynamic, functional, object oriented, and the like) can differ, as can the reasons behind their existence. The limitations coming from patterns are there for a reason, they are purposeful. That’s the basic goal of patterns; to tell us how to do something and how not to do it. We’ll speak about patterns, and especially Python design patterns, later.
Python’s philosophy is built on top of the idea of well thought out best practices. Python is a dynamic language (did I already said that?) and as such, already implements, or makes it easy to implement, a number of popular design patterns with a few lines of code. Some design patterns are built into Python, so we use them even without knowing. Other patterns are not needed due of the nature of the language.
For example, Factory is a structural Python design pattern aimed at creating new objects, hiding the instantiation logic from the user. But creation of objects in Python is dynamic by design, so additions like Factory are not necessary. Of course, you are free to implement it if you want to. There might be cases where it would be really useful, but they’re an exception, not the norm.
What is so good about Python’s philosophy? Let’s start with this (explore it in the Python terminal):
> >> might not be patterns in the traditional sense, but these are rules that define the “Pythonic” approach to programming in the most elegant and useful fashion.
We have also PEP-8 code guidelines that help structure our code. It’s a must for me, with some appropriate exceptions, of course. By the way, these exceptions are encouraged by PEP-8 itself:
But most importantly: know when to be inconsistent – sometimes the style guide just doesn’t apply. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don’t hesitate to ask!
Combine PEP-8 with The Zen of Python (also a PEP - PEP-20), and you’ll have a perfect foundation to create readable and maintainable code. Add Design Patterns and you are ready to create every kind of software system with consistency and evolvability.
Python Design Patterns
What Is A Design Pattern?
Everything starts with the Gang of Four (GOF). Do a quick online search if you are not familiar with the GOF.
Design patterns are a common way of solving well known problems. Two main principles are in the bases of the design patterns defined by the GOF:
- Program to an interface not an implementation.
- Favor object composition over inheritance.
Let’s take a closer look at these two principles from the perspective of Python programmers.
Program to an interface not an implementation
Think about Duck Typing. In Python we don’t like to define interfaces and program classes according these interfaces, do we? But, listen to me! This doesn’t mean we don’t think about interfaces, in fact with Duck Typing we do that all the time.
Let’s say some words about the infamous Duck Typing approach to see how it fits in this paradigm: program to an interface.
We don’t bother with the nature of the object, we don’t have to care what the object is; we just want to know if it’s able to do what we need (we are only interested in the interface of the object).
Can the object quack? So, let it quack!
try: bird.quack() except AttributeError: self.lol()
Did we define an interface for our duck? No! Did we program to the interface instead of the implementation? Yes! And, I find this so nice.
As Alex Martelli points out in his well known presentation about Design Patterns in Python, “Teaching the ducks to type takes a while, but saves you a lot of work afterwards!”
Favor object composition over inheritance
Now, that’s what I call a Pythonic principle! I have created fewer classes/subclasses compared to wrapping one class (or more often, several classes) in another class.
Instead of doing this:
class User(DbObject): pass
We can do something like this:
class User: _persist_methods = ['get', 'save', 'delete'] def __init__(self, persister): self._persister = persister def __getattr__(self, attribute): if attribute in self._persist_methods: return getattr(self._persister, attribute)
The advantages are obvious. We can restrict what methods of the wrapped class to expose. We can inject the persister instance in runtime! For example, today it’s a relational database, but tomorrow it could be whatever, with the interface we need (again those pesky ducks).
Composition is elegant and natural to Python.
Behavioral Patterns
Behavioural Patterns involve communication between objects, how objects interact and fulfil a given task. According to GOF principles, there are a total of 11 behavioral patterns in Python: Chain of responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template, Visitor.
I find these patterns very useful, but this does not mean the other pattern groups are not.
Iterator
Iterators are built into Python. This is one of the most powerful characteristics of the language. Years ago, I read somewhere that iterators make Python awesome, and I think this is still the case. Learn enough about Python iterators and generators and you’ll know everything you need about this particular Python pattern.
Chain of responsibility
This pattern gives us a way to treat a request using different methods, each one addressing a specific part of the request. You know, one of the best principles for good code is the Single Responsibility principle.
Every piece of code must do one, and only one, thing.
This principle is deeply integrated in this design pattern.
For example, if we want to filter some content we can implement different filters, each one doing one precise and clearly defined type of filtering. These filters could be used to filter offensive words, ads, unsuitable video content, and so on.
class ContentFilter(object): def __init__(self, filters=None): self._filters = list() if filters is not None: self._filters += filters def filter(self, content): for filter in self._filters: content = filter(content) return content filter = ContentFilter([ offensive_filter, ads_filter, porno_video_filter]) filtered_content = filter.filter(content)
Command
This is one of the first Python design patterns I implemented as a programmer. That reminds me: Patterns are not invented, they are discovered. They exist, we just need to find and put them to use. I discovered this one for an amazing project we implemented many years ago: a special purpose WYSIWYM XML editor. After using this pattern intensively in the code, I read more about it on some sites.
The command pattern is handy in situations when, for some reason, we need to start by preparing what will be executed and then to execute it when needed. The advantage is that encapsulating actions in such a way enables Python developers to add additional functionalities related to the executed actions, such as undo/redo, or keeping a history of actions and the like.
Let’s see what a simple and frequently used example looks like:
class RenameFileCommand(object): def __init__(self, from_name, to_name): self._from = from_name self._to = to_name def execute(self): os.rename(self._from, self._to) def undo(self): os.rename(self._to, self._from) class History(object): def __init__(self): self._commands = list() def execute(self, command): self._commands.append(command) command.execute() def undo(self): self._commands.pop().undo() history = History() history.execute(RenameFileCommand('docs/cv.doc', 'docs/cv-en.doc')) history.execute(RenameFileCommand('docs/cv1.doc', 'docs/cv-bg.doc')) history.undo() history.undo()
Creational Patterns
Let’s start by pointing out that creational patterns are not commonly used in Python. Why? Because of the dynamic nature of the language.
Someone wiser than I once said that Factory is built into Python. It means that the language itself provides us with all the flexibility we need to create objects in a sufficiently elegant fashion; we rarely need to implement anything on top, like Singleton or Factory.
In one Python Design Patterns tutorial, I found a description of the creational design patterns that stated these design “patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using a new operator.”
That pretty much sums up the problem: We don’t have a new operator in Python!
Nevertheless, let’s see how we can implement a few, should we feel we might gain an advantage by using such patterns.
Singleton
The Singleton pattern is used when we want to guarantee that only one instance of a given class exists during runtime. Do we really need this pattern in Python? Based on my experience, it’s easier to simply create one instance intentionally and then use it instead of implementing the Singleton pattern.
But should you want to implement it, here is some good news: In Python, we can alter the instantiation process (along with virtually anything else). Remember the
__new__() method I mentioned earlier? Here we go:
class Logger(object): def __new__(cls, *args, **kwargs): if not hasattr(cls, '_logger'): cls._logger = super(Logger, cls ).__new__(cls, *args, **kwargs) return cls._logger
In this example, Logger is a Singleton.
These are the alternatives to using a Singleton in Python:
- Use a module.
- Create one instance somewhere at the top-level of your application, perhaps in the config file.
- Pass the instance to every object that needs it. That’s a dependency injection and it’s a powerful and easily mastered mechanism.
Dependency Injection
I don’t intend to get into a discussion on whether dependency injection is a design pattern, but I will say that it’s a very good mechanism of implementing loose couplings, and it helps make our application maintainable and extendable. Combine it with Duck Typing and the Force will be with you. Always.
I listed it in the creational pattern section of this post because it deals with the question of when (or even better: where) the object is created. It’s created outside. Better to say that the objects are not created at all where we use them, so the dependency is not created where it is consumed. The consumer code receives the externally created object and uses it. For further reference, please read the most upvoted answer to this Stackoverflow question.
It’s a nice explanation of dependency injection and gives us a good idea of the potential of this particular technique. Basically the answer explains the problem with the following example: Don’t get things to drink from the fridge yourself, state a need instead. Tell your parents that you need something to drink with lunch.
Python offers us all we need to implement that easily. Think about its possible implementation in other languages such as Java and C#, and you’ll quickly realize the beauty of Python.
Let’s think about a simple example of dependency injection:
class Command: def __init__(self, authenticate=None, authorize=None): self.authenticate = authenticate or self._not_authenticated self.authorize = authorize or self._not_autorized def execute(self, user, action): self.authenticate(user) self.authorize(user, action) return action() if in_sudo_mode: command = Command(always_authenticated, always_authorized) else: command = Command(config.authenticate, config.authorize) command.execute(current_user, delete_user_action)
We inject the authenticator and authorizer methods in the Command class. All the Command class needs is to execute them successfully without bothering with the implementation details. This way, we may use the Command class with whatever authentication and authorization mechanisms we decide to use in runtime.
We have shown how to inject dependencies through the constructor, but we can easily inject them by setting directly the object properties, unlocking even more potential:
command = Command() if in_sudo_mode: command.authenticate = always_authenticated command.authorize = always_authorized else: command.authenticate = config.authenticate command.authorize = config.authorize command.execute(current_user, delete_user_action)
There is much more to learn about dependency injection; curious people would search for IoC, for example.
But before you do that, read another Stackoverflow answer, the most upvoted one to this question.
Again, we just demonstrated how implementing this wonderful design pattern in Python is just a matter of using the built-in functionalities of the language.
Let’s not forget what all this means: The dependency injection technique allows for very flexible and easy unit-testing. Imagine an architecture where you can change data storing on-the-fly. Mocking a database becomes a trivial task, doesn’t it? For further information, you can check out Toptal’s Introduction to Mocking in Python.
You may also want to research Prototype, Builder and Factory design patterns.
Structural Patterns
Facade
This may very well be the most famous Python design pattern.
Imagine you have a system with a considerable number of objects. Every object is offering a rich set of API methods. You can do a lot of things with this system, but how about simplifying the interface? Why not add an interface object exposing a well thought-out subset of all API methods? A Facade!
Python Facade design pattern example:
class Car(object): def __init__(self): self._tyres = [Tyre('front_left'), Tyre('front_right'), Tyre('rear_left'), Tyre('rear_right'), ] self._tank = Tank(70) def tyres_pressure(self): return [tyre.pressure for tyre in self._tyres] def fuel_level(self): return self._tank.level
There is no surprise, no tricks, the
Car class is a Facade, and that’s all.
Adapter
If Facades are used for interface simplification, Adapters are all about altering the interface. Like using a cow when the system is expecting a duck.
Let’s say you have a working method for logging information to a given destination. Your method expects the destination to have a
write() method (as every file object has, for example).
def log(message, destination): destination.write('[{}] - {}'.format(datetime.now(), message))
I would say it is a well written method with dependency injection, which allows for great extensibility. Say you want to log to some UDP socket instead to a file,you know how to open this UDP socket but the only problem is that the
socket object has no
write() method. You need an Adapter!
import socket class SocketWriter(object): def __init__(self, ip, port): self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self._ip = ip self._port = port def write(self, message): self._socket.send(message, (self._ip, self._port)) def log(message, destination): destination.write('[{}] - {}'.format(datetime.now(), message)) upd_logger = SocketWriter('1.2.3.4', '9999') log('Something happened', udp_destination)
But why do I find adapter so important? Well, when it’s effectively combined with dependency injection, it gives us huge flexibility. Why alter our well-tested code to support new interfaces when we can just implement an adapter that will translate the new interface to the well known one?
You should also check out and master bridge and proxy design patterns, due to their similarity to adapter. Think how easy they are to implement in Python, and think about different ways you could use them in your project.
Decorator
Oh how lucky we are! Decorators are really nice, and we already have them integrated into the language. What I like the most in Python is that using it teaches us to use best practices. It’s not that we don’t have to be conscious about best practices (and design patterns, in particular), but with Python I feel like I’m following best practices, regardless. Personally, I find Python best practices are intuitive and second nature, and this is something appreciated by novice and elite developers alike.
The decorator pattern is about introducing additional functionality and in particular, doing it without using inheritance.
So, let’s check out how we decorate a method without using built-in Python functionality. Here is a straightforward example.
def execute(user, action): self.authenticate(user) self.authorize(user, action) return action()
What is not so good here is that the
execute function does much more than executing something. We are not following the single responsibility principle to the letter.
It would be good to simply write just following:
def execute(action): return action()
We can implement any authorization and authentication functionality in another place, in a decorator, like so:
def execute(action, *args, **kwargs): return action()dError return decorated execute = authenticated_only(execute) execute = authorized_only(execute)
Now the
execute() method is:
- Simple to read
- Does only one thing (at least when looking at the code)
- Is decorated with authentication
- Is decorated with authorization
We write the same using Python’s integrated decorator syntax:Error return decorated @authorized_only @authenticated_only def execute(action, *args, **kwargs): return action()
It is important to note that you are not limited to functions as decorators. A decorator may involve entire classes. The only requirement is that they must be callables. But we have no problem with that; we just need to define the
__call__(self) method.
You may also want to take a closer look at Python’s functools module. There is much to discover there!
Conclusion
I have shown how natural and easy is to use Python’s design patterns, but I have also shown how programming in Python should be easy going, too.
“Simple is better than complex,” remember that? Maybe you have noticed that none of the design patterns is fully and formally described. No complex full-scale implementations were shown. You need to “feel” and implement them in the way that best fits your style and needs. Python is a great language and it gives you all the power you need to produce flexible and reusable code.
However, it gives you more than that. It gives you the “freedom” to write really bad code. Don’t do it! Don’t Repeat Yourself (DRY) and never write code lines longer than 80 characters. And don’t forget to use design patterns where applicable; it’s one of the best ways to learn from others and gain from their wealth of experience free of charge. | https://www.toptal.com/python/python-design-patterns | CC-MAIN-2019-39 | refinedweb | 3,274 | 57.06 |
Amusing C++
Lisa Simpson gave three apples to her brother Bart, then took back one.
Q.: How many apples does Bart have?
A.: Who knows? We're still unaware of how many apples he had to start!
Can C++ be funny? Let's check it out! Here are some examples that gladden the programmer's eye. Enjoy looking at them!
int a = 5; int b = a++ + ++a;
What does b equal? Are you sure? :) The point is that the right value lies somewhere between 10 and 14! My GCC returns 12, but that's not the limit yet! The C++ Standard does not presuppose the calculation of the ++ operator before the assignment operator is done - so that the answer may vary depending on the compiler; it may even depend on the optimization keys. Note that the result of the operation i = i++ is not defined either! People who want to learn more, can google "C++ sequence point", while we go on!
What do you think - is this code workable?
int i[i]; int j = j; x x; int y::y = x.x;
Strange as it may seem, it is - if we do like this:
const int i = 1; const int j = 2; struct x { int x; }; namespace y { int i[i]; int j = j; x x; int y::y = x.x; };
Visibility overlap did its dirty deed! :) However, MSVC does not accept such code: it considers the declaration of int x to be a declaration of the constructor (the latter, as is known, cannot return a value). And, what's even worse, the namespaced variable j will have an unexpected value, though it is "initialized". So, this clearly indicates that such "tricks" are not worth being played!
Let's go on with the next example. Here's another nice code I've gotten you into! :) This one marked the beginning of my collection of C++ pranks, and I like it the most. Apart from being a really cool prank, it also comprises a psychological trick. Just look at this:
T t1; T t2(t1); T t3 = t1; T t4();
Which constructor will be called in each of these four cases? If you have decided that those must be:
- default constructor,
- copy constructor,
- assignment operator, and
- default constructor again,
int func();
If you made no mistakes, congratulations! If you made one nevertheless and are now craving another chance to win, here's a new opportunity for you! Suppose you have this class:
class C { public: C() { printf("default\n"); } C(long) { printf("long\n"); } explicit C(int) { printf("int\n"); } C(const C&) { printf("copy\n"); } C &operator=(const C&) { printf("op=\n"); return *this; } };
Also, you have a code that involves it:
void prn(int n) { cout << n << ": "; } int main() { const int i = 0; prn(1); C c1(); prn(2); C c2 = i; prn(3); C c3(i); prn(4); C c4 = C(i); prn(5); C c5 = (C) i; prn(6); C c6 = static_cast
(i); return 0; }
What will be displayed on the screen then? To be honest, I made a mistake myself here. And that mistake was severe and reiterated :) So, please be extremely focused. Done? The right answer is:
1: 2: long 3: int 4: int 5: int 6: int
Naturally, one is blank; as you remember, it is a function declaration. Two did not manage to build a class from int, since the int-constructor is specified as explicit; however, the compiler obligingly converted int into long - where its own constructor already exists. The rest of options are variations on a theme of C(i), although differently decorated. I cannot but admire the competence of the translator, which used neither excessive copy constructor, nor assignment constructor, nor even default constructor. C++ at its best!
Here's the last example - maybe the most "practical" among those cited. Suppose you need to create a cycle in which the value of a variable tends to zero. Certainly, you can use the operator for. But we can also do like this!
int i = 10; while (i --> 0) { cout << i << endl; }
This thingamajig is called "arrow operator", just in case.
Here were the tricks originating in our more-than-native language. And then, C++0x may well come, which conceals many such pranks, I guess. As for now, let's keep in mind that this code is nothing but a joke - it ain't a blueprint for action! :)
Table of authorities
- C++ Standard
- Herb Sutter, Exceptional C++ (Addison-Wesley, 2000, ISBN 0-201-61562-2)
- Internet surfing
There are no comments yet. Be the first to comment! | http://www.codeguru.com/cpp/article.php/c19303/Amusing-C.htm | CC-MAIN-2017-26 | refinedweb | 766 | 72.66 |
With the end of the year just around the corner, ReSharper 10 released less than two months ago, and having just released our second maintenance release, it’s a perfect time to take a look at some of the extensions we’ve got available for ReSharper 10.
ReSharper provides a very rich extensibility platform. It is a very modular application, composing functionality and features via a component container. Extensions can extend existing functionality, such as adding items to the Alt+Enter menu, or new inspections and Quick Fixes, or add new functionality, such as support for new languages, or synchronising settings via DropBox.
We currently have about 60 extensions available in the Extension Manager for ReSharper 10. If you haven’t yet had a look to see what’s available, grab yourself a coffee and we’ll take a wander through some of what’s out there. If you see anything you like, head over to the Extension Manager under the ReSharper menu, and search for the extension you want.
ZenSharp
The ZenSharp extension is like ReSharper’s Live Templates on steroids. While Live Templates will expand a static shortcut (like tm) into a code snippet (such as a test method), ZenSharp uses “dynamic” shortcuts to customise the generated snippet.
For example, pc will expand to public class $Name { }, where $Name is a standard Live Template “hotspot” to edit the class name. But pcPerson will expand to public class Person { }.
Similarly, pmSayHello will expand to public void SayHello() { }. And pmsSayHello will expand to public string SayHello() { }.
The shortcuts are defined to be intuitive mnemonics that can be combined and built up to make it easy and fast to create classes, methods, properties, fields and so on. Standard types can be specified as part of the mnemonic shortcut, and once you’ve mastered it, there’s no faster way to create types and type members.
Enhanced Tooltips
The Enhanced Tooltip extension gives ReSharper’s tooltips a facelift. While this doesn’t exactly sound like it’s a big deal, it has a surprising impact – tooltips and parameter info popups in C# are rendered with syntax highlighting, which makes quickly reading parameter lists and method names a whole lot easier.
Furthermore, the tooltips that appear for ReSharper’s inspection warnings and suggestions are also syntax highlighted, with any member names in the message being rendered correctly, and an icon showing what kind of message is being displayed. ReSharper never looked so good!
ReSpeller
Office has it, so why shouldn’t ReSharper? Spelling, that is, and the ReSpeller extension provides just that. It’s available in Free and Pro versions and will look for typos in different languages, such as C#, VB and XML, and even differentiates between identifiers, string literals and comments. For example, you can configure typos in identifiers to be shown as a “hint”, and change typos in comments (such as XML documentation) to be “warning”. And it understands “CamelCasing”, treating “SayHelo” as two words, and finding the typo in “hello”.
It also supports the Alt+Enter menu, offering a Quick Fix to replace the typo, or options to add the word to the user dictionary.
The Pro edition adds extra features, like enabling support for extra languages (such as JavaScript, HTML and Razor), multiple language support and even spell checking directly in the Rename refactoring dialog box!
StyleCop
While the StyleCop project itself has stalled, there are still many people using it to maintain a very consistent style when writing code within a team. The StyleCop extension provides as-you-type inspections to highlight when your code doesn’t match the expected style. It also configures ReSharper so that the code ReSharper produces or formats is in the correct style.
We find ourselves in the unfortunate position of having two different StyleCop extensions available in the Extension Manager (it’s a long story, sadly, and we’re working to resolve it). We strongly recommend you use the StyleCop by JetBrains version (search for “StyleCop by JetBrains” in the Extension Manager), as it fixes many issues, including exceptions and memory leaks, and implements improved performance throttling. It also doesn’t need the StyleCop Visual Studio plugin installed.
One thing to note is that StyleCop itself does not support C# 6. The StyleCop engine that the extension uses has a custom C# parser, rather than using ReSharper’s already parsed abstract syntax trees (one cause for performance issues), and due to the project stalling, the parser hasn’t been updated for C# 6. If you’re using Visual Studio 2015 and C# 6, we recommend you use the StyleCopAnalyzers project, which has full support for C# 6, including new rules. When the StyleCop by JetBrains extension sees that StyleCopAnalyzers is installed, it disables its own as-you-type analysis, but still provides code cleanup features and configures ReSharper to match the StyleCop settings.
Extra inspections
Some extensions are designed to add new inspections, and we’ll take a look at two – Cyclomatic Complexity and Heap Allocations Viewer.
The Cyclomatic Complexity extension calculates the cyclomatic complexity of a block of code. This is a measurement of how complex your code is, and you should ideally be aiming for a very low figure – the higher the value, the more complex the code, and the harder it is to maintain and understand. The value is always shown in a tooltip, and if it’s over a certain configurable threshold, the method name (or similar) is highlighted as a warning. The extension works with C#, VB, JavaScript, TypeScript and C++.
The Heap Allocation Viewer extension highlights all allocations made by your code. This is an interesting extension, because it doesn’t indicate that anything is actually wrong, but it’s intended to make you aware that an allocation happens here. This is very useful when writing performance critical code, when you really need to keep track of all allocations. While it’s obvious that the new statement will allocate memory, this extension will also highlight less obvious allocations, such as boxing, string allocation, allocations when iterating with a foreach loop, and so on.
Working with open source libraries
While some extensions are designed to provide new functionality across the product (such as improving the editing experience, or more inspections for your code), others are designed for a specific library or framework.
A good example of this is support for AngularJS, parsing your JavaScript code to pull out Angular directives, and add them to your HTML code completion. It will also provide improved code completion for the services and providers injected into controllers and directives.
Similarly, Unity support provides features for users of Unity 3D. It will mark methods and fields used by Unity as being in use when Solution Wide Analysis is enabled, generate message handlers via the Generate Code command and automatically mark a C# project as C# 5, so ReSharper won’t suggest incompatible C# 6 features when the project is opened in Visual Studio 2015.
Working with commercial libraries
A very nice use of ReSharper extensions is supporting commercial frameworks and products. The team at Trackerbird have done just that, and released an extension that will make it very easy for you to integrate their analysis SDK into your own project. Once installed, this extension adds an item to the ReSharper menu, offering options to set up the SDK in your project, add simple or detailed event tracking code to your project, help you implement checking for updates and so on. It also includes a context action on Application.Run that will add the code necessary to initialise and start activity tracking in your app.
Please check out the Trackerbird blog for more details.
Annotations
ReSharper extensions are not just about custom code adding new items to the Alt+Enter menu, but can also include “external annotations”. These are files that contain annotations for pre-compiled assemblies that in turn provide hints to ReSharper’s inspections, resulting in better analysis for features such as null analysis, string formatting highlighting and telling ReSharper that type members are used externally from the code. Here are some annotations packages:
- Community External Annotations – this is a nice open source project that maintains annotations for a number of third party libraries, as well as adding extra support for various BCL libraries. You can see the list of supported assemblies in the project readme. Contributions welcome!
- NLog Annotations – adds null analysis and string formatting highlighting annotations for the NLog framework.
- Caliburn.Light Annotations – adds annotations for the Caliburn.Light MVVM framework
Live Templates
Alongside external annotations, ReSharper extensions can also include settings files, which are automatically merged into ReSharper’s settings (technically, they override ReSharper’s defaults, and can get overwritten by your own settings). One of the more interesting uses for this is to package up a settings file that contains Live Templates.
There are several such packages available in the Extension Manager, such as:
- SpecsFor templates for the SpecsFor BDD framework
- Joar Øyen’s Live Template Macros – adding templates for BDD and a macro that converts a Live Template “hotspot” into a “snake_case_identifier”, such as given_a_new_customer .
Presentation Assistant
This extension is very useful when you find yourself giving a presentation. It will display the name of the last command run, and the keyboard shortcuts used to run it, allowing everyone to follow along with the steps you make as you make them. It shows both ReSharper and Visual Studio commands, and can be enabled from the ReSharper → Tools → Presentation Assistant.
It’s also useful for pair programming, to stop the “how did you do that?!” questions as you show off your mad keyboard skillz.
Working with settings files
Two useful extensions for working with settings files are ReSharper Solution Settings Autodiscovery and JetBox.
ReSharper already allows you to share settings files per-solution, by creating a .sln.DotSettings file that lives next to your solution file. But this needs setting up for each solution – what if your team has a number of solutions that you want to work with?
The ReSharper Solution Settings Autodiscovery extension will look for a settings file in each of the parent folders when opening a solution. So if your solution is in C:\projects\team\solution\mySolution.sln, this plugin will look for any file that ends in *.AutoLoad.DotSettings in any of the parent folders – C:\projects\team\solution, C:\projects\team, C:\projects and so on, up to the root of the drive. This is ideal when working on a source control check out that has multiple solutions, and allows you to easily share settings between all of them, and still have the file checked into source control.
The JetBox extension will sync your global settings via DropBox. Simply log in to DropBox via the options page, and the global settings file will be synced whenever there are any changes. And because ReSharper automatically refreshes the settings in any running instances whenever the file changes, you don’t even need to close and reopen Visual Studio for the changes to take effect.
And Finally…
It doesn’t have to be all work and no play. We’ve got a couple of fun extensions too. Check out ReMoji, to add support for JBEvain’s EmojiVS extension to ReSharper’s code completion (make sure you read the instructions for installing first!)
And of course, who can forget Clippy?
We hope you’ve found this look at some of the extensions available for ReSharper 10 useful. It’s by no means all of the extensions that are out there, so please, have a scroll through the Extension Manager, and see if there’s anything else there that interests you.
Pingback: The Morning Brew - Chris Alcock » The Morning Brew #1996
Hi Matt, tried to install Clippy (yes, really) but it didn’t work
“Error resolving type DoubleAgent.Control.Character from assembly “DoubleAgent.Control, Version=1.2.0.55, Culture=neutral, PublicKeyToken=69c93fb14342e6fc”, request originating from assembly “CitizenMatt.ReSharper.Plugins.Clippy, Version=1.2.0.0, Culture=neutral, PublicKeyToken=null”. Could not find a referenced assembly by the TT_ASSEMBLYREF token.”
Seems like a dependency is missing in the package?!
That file is in the package. Was that an error in the installer, or from ReSharper/Visual Studio itself? If it’s the installer, I think you can safely ignore it – try opening a solution and see if Clippy appears.
I am not seeing all\any of the extensions mentioned, do I need to add a URI to the Extension Manager? Or what URI’s should be used in the Extension Managger?
Dave
In the Extension Manager options, you should have the “.NET Products Gallery” item with the URL:. The “.NET Products Gallery” source should be checked, and there should only be one (if there is more than one item with the same name, it can cause issues).
Are you behind a proxy or corporate firewall?
That fixed it, it was set to:.
I can’t see any R# extensions, either and yes I’m behind a proxy and a corporate firewall.
I had the same problem. I changed the URL to the extensions to be http instead of https and that did the trick for me. The setting is in ReSharper/Options/Environment/ExtensionManager.
Pingback: 27-12-2015 - This is the end of this year... so these are the leftover links - Magnus Udbjørg
Pingback: Les liens de la semaine – Édition #164 | French Coding
Pingback: Xamarin Link Roundup – 29 December 2015 — Kym Phillpotts
Hadi Hariri’s CleanCode plugin () is not compatible with Resharper 10 but has some good rules.
Can you suggest a replacement? Something that can warnings if an expression is breaking the Law of Demeter? Or one for when a constructor has too many parameters, indicating too many dependencies?
I just put two and two together and realized you were a contributer on Clean Code. I’ve messaged the other contributes including Hadi Hariri, but I think he is very busy working on Project Rider.
Yes, sorry, CleanCode hasn’t been updated in a while. I’ve got a list of plugins to update as part of the forthcoming 2016.1 (aka 10.1) release, and it’s definitely a part of that.
Hello, with respect to coding standard – do resharper covers all the features that StyleCop provides?
The StyleCop plugin will run all of the standard StyleCop inspections, and display them in the editor. A number of them also include Alt+Enter quick fixes to automatically fix the issues. | https://blog.jetbrains.com/dotnet/2015/12/22/end-of-year-round-up-of-resharper-10-extensions/ | CC-MAIN-2019-51 | refinedweb | 2,417 | 52.19 |
27 January 2010 23:59 [Source: ICIS news]
LONDON (ICIS news)--First-quarter European melamine contracts have been agreed up €120-150/tonne ($169-211/tonne) from the previous quarter, in line with low stock levels and sustainable demand, sources confirmed on Wednesday.
Depending on the location, and at what levels fourth-quarter contracts settled, most sources agreed to increases of €120-150/tonne, bringing first-quarter prices to €1,020-1,100/tonne FD (free delivered) NWE (northwest Europe).
“The majority of my big contracts settled at increases of €130-150/tonne,” one producer said.
Other sellers had previously confirmed increases of €130-175/tonne, but added that not all of the high numbers were representative of the NWE market.
Most buyers agreed to slightly lower price rises of €110-150/tonne, with one consumer explaining that it needed the product and therefore had to accept the increases.
Across the chain, players agreed that stock levels were not as low as had previously been forecast in December, but a lack of imports – especially from China, where ongoing tightness had kept prices high – meant that European producers had been in the driving seat during the negotiations.
In addition, it was no secret that producers were trying to regain some of their lost margins ahead of the anticipated imports that were expected to arrive from two new plants due to come on stream this year in Trinidad and Qatar.
Sources said domestic demand was not as strong as most had anticipated in December, which was partly caused by extended shutdowns and partly by higher-than-expected stock levels.
Overall, however, most players agreed that volumes for the first quarter were up from the same period last year but flat compared with the fourth quarter.
Domestic spot prices were expected to go up in line with the first-quarter contracts. But most players agreed that, for the time being, they should be kept stable at €950-1,020/tonne FD NWE.
Import levels were also unchanged at $1,250-1,350/tonne T1 CIF (cost, insurance and freight) European Main Port.
On Wednesday afternoon, Chinese spot prices were assessed stable to soft, as buying resistance grew stronger.
Several major melamine producers in ?xml:namespace>
Asian contract negotiations for the first quarter were still ongoing, with most producers targeting a $200-300/tonne price hike compared with the fourth quarter.
There was no news yet on developments with US melamine contracts.
Fourth-quarter European melamine contracts were agreed at €900-1,050/tonne FD NWE.
($1 = €0.71)
Please visit the complete ICIS plants and projects database. | http://www.icis.com/Articles/2010/01/27/9329222/europe+q1+melamine+contracts+settle+up+at+1020-1100tonne.html | CC-MAIN-2013-20 | refinedweb | 434 | 57.71 |
In HTML, it is actually possible to embed raw image data directly into HTML so that separate image files are not needed. This can speed up HTTP transfers in many cases, but there are compatibility issues especially with Internet Explorer up to and including version 8. This short article will show an easy way to extract these images and convert the HTML to use external images.
Normally images are included using this syntax:
<img src="Image1.png">
The data URI syntax however allows images to be directly embedded, reducing the number of HTTP requests and also allowing for saving on disk as a single file. While this article deals with only the img tag, this method can be applied to other tags as well. Here is an example of data URI usage:
img
<img src=">
More information on data URIs is available here:
Most editors do not use the data URI syntax. However, starting with SeaMonkey 2.1 Composer (Mozilla HTML Editor), images which are dragged and dropped are imported using this syntax. This is quite a bad change in my opinion, especially since it is not obvious and because it is a change in behavior from 2.0. In my case, I made a large HTML file with over 50 images before I discovered it was not linking them, but instead embedding them.
Amazingly, there are quite a few online utilities to convert images to the data URI format, but none that I could find that could do the reverse. Because I did not want to hand-edit my document, I wrote a quick utility to extract the images to disk and change the HTML to use external images. This allows the document to be loaded by any standard browser including Internet Explorer 8.
The source code is quite targeted to my specific need. It has a lot of limitations. I have published it however so that it is available as a foundation for you to expand should you have the same need.
ImageExtract is a console application and accepts one parameter. The parameter is the HTML file for input. The images will be output in the same directory, and the new HTML file will have a -new suffix. So if the input is index.html, the output HTML will be index-new.html.
ImageExtract
I have made the project available for download, but it is quite simple. It is a C# .NET Console application. For easy viewing, here is the class:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace ImageExtract {
class Program {
// NOTE - This program is rough and dirty - I designed
// it to accomplish and urgent task. I have not built in
// normal error handling etc.
//
// It also has not been optimized at all
// and certainly is not very efficient.
//
// It also assumes all images are png files.
static void Main(string[] aArgs) {
string xSrcPathname = aArgs[0];
string xPath = Path.GetDirectoryName(xSrcPathname);
string xDestPathname = Path.Combine(xPath,
Path.GetFileNameWithoutExtension(xSrcPathname) + "-New.html");
int xImgIdx = 0;
Console.WriteLine("Processing " + Path.GetFileName(xSrcPathname));
string xSrc = File.ReadAllText(xSrcPathname);
var xDest = new StringBuilder();
string xStart = @";
string xB64;
int x = 0;
int y = 0;
int z = 0;
do {
x = xSrc.IndexOf(xStart, z);
if (x == -1) {
break;
}
// Write out preceding HTML
xDest.Append(xSrc.Substring(z, x - z));
// Get the Base64 string
y = xSrc.IndexOf('"', x + 1);
xB64 = xSrc.Substring(x + xStart.Length, y - x - xStart.Length);
// Convert the Base64 string to binary data
byte[] xImgData = System.Convert.FromBase64String(xB64);
string xImgName;
// Get Image name and replace it in the HTML
// We don't want to overwrite images that might already exist on disk,
// so cycle till we find a non used name
do {
xImgIdx++;
xImgName = "Image" + xImgIdx.ToString("0000") + ".png";
} while (File.Exists(Path.Combine(xPath, xImgName)));
Console.WriteLine("Extracting " + xImgName);
// Write image name into HTML
xDest.Append(xImgName);
// Write the binary data to disk
File.WriteAllBytes(Path.Combine(xPath, xImgName), xImgData);
z = y;
} while (true);
// Write out remaining HTML
xDest.Append(xSrc.Substring(z));
// Write out result
File.WriteAllText(xDestPathname, xDest.ToString());
Console.WriteLine("Output to " + Path.GetFileName(xDestPathname));
}
}
}
This article, along with any associated source code and files, is licensed under The BSD License
code-comment">//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
General News Suggestion Question Bug Answer Joke Praise 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/221284/Data-URI-Image-Extractor | CC-MAIN-2015-48 | refinedweb | 737 | 58.58 |
Ticket #1888 (closed defect: fixed)
top_level_dir (in config) don't resolve correctly in namespace packages
Description
I have a turbogears website that I would like to deploy within my conventional namespace. I have already, for example, myns.util. I also have the turbogears website with a package of myns.website.
I have altered the default paste template to create myns.website. I believe I have implemented the namespace correctly, as most everything works as expected, except... static content fails to render and an error is reported:
2008-07-08 20:24:27,438 cherrypy.msg INFO DEBUG: NOT FOUND file: C:/Program Files/Python?/lib/site-packages/myns.util-0.2dev_r572-py2.5.egg/myns/website/static\images/under_the_hood_blue.png
or if a development link was set for myns.util:
2008-07-08 19:52:07,075 cherrypy.msg INFO DEBUG: NOT FOUND file: c:/projects/myns.util/src/myns/website/static\images/under_the_hood_blue.png
Note that turbogears is using the deployment path for myns.util, not myns.website, so the incorrect value must be being set in top_level_dir and package_dir.
The error occurs if myns.util is either installed or linked using "setup develop". If I remove all projects that share the same namespace, static content renders properly in myns.website.
It's possible that under certain conditions, the myns.website would take precedence, but I'm not sure what these conditions would be.
Note that the issue occurs regardless of whether myns.website is registered with setuptools (i.e. via "setup develop"). Furthermore, note that if both namespace packages are registered, they are both properly accessible through import.
from myns.site import * from myns.util import *
This issue is related to, although distinct from, #12.
Attachments
Change History
comment:2 Changed 11 years ago by guest
- Summary changed from top_level_dir and package_dir (in config) don't resolve correctly in namespace packages to top_level_dir (in config) don't resolve correctly in namespace packages
So the issue is that top_level_dir is being calculated from the location for the "myns" package, which actually appears in a number of locations (physically). Therefore, top_level_dir should probably be calculated using a different technique.
comment:3 Changed 11 years ago by Chris Arndt
Can you please provide an example project (together with the necessary namespace packages) that demonstrates this problem? I don't quite understand the problem. If I can look at the code, it might be easier to understand.
Changed 11 years ago by guest
- attachment myns.site.zip
added
A namespace-based tg project
comment:5 Changed 11 years ago by guest
I have attached a sample TG 1.0.5 project that was quickstarted using:
tg-admin quickstart -e -t tggenshi
It was originally called myns_site (myns stands for "my namespace" and site is the web site in this namespace).
I then converted the quickstarted project into a namespace-aware project. The different between the original is included in a diff file in the zip archive.
Note that when one starts the application as written, the error is exemplified. If one alters app.cfg to use the %(package_dir)s string, then the static content loads correctly. This indicates to me that %(package_dir)s may be the correct variable to use in all cases.
To further complicate matters, one may also install another package in the myns namespace. Simple examples are available from. Installing myns.projA with the attached TG site will cause TG to search in the myns.projA for static content, and not in myns.site. In particular, top_level_dir will refer to something like "c:\Python\lib\site-packages\myns.projA\myns".
I will be gone for the weekend but back on Tuesday. Let me know if I can provide any clarification for this issue.
comment:6 Changed 10 years ago by jorge.vargas
- Milestone changed from __unclassified__ to 1.x
This is 1.x specific as TG2.x works well with namespaced packages
Correction: top_level_dir appears to be the only variable that is affected by this issue. package_dir does resolve correctly.
So, a workaround for the static content issue is to change:
static_filter.dir = "%(top_level_dir)s/site/static"
to
static_filter.dir = "%(package_dir)s/static"
(and similarly for /favicon.ico).
It seems to me this is the better variable choice (for app.cfg in the template) anyway. | http://trac.turbogears.org/ticket/1888 | CC-MAIN-2019-22 | refinedweb | 716 | 60.21 |
This is the mail archive of the libstdc++@sources.redhat.com mailing list for the libstdc++ project.
Phil Edwards wrote: >. I'll have to take a look at Socket++. I didn't find it when I looked before, but I probably wasn't looking hard enough. Bummer, because I'd rather not write such stuff myself. ;^) > > #ifdef WIN32 > > #error "close() probably isn't right for a socket!" > > #endif > > Supporting that platform, though, is going to be a pain... Yup. If sockets were handles, then it would be equivalent to *nix, really. Would've thought they fixed that when they went from Win16 to Win32, but I guess not. > > You guys still support this non-standard filebuf constructor, right? > > Sorry, exactly which one there is non-standard? (Without all the private > members, we couldn't tell what's being called.) The file I showed you, "socketostream.h" was the complete file. Here it is again, for clarity: 1 template<typename _CharT, 2 typename _Traits = char_traits<_CharT> > 3 class basic_socketostream 4 : public basic_ostream<_CharT, _Traits> 5 { 6 public: 7 basic_socketostream(int iSocket) 8 : basic_ostream<_CharT, _Traits>(0), 9 m_iSocket(iSocket), 10 m_fb(iSocket, "socket", ios::out) 11 { 12 this->init(&m_fb); 13 } 14 15 virtual ~basic_socketostream() 16 { 17 shutdown(m_iSocket, 2); 18 19 #ifdef WIN32 20 #error "close() probably isn't right for a socket!" 21 #endif 22 } 23 24 private: 25 int m_iSocket; 26 filebuf m_fb; 27 }; 28 29 typedef basic_socketostream<char> socketostream; If you look at line 26, basic_socketostream "has a" plain, unadulturated filebuf object. Looking at line 10, you see that I use the non-standard constructor for the filebuf: // Non-standard ctor: basic_filebuf(int __fd, const char* __name = "unknown", ios_base::openmode __mode = ios_base::in | ios_base::out); This comes from line 80 of bits/std_fstream.h in the 2.90.3 distribution. Will this non-standard constructor remain in the shipping version? (Please say yes...;^) I use the above class in my program to send output to a socket which I've previously done accept(). (Note: if you want to use the above in a program, make sure to include <fstream> and <ostream> before including socketostream.h) > Dunno about the memory leak problem. When I run the following test program on my system, using gcc 2.95.2, and the last separate release of libstdc++-v3, the 2.90.3 release, it will leak memory until it crashes. While at first it may appear that I'm abusing the fstream class, my conjecture is that any failure at close() in the basic libstdc++ object will leak memory and this was the best way I could figure to make it happen. This is on my Linux system, btw. Would you happen to have a more recent release of the compiler/libstdc++ on which to try? I'd do it myself, but I'm a bit constrained here w.r.t. disk space. Is there a bug tracking system somewhere where I can report this? #include <ostream> #include <fstream> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <assert.h> #include <unistd.h> template<typename _CharT, typename _Traits = char_traits<_CharT> > class basic_fdostream : public basic_ostream<_CharT, _Traits> { public: basic_fdostream(int iFD) : basic_ostream<_CharT, _Traits>(0), m_iFD(iFD), m_fb(iFD, "some fd", ios::out) { this->init(&m_fb); } virtual ~basic_fdostream() { // Force close() to fail when filebuf's destructor runs. // If you comment out this line, the program works as expected. close(m_iFD); } private: int m_iFD; filebuf m_fb; }; int main(int argc, char*argv[]) { for (int i=0; i<50000; ++i) { int fd = open("wacko.txt", O_WRONLY | O_CREAT | O_TRUNC, 0700); assert(fd != -1); basic_fdostream<char> duh(fd); duh << "Quack" << flush; } return 0; } -- George T. Talbot <george at moberg dot com> | http://gcc.gnu.org/ml/libstdc++/2000-09/msg00075.html | crawl-002 | refinedweb | 618 | 67.25 |
Dynamic connection specifies that the force fields, emitters, or collisions of an object affect another dynamic object. The dynamic object that is connected to a field, emitter, or collision object is influenced by those fields, emitters and collision objects. Connections are made to individual fields, emitters, collisions. So, if an object owns several fields, if the user wants some of the fields to affect an object, s/he can specify each field with a -fflag; but if the user wants to connect all the fields owned by an object, s/he can specify the object name with the -fflag. The same is true for emitters and collisions. Different connection types (i.e., for fields vs. emitters) between the same pair of objects are logically independent. In other words, an object can be influenced by another object’s fields without being influenced by its emitters or collisions. Each connected object must be a dynamic object. The object connected to can be any object that owns fields, emitters, etc.; it need not be dynamic. Objects that can own influences are particles, geometry objects (nurbs and polys) and lattices. You can specify either the shape name or the transform name of the object to be influenced.
Derived from mel command maya.cmds.connectDynamic
Example:
import pymel.core as pm pm.connectDynamic( 'Book', c='Floor' ) # Connects the dynamic object "Book" to the collision model of the # "Floor". This means that the book will collide with and bounce off of # the floor. pm.connectDynamic( 'Moon', 'Spaceship', f='Moon' ) # Connects dynamic object "Spaceship" to the all fields and emitters # owned by "Moon". pm.connectDynamic( 'Spaceship', f='newtonField1' ) # Connects dynamic object "Spaceship" to "newtonField1" owned by "Moon". pm.connectDynamic( 'Moon', f='newtonField1' ) # If the selection list consists of "Spaceship", connects dynamic object # "Spaceship" to "newtonField1" and all emitters owned by "Moon". pm.connectDynamic( 'Spaceship', d=True, f='Moon' ) # Deletes the field connection between all the fields owned by "Moon" and # "Spaceship". Note that the command establishing the connection need not # be in the undo queue. pm.connectDynamic( 'Spaceship', d=True, f='newtonField1' ) # Deletes the field connection between "newtonField1" owned by "Moon" and # "Spaceship". | http://www.luma-pictures.com/tools/pymel/docs/1.0/generated/functions/pymel.core.effects/pymel.core.effects.connectDynamic.html#pymel.core.effects.connectDynamic | crawl-003 | refinedweb | 356 | 57.87 |
Software that is used evolves. How fast does software evolve, e.g., much new functionality is added and how much existing functionality is updated?
A new software release is often accompanied by a changelog which lists new, changed and deleted functionality. When software is developed using a continuous release process, the changelog can be very fine-grained.
The changelog for the Beeminder app contains 3,829 entries, almost one per day since February 2011 (around 180 entries are not present in the log I downloaded, whose last entry is numbered 4012).
Is it possible to use the information contained in the Beeminder changelog to estimate the rate of growth of functionality of Beeminder over time?
My thinking is driven by patterns in a plot of the Renzo Pomodoro dataset. Renzo assigned a tag-name (sometimes two) to each task, which classified the work involved, e.g.,
@planning. The following plot shows the date of use of each tag-name, over time (ordered vertically by first use). The first and third black lines are fitted regression models of the form , where: is a constant and is the number of days since the start of the interval fitted; the second (middle) black line is a fitted straight line.
How might a changelog line describing a day’s change be distilled to a much shorter description (effectively a tag-name), with very similar changes mapping to the same description?
Named-entity recognition seemed like a good place to start my search, and my natural language text processing tool of choice is still spaCy (which continues to get better and better).
spaCy is Python based and the processing pipeline could have all been written in Python. However, I’m much more fluent in awk for data processing, and R for plotting, so Python was just used for the language processing.
The following shows some Beeminder changelog lines after stripping out urls and formatting characters:
Cheapo bug fix for erroneous quoting of number of safety buffer days for weight loss graphs. Bugfix: Response emails were accidentally off the past couple days; fixed now. Thanks to user bmndr.com/laur for alerting us! More useful subject lines in the response emails, like "wrong lane!" or whatnot. Clearer/conciser stats at bottom of graph pages. (Will take effect when you enter your next datapoint.) Progress, rate, lane, delta. Better handling of significant digits when displaying numbers. Cf stackoverflow.com/q/5208663
The code to extract and print the named-entities in each changelog line could not be simpler.
import spacy import sys nlp = spacy.load("en_core_web_sm") # load trained English pipelines count=0 for line in sys.stdin: count += 1 print(f'> {count}: {line}') # doc=nlp(line) # do the heavy lifting # for ent in doc.ents: # iterate over detected named-entities print(ent.lemma_, ent.label_)
To maximize the similarity between named-entities appearing on different lines the lemmas are printed, rather than original text (i.e., words appear in their base form).
The
label_ specifies the kind of named-entity, e.g., person, organization, location, etc.
This code produced 2,225 unique named-entities (5,302 in total) from the Beeminder changelog (around 0.6 per day), and failed to return a named-entity for 33% of lines. I was somewhat optimistically hoping for a few hundred unique named-entities.
There are several problems with this simple implementation:
- each line is considered in isolation,
- the change log sometimes contains different names for the same entity, e.g., a person’s full name, Christian name, or twitter name,
- what appear to be uninteresting named-entities, e.g., numbers and dates,
- the language does not know much about software, having been training on a corpus of general English.
Handling multiple names for the same entity would a lot of work (i.e., I did nothing), ‘uninteresting’ named-entities can be handled by post-processing the output.
A language processing pipeline that is not software-concept aware is of limited value. spaCy supports adding new training models, all I need is a named-entity model trained on manually annotated software engineering text.
The only decent NER training data I could find (trained on StackOverflow) was for BERT (another language processing tool), and the data format is very different. Existing add-on spaCy models included fashion, food and drugs, but no software engineering.
Time to roll up my sleeves and create a software engineering model. Luckily, I found a webpage that provided a good user interface to tagging sentences and generated the json file used for training. I was patient enough to tag 200 lines with what I considered to be software specific named-entities. … and now I have broken the NER model I built…
The following plot shows the growth in the total number of named-entities appearing in the changelog, and the number of unique named-entities (with the 1,996 numbers and dates removed; code+data);
The regression fits (red lines) are quadratics, slightly curving up (total) and down (unique); the linear growth components are: 0.6 per release for total, and 0.46 for unique.
Including software named-entities is likely to increase the total by at least 15%, but would have little impact on the number of unique entries.
This extraction pipeline processes one release line at a time. Building a set of Beeminder tag-names requires analysing the changelog as a whole, which would take a lot longer than the day spent on this analysis.
The Beeminder developers have consistently added new named-entities to the changelog over more than eleven years, but does this mean that more features have been consistently added to the software (or are they just inventing different names for similar functionality)?
It is not possible to answer this question without access to the code, or experience of using the product over these eleven years.
However, staying in business for eleven years is a good indicator that the developers are doing something right. | https://www.artificialworlds.net/planetcode/category/beeminder/ | CC-MAIN-2022-21 | refinedweb | 992 | 54.83 |
A Guide to Parsing: Algorithms and Technology (Part 3)
A Guide to Parsing: Algorithms and Technology (Part 3)
Let's continue talking about grammars in algorithms in the context of the big picture, starting with parsers, parsing trees, abstract syntax trees, and more.
Join the DZone community and get the full member experience.Join For Free
Be sure to check out Part 2 first! If you're encountering this series for the first time, you can find the rest of the posts at the bottom of this article.
The Big Picture
Grammars
Parser
In the context of parsing, parser can refer both to the software that performs the whole process and also just to the proper parser that analyzes the tokens produced by the lexer. This is simply a consequence of the fact that the parser takes care of the most important and difficult part of the whole process of parsing. By most important, we mean what the user cares about the most and will actually see. In fact, as we said, the lexer works as an helper to facilitate the work of the parser.
In any sense, the parser's output is an organized structure of the code — usually, a tree. The tree can be a parse tree or an abstract syntax tree. They are both trees, but they differ in how closely they represent the actual code written and the intermediate elements defined by the parser. The line between the two can be blurry at times. We are going to see their differences a bit better in a later paragraph.
The form of a tree is chosen because it is an easy and natural way to work with the code at different levels of detail. For example, a class in C# has one body, this body is made of one statement, the block statement, that is a list of statements enclosed in a pair of curly brackets, and so on…
Syntactic vs. Semantic Correctness
A parser is a fundamental part of a compiler, or an interpreter, but of course can be part of a variety of other software. For example, in this article, we parsed C# files to produce diagrams.
The parser can only check the syntactic correctness of piece of code, but the compiler can use its output in the process of checking the semantic validity of the same piece of code.
Let's see an example of code that is syntactically correct, but semantically incorrect.
int x = 10 int sum = x + y
The problem is that one variable (
y) is never defined and thus, if executed, the program will fail. However, the parser has no way of knowing this because it does not keep track of variables — it just looks at the structure of the code.
A compiler instead would typically traverse the parse tree a first time and keep a list of all the variables that are defined. Then, it traverses the parse tree a second time and checks whether the variables that are used are all properly defined. In this example, they are not, and it will throw an error. That is one way the parse tree can also be used to check the semantics by the compiler.
Scannerless Parser
A scannerless parser, or more rarely, a lexerless parser, is a parser that performs the tokenization (i.e. the transformation of sequence of characters in tokens) and proper parsing in a single step. In theory, having a separate lexer and parser is preferable because it allows a clearer separation of objectives and the creation of a more modular parser.
A scannerless parser is a better design for a language where a clear distinction between the lexer and parser is difficult or unnecessary. An example is a parser for a markup language, where special markers are inserted in a sea of text. It can also facilitates the handling of languages where traditional lexing is difficult, like C. That is because a scannerless parser can more easily deal with complex tokenizations.
Issues With Parsing Real Programming Languages
In theory, contemporary parsing is designed to handle real programming languages. In practice, there are challenges with some real programming languages. It might be harder to parse them using normal parsing generator tools.
Context-Sensitive Parts
Parsing tools are traditionally designed to handle context-free languages, but sometimes, the languages are context-sensitive. This might be done to simplify the life of programmers or simply because of bad design. I remember reading about a programmer that thought it could produce a parser for C in a week, but then it found so many corner cases that a year later he was still working on it…
A typical example of context-sensitive elements are soft keywords, i.e. strings that can be considered keywords in certain places but otherwise can be used as identifiers.
Whitespace
Whitespace plays a significant role in some languages. The most well-known example is Python, where the indentation of a statement indicates if it is part of a certain block of code.
In most places, whitespace is irrelevant — even in Python, spaces between words or keywords do not matter. The real problem is the indentation that is used to identify blocks of code. The simplest way to deal with it is to check the indentation at the start of the line and transform in the proper token, i.e. create a token when the indentation changes from the previous line.
In practice, a custom function in the lexer produces INDENT and DEDENT tokens when the indentation increases or decreases. These tokens play the role that, in C-like languages, is played by curly brackets — they indicate the start and end of code blocks.
This approach makes lexing context-sensitive instead of context-free. This complicates parsing and you normally, would not want to do it, but you are forced to do in this case.
Multiple Syntaxes
Another common issue is dealing with the fact that a language might actually include a few different syntaxes. In other words, the same source file may contain sections of code that follow a different syntax. In the context of parsing, the same source file contains different languages. The most famous example is probably the C or C++ preprocessor, which is actually a fairly complicated language on its own and can magically appear inside any random C code.
An easier case to deal with is annotations, which are present in many contemporary programming languages. Among other things, they can be used to process code before it arrives to the compiler. They can command the annotation processor to transform the code in some way; for instance, to execute a specific function before executing the annotated one. They are easier to manage because they can appear only in specific places.
Dangling Else
The dangling else is a common problem in parsing linked to the if-then-else statement. Since the else clause is optional, a sequence of if statements could be ambiguous — for example, this one:
if one then if two then two else ???
It is unclear if the
else belongs to the first
if or the second one.
To be fair, this is, for the most part, a problem of language design. Most solutions don't really complicate parsing that much; for example, requiring the use of an
endif or requiring the use of blocks to delimit the
if statement when it includes an else clause.
However, there are also languages that offer no solution; that is to say, they're designed ambiguously — for example, you guessed it, C. The conventional approach is to associate the else to the nearest if statement, which makes the parsing context-sensitive.
Parsing Tree and Abstract Syntax Tree
There are two terms that are related and sometimes they are used interchangeably: parse tree and abstract syntax tree (AST). Technically, the parse tree could also be called a concrete syntax tree (CST) because it should reflect more concretely the actual syntax of the input, at least compared to the AST.
Conceptually, they are very similar. They are both trees; there is a root that has nodes representing the whole source code. The roots have children nodes that contain subtrees representing smaller and smaller portions of code, until single tokens (terminals) appears in the tree.
The difference is in the level of abstraction. A parse tree might contains all the tokens that appeared in the program and possibly, a set of intermediate rules. The AST, instead, is a polished version of the parse tree, in which only the information relevant to understanding the code is maintained. We are going to see an example of an intermediate rule in the next section.
Some information might be absent both in the AST and the parse tree. For instance, comments and grouping symbols (i.e. parentheses) are usually not represented. Things like comments are superfluous for a program and grouping symbols are implicitly defined by the structure of the tree.
From Parse Tree to Abstract Syntax Tree
A parse tree is a representation of the code closer to the concrete syntax. It shows many details of the implementations of the parser. For instance, usually, each rule corresponds to a specific type of a node. A parse tree is usually transformed in an AST by the user, possibly with some help from the parser generator. A common help allows you to annotate some rule in the grammar in order to exclude the corresponding nodes from the generated tree. Another one is an option to collapse some kinds of nodes if they have only one child.
This makes sense because the parse tree is easier to produce for the parser since it is a direct representation of the parsing process. However, the AST is simpler and easier to process through the steps of the program. They typically include all the operations that you may want to perform on the tree: code validation, interpretation, compilation, etc.
Let's look at a simple example to show the difference between a parse tree and an AST. Let’s start with a look at an example grammar.
In this grammar, we can define a sum using both the symbol plus (
+) or the string
plus as operators. Imagine that you have to parse the following code. These could be the resulting parse tree and abstract syntax tree.
In the AST the indication of the specific operator is disappeared and all that remains is the operation to be performed. The specific operator is an example of an intermediate rule.
Graphical Representation of a Tree
The output of a parser is a tree, but the tree can also be represented in graphical ways. That is to allow an easier understanding to the developer. Some parsing generator tools can output a file in the DOT language, a language designed to describe graphs (a tree is a particular kind of graph). Then this file is fed to a program that can create a graphical representation starting from this textual description (i.e. Graphviz).
Let’s see a DOT text based on the previous sum example.
digraph sum { sum -> 10; sum -> 21; }
The appropriate tool can create the following graphical representation.
If you want to see a bit more of DOT, you can read this article, where we show how to create a Visual Studio Code plugin that can handle DOT files. }} | https://dzone.com/articles/a-guide-to-parsing-algorithms-and-technology-part-7 | CC-MAIN-2019-47 | refinedweb | 1,890 | 61.06 |
i need to write a program as follows:
Write a program that prompts the user to enter three positive integers representing the number of rows, the number of columns of a grid, and the number of mines hidden in the grid, the program then calls the following function:
void Minesweeper(int nRows, int nColumns, int nMines )
The function Minesweeper( ) prints a grid of nRows x nColumns of 0's and 1's. A 0 represents a square that has no mine and a 1 represents a square that has a mine. The parameter nMines represents the number of mines.
Hint: Store the 0's and 1's in a two dimensional array first then print that array.
i have started it, but i have no idea on where to to go about with this. i will paste my code down below, but i know it wont help much.
i just need someone to point me to the right direction on how to solve it. i know i need to store the values into an array, but i'm a little confused on how to do that with variables? and i assume that my task is to generate the user-defined number of mines into random parts of the array- i dont even know where i would go about trying to figuring that one out.
here's my code:
Code:#include <iostream> #include <iomanip> #include <fstream> #include <string> using namespace std; void minesweeper(int numbers_r, int numbers_c, int numbers_m); int main () { int numbers_r, numbers_c, numbers_m; //int mineArray[numbers_r][numbers_c]; cout<<"Enter the number of rows: "; cin>>numbers_r; cout<<"Enter the number of columns: "; cin>>numbers_c; cout<<"Enter the number of mines: "; cin>>numbers_m; minesweeper(numbers_r, numbers_c, numbers_m); return 0; } void minesweeper(int nRows, int nColumns, int nMines) { char mines_chr= '1'; char not_mines_chr= '0'; if (nMines>0) n_not_mines=(nRows*nColumns)-nMines; int mineArray[nRows][nColumns]; for (int i=0; i<nRows; i++) { for(int j=0; j<nColumns; j++) mineArray[i][j]= n_not_mines; cout<<setw(5)<<mineArray[i][j]; } } | https://cboard.cprogramming.com/cplusplus-programming/126431-2d-array-help.html | CC-MAIN-2017-26 | refinedweb | 337 | 58.05 |
After the success of the book Python Data Analysis, Packt's acquisition editor Prachi Bisht gauged the interest of the author, Ivan Idris, in publishing Python Data Analysis Cookbook. According to Ivan, Python Data Analysis is one of his best books. Python Data Analysis Cookbook is meant for a bit more experienced Pythonistas and is written in the cookbook format. In the year after the release of Python Data Analysis, Ivan has received a lot of feedback—mostly positive, as far as he is concerned.
Although Python Data Analysis covers a wide range of topics, Ivan still managed to leave out a lot of subjects. He realized that he needed a library as a toolbox. Named dautil for data analysis utilities, the API was distributed by him via PyPi so that it is installable via pip/easy_install. As you know, Python 2 will no longer be supported after 2020, so dautil is based on Python 3.
For the sake of reproducibility, Ivan also published a Docker repository named pydacbk (for Python Data Analysis Cookbook). The repository represents a virtual image with preinstalled software. For practical reasons, the image doesn't contain all the software, but it still contains a fair percentage. This article has the following sections:
- Data analysis, data science, big data – what is the big deal?
- A brief history of data analysis with Python
- A high-level overview of dautil
- IPython notebook utilities
- Downloading data
- Plotting utilities
- Demystifying Docker
- Future directions
(For more resources related to this topic, see here.)
Data analysis, data science, big data – what is the big deal?
You've probably seen Venn diagrams depicting data science as the intersection of mathematics/statistics, computer science, and domain expertise. Data analysis is timeless and was there before data science and computer science. You could perform data analysis with a pen and paper and, in more modern times, with a pocket calculator.
Data analysis has many aspects with goals such as making decisions or coming up with new hypotheses and questions. The hype, status, and financial rewards surrounding data science and big data remind me of the time when data warehousing and business intelligence were the buzzwords. The ultimate goal of business intelligence and data warehousing was to build dashboards for management. This involved a lot of politics and organizational aspects, but on the technical side, it was mostly about databases. Data science, on the other hand, is not database-centric, and leans heavily on machine learning. Machine learning techniques have become necessary because of the bigger volumes of data. Data growth is caused by the growth of the world's population and the rise of new technologies such as social media and mobile devices. Data growth is in fact probably the only trend that we can be sure will continue. The difference between constructing dashboards and applying machine learning is analogous to the way search engines evolved.
Search engines (if you can call them that) were initially nothing more than well-organized collections of links created manually. Eventually, the automated approach won. Since more data will be created in time (and not destroyed), we can expect an increase in automated data analysis.
A brief history of data analysis with Python
The history of the various Python software libraries is quite interesting. I am not a historian, so the following notes are written from my own perspective:
- 1989: Guido van Rossum implements the very first version of Python at the CWI in the Netherlands as a Christmas hobby project.
- 1995: Jim Hugunin creates Numeric, the predecessor to NumPy.
- 1999: Pearu Peterson writes f2py as a bridge between Fortran and Python.
- 2000: Python 2.0 is released.
- 2001: The SciPy library is released. Also, Numarray, a competing library of Numeric, is created. Fernando Perez releases IPython, which starts out as an afternoon hack. NLTK is released as a research project.
- 2002: John Hunter creates the matplotlib library.
- 2005: NumPy is released by Travis Oliphant. Initially, NumPy is Numeric extended with features inspired by Numarray.
- 2006: NumPy 1.0 is released. The first version of SQLAlchemy is released.
- 2007: The scikit-learn project is initiated as a Google Summer of Code project by David Cournapeau. Cython is forked from Pyrex. Cython is later intensively used in pandas and scikit-learn to improve performance.
- 2008: Wes McKinney starts working on pandas. Python 3.0 is released.
- 2011: The IPython 0.12 release introduces the IPython notebook. Packt releases NumPy 1.5 Beginner's Guide.
- 2012: Packt releases NumPy Cookbook.
- 2013: Packt releases NumPy Beginner's Guide - Second Edition.
- 2014: Fernando Perez announces Project Jupyter, which aims to make a language-agnostic notebook. Packt releases Learning NumPy Array and Python Data Analysis.
- 2015: Packt releases NumPy Beginner's Guide - Third Edition and NumPy Cookbook - Second Edition.
A high-level overview of dautil
The dautil API that Ivan made for this book is a humble toolbox, which he found useful. It is released under the MIT license. This license is very permissive, so you could in theory use the library in a production system. He doesn't recommend doing this currently (as of January, 2016), but he believes that the unit tests and documentation are of acceptable quality. The library has 3000+ lines of code and 180+ unit tests with a reasonable coverage. He has fixed as many issues reported by pep8 and flake8 as possible.
Some of the functions in dautil are on the short side and are of very low complexity. This is on purpose. If there is a second edition (knock on wood), dautil will probably be completely transformed. The API evolved as Ivan wrote the book under high time pressure, so some of the decisions he made may not be optimal in retrospect. However, he hopes that people find dautil useful and, ideally, contribute to it.
The dautil modules are summarized in the following table:
IPython notebook utilities
The IPython notebook has become a standard tool for data analysis. The dautil.nb has several interactive IPython widgets to help with Latex rendering, the setting of matplotlib properties, and plotting. Ivan has defined a Context class, which represents the configuration settings of the widgets. The settings are stored in a pretty-printed JSON file in the current working directory, which is named dautil.json. This could be extended, maybe even with a database backend. The following is an edited excerpt (so that it doesn't take up a lot of space) of an example dautil.json:
{ ... "calculating_moments": { "figure.figsize": [ 10.4, 7.7 ], "font.size": 11.2 }, "calculating_moments.latex": [ 1, 2, 3, 4, 5, 6, 7 ], "launching_futures": { "figure.figsize": [ 11.5, 8.5 ] }, "launching_futures.labels": [ [ {}, { "legend": "loc=best", "title": "Distribution of Means" } ], [ { "legend": "loc=best", "title": "Distribution of Standard Deviation" }, { "legend": "loc=best", "title": "Distribution of Skewness" } ] ], ... }
The Context object can be constructed with a string—Ivan recommends using the name of the notebook, but any unique identifier will do. The dautil.nb.LatexRenderer also uses the Context class. It is a utility class, which helps you number and render Latex equations in an IPython/Jupyter notebook, for instance, as follows:
import dautil as dl lr = dl.nb.LatexRenderer(chapter=12, context=context) lr.render(r'\delta\! = x - m') lr.render(r'm\' = m + \frac{\delta}{n}') lr.render(r'M_2\' = M_2 + \delta^2 \frac{ n-1}{n}') lr.render(r'M_3\' = M_3 + \delta^3 \frac{ (n - 1) (n - 2)}{n^2}/ - \frac{3\delta M_2}{n}') lr.render(r'M_4\' = M_4 + \frac{\delta^4 (n - 1) / (n^2 - 3n + 3)}{n^3} + \frac{6\delta^2 M_2}/ {n^2} - \frac{4\delta M_3}{n}') lr.render(r'g_1 = \frac{\sqrt{n} M_3}{M_2^{3/2}}') lr.render(r'g_2 = \frac{n M_4}{M_2^2}-3.')
The following is the result:
Another widget you may find useful is RcWidget, which sets matplotlib settings, as shown in the following screenshot:
Downloading data
Sometimes, we require sample data to test an algorithm or prototype a visualization. In the dautil.data module, you will find many utilities for data retrieval. Throughout this book, Ivan has used weather data from the KNMI for the weather station in De Bilt. A couple of the utilities in the module add a caching layer on top of existing pandas functions, such as the ones that download data from the World Bank and Yahoo! Finance (the caching depends on the joblib library and is currently not very configurable). You can also get audio, demographics, Facebook, and marketing data.
The data is stored under a special data directory, which depends on the operating system. On the machine used in the book, it is stored under ~/Library/Application Support/dautil. The following example code loads data from the SPAN Facebook dataset and computes the clique number:
import networkx as nx import dautil as dl fb_file = dl.data.SPANFB().load() G = nx.read_edgelist(fb_file, create_using=nx.Graph(), nodetype=int) print('Graph Clique Number', nx.graph_clique_number(G.subgraph(list(range(2048)))))
To understand what is going on in detail, you will need to read the book. In a nutshell, we load the data and use the NetworkX API to calculate a network metric.
Plotting utilities
Ivan visualizes data very often in the book. Plotting helps us get an idea about how the data is structured and helps you form hypotheses or research questions. Often, we want to chart multiple variables, but we want to easily see what is what. The standard solution in matplotlib is to cycle colors. However, Ivan prefers to cycle line widths and line styles as well. The following unit test demonstrates his solution to this issue:
def test_cycle_plotter_plot(self): m_ax = Mock() cp = plotting.CyclePlotter(m_ax) cp.plot([0], [0]) m_ax.plot.assert_called_with([0], [0], '-', lw=1) cp.plot([0], [1]) m_ax.plot.assert_called_with([0], [1], '--', lw=2) cp.plot([1], [0]) m_ax.plot.assert_called_with([1], [0], '-.', lw=1)
The dautil.plotting module currently also has a helper tool for subplots, histograms, regression plots, and dealing with color maps. The following example code (the code for the labels has been omitted) demonstrates a bar chart utility function and a utility function from dautil.data, which downloads stock price data:
import dautil as dl import numpy as np import matplotlib.pyplot as plt ratios = [] STOCKS = ['AAPL', 'INTC', 'MSFT', 'KO', 'DIS', 'MCD', 'NKE', 'IBM'] for symbol in STOCKS: ohlc = dl.data.OHLC() P = ohlc.get(symbol)['Adj Close'].values N = len(P) mu = (np.log(P[-1]) - np.log(P[0]))/N var_a = 0 var_b = 0 for k in range(1, N): var_a = (np.log(P[k]) - np.log(P[k - 1]) - mu) ** 2 var_a = var_a / N for k in range(1, N//2): var_b = (np.log(P[2 * k]) - np.log(P[2 * k - 2]) - 2 * mu) ** 2 var_b = var_b / N ratios.append(var_b/var_a - 1) _, ax = plt.subplots() dl.plotting.bar(ax, STOCKS, ratios) plt.show()
Refer to the following screenshot for the end result:
The code performs a random walk test and calculates the corresponding ratio for a list of stock prices. The data is retrieved whenever you run the code, so you may get different results. Some of you have a finance aversion, but rest assured that this book has very little finance-related content.
The following script demonstrates a linear regression utility and caching downloader for World Bank data (the code for the watermark and plot labels has been omitted):
import dautil as dl import matplotlib.pyplot as plt import numpy as np wb = dl.data.Worldbank() countries = wb.get_countries()[['name', 'iso2c']] inf_mort = wb.get_name('inf_mort') gdp_pcap = wb.get_name('gdp_pcap') df = wb.download(country=countries['iso2c'], indicator=[inf_mort, gdp_pcap], start=2010, end=2010).dropna() loglog = df.applymap(np.log10) x = loglog[gdp_pcap] y = loglog[inf_mort] dl.options.mimic_seaborn() fig, [ax, ax2] = plt.subplots(2, 1) ax.set_ylim([0, 200]) ax.scatter(df[gdp_pcap], df[inf_mort]) ax2.scatter(x, y) dl.plotting.plot_polyfit(ax2, x, y) plt.show()
The following image should be displayed by the code:
The program downloads World Bank data for 2010 and plots the infant mortality rate against the GDP per capita. Also shown is a linear fit of the log-transformed data.
Demystifying Docker
Docker uses Linux kernel features to provide an extra virtualization layer. It was created in 2013 by Solomon Hykes. Boot2Docker allows us to install Docker on Windows and Mac OS X as well. Boot2Docker uses a VirtualBox VM that contains a Linux environment with Docker. Ivan's Docker image, which is mentioned in the introduction, is based on the continuumio/miniconda3 Docker image. The Docker installation docs are at.
Once you install Boot2Docker, you need to initialize it. This is only necessary once, and Linux users don't need this step:
$ boot2docker init
The next step for Mac OS X and Windows users is to start the VM:
$ boot2docker start
Check the Docker environment by starting a sample container:
$ docker run hello-world
Docker images are organized in a repository, which resembles GitHub. A producer pushes images and a consumer pulls images. You can pull Ivan's repository with the following command. The size is currently 387 MB.
$ docker pull ivanidris/pydacbk
Future directions
The dautil API consists of items Ivan thinks will be useful outside of the context of this book. Certain functions and classes that he felt were only suitable for a particular chapter are placed in separate per-chapter modules, such as ch12util.py. In retrospect, parts of those modules may need to be included in dautil as well.
In no particular order, Ivan has the following ideas for future dautil development:
- He is playing with the idea of creating a parallel library with "Cythonized" code, but this depends on how dautil is received
- Adding more data loaders as required
- There is a whole range of streaming (or online) algorithms that he thinks should be included in dautil as well
- The GUI of the notebook widgets should be improved and extended
- The API should have more configuration options and be easier to configure
Summary
In this article, Ivan roughly sketched what data analysis, data science, and big data are about. This was followed by a brief of history of data analysis with Python. Then, he started explaining dautil—the API he made to help him with this book. He gave a high-level overview and some examples of the IPython notebook utilities, features to download data, and plotting utilities.
He used Docker for testing and giving readers a reproducible data analysis environment, so he spent some time on that topic too. Finally, he mentioned the possible future directions that could be taken for the library in order to guide anyone who wants to contribute.
Resources for Article:
Further resources on this subject:
- Recommending Movies at Scale (Python) [article]
- Python Data Science Up and Running [article]
- Making Your Data Everything It Can Be [article] | https://www.packtpub.com/books/content/python-data-analysis-utilities | CC-MAIN-2017-17 | refinedweb | 2,470 | 57.98 |
Have been experienced some delays/slowdowns with the arduino ide using Windows?
Specially when you left your bluetooth serial ports enabled?, when starting or clicking on "TOOLS" menu like you can see here?:
After a while playing with the Java code of the IDE, I noticed () that the problem is a bit more hard to solve than fixing the Arduino IDE, even when I solved another small problem road to my final solution ::):
You can download the "fixed" Arduino 0014 file here (replace this in the Arduino/lib/ path):
Well, the problem resides in the rxtx serial library, library that Arduino IDE uses to enumerate the com ports and for communication with the board. This library is open source and multi platform:
After hours of trying to find the problem, I isolated the problem: the initialization routines are guilty, because even if I don't call the enumeration (clicking on the TOOLS menu) from the Arduino IDE, the delays appear with any sketch upload or turning on the serial monitor.
The problem begin from this code, in the SerialImp.c file:
#ifndef WIN32 pid = getpid(); #else char full_windows_name[80]; #endif /* WIN32 */ ENTER( "RXTXPort:testRead" ); #ifdef TRENT_IS_HERE_DEBUGGING_ENUMERATION /* vmware lies about which ports are there causing irq conflicts */ /* this is for testing only */ if( !strcmp( name, "COM1" ) || !strcmp( name, "COM2") ) { printf("%s is good\n",name); sprintf( message, "testRead: %s is good!\n", name ); report( message ); (*env)->ReleaseStringUTFChars( env, tty_name, name ); return( JNI_TRUE ); } (*env)->ReleaseStringUTFChars( env, tty_name, name ); return( JNI_FALSE ); #endif /* TRENT_IS_HERE_DEBUGGING_ENUMERATION */ #ifdef WIN32 strcpy( full_windows_name, DEVICEDIR ); strcat( full_windows_name, name ); ret = serial_test((char *) full_windows_name ); ret = serial_test((char *) name ); (*env)->ReleaseStringUTFChars( env, tty_name, name ); return(ret); #endif /* WIN32 *
For each com port, we call "serial_test((char *) full_windows_name );" to check if we can open that port. In Windows each com port, device, etc is a file too (like in Unix, but Windows does not allow us to see this directly using a "class-device" approach, not a file-based one), ports as any other device are part of the "//./" namespace, for example "//./COM12" is the path for my LOCALHOST "." COM12 port. If the system can open this port/file, I will treat this port as valid, in the termios.c file:
unsigned long *hcomm; hcomm = CreateFile( filename, GENERIC_READ |GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0 ); if ( hcomm == INVALID_HANDLE_VALUE ) { if (GetLastError() == ERROR_ACCESS_DENIED) { ret = 1; } else { ret = 0; } } else { ret = 1; } CloseHandle( hcomm );
Opening a file... yeah right but there is a small issue with this method. We want to check a lot of port quicky (each time that the Arduino/Tool menu is shown, uploaded a sketch, etc) so we need a non blocking operation, something like Synchronous vs Asynchronous (), but for this task CreateFile is very buggy. It delays if the "file" does not respond until a timeout, so if my bluetooth dongle is connected and there are some virtual bt com ports, the process is very laggy and time-consuming.
Thanks to I discovered another way to check ports. It is only for Windows NT, so we need to keep the compatibility backwards. Even when the new function is a lot faster, its very dirty (not as the old solution) because to keep the compatibility I just overwrite the "serial_test" function, and this function only works for one port at once. But in fact, using the QueryDosDevice API (for NT) I have the full list of devices at once, not one by one (so in the future the next release of this rxtx library will be a lot quicker).
Here is the brand-new ultra fast serial_test ;):
/*---------------------------------------------------------- serial_test accept: filename to test perform: return: 1 on success 0 on failure exceptions: win32api: CreateFile CloseHandle comments: if the file opens it should be ok. ----------------------------------------------------------*/ int serial_test( char * filename ) { int ret = 0; // Getting the Windows Version OSVERSIONINFO osvi; osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); BOOL bGetVer = GetVersionEx(&osvi); // Using the QueryDosDevice API (on NT) if (bGetVer && (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)) { // This solution is based on TCHAR szDevices[65535]; DWORD dwChars = QueryDosDevice(NULL, szDevices, 65535); if (dwChars) { int i=0; for (;;) { //Get the current device name char* pszCurrentDevice = &szDevices[i]; if (strlen(pszCurrentDevice) > 3 && strcmp(pszCurrentDevice,filename)==0) { ret = 1; break; } // Go to next NULL character while(szDevices[i] != '\0') i++; // Bump pointer to the next string i++; // The list is double-NULL terminated, so if the character is // now NULL, we're at the end if (szDevices[i] == '\0') break; } } } else { // Buggy way to test if we can open the comport (on Win9x) unsigned long *hcomm; hcomm = CreateFile( filename, GENERIC_READ |GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0 ); if ( hcomm == INVALID_HANDLE_VALUE ) { if (GetLastError() == ERROR_ACCESS_DENIED) { ret = 1; } else { ret = 0; } } else { ret = 1; } CloseHandle( hcomm ); } return(ret); }
And the new and fixed compiled library is here (for all those have problems with delays and slowdowns in their arduino IDE, startup, uploading or displaying the TOOLS menu, any build, just replace the file "rxtxSerial.dll")
Hope it helps for your problem/ or as experience to solve other problems. The key is a whole night, Pepsi and reading the README files! | https://forum.arduino.cc/t/road-to-solve-the-delay-on-the-arduino-ide/47118 | CC-MAIN-2021-21 | refinedweb | 837 | 52.12 |
2,260.
eddieace left a reply on VerifyCsrfToken Exclude Not Working
Now I tried this and it did not work
protected $except = [ '*', ];
eddieace started a new conversation VerifyCsrfToken Exclude Not Working
I'm having an issue with excluding a route from verifying CSRF token.
I'm trying to exclude all requests on an endpoint which I call mydomain.com/example so I do like this in the VerifyCsrfToken.php file.
class VerifyCsrfToken extends Middleware { /** * Indicates whether the XSRF-TOKEN cookie should be set on the response. * * @var bool */ protected $addHttpCookie = true; /** * The URIs that should be excluded from CSRF verification. * * @var array */ protected $except = [ 'example/*', ]; }
But it does not solve the issue. If I do this in the app/Http/Kernel.php file everything works as it should.
Anyone know why I can't exclude specific routes?, \Barryvdh\Cors\HandleCors::class, ], 'api' => [ 'throttle:60,1', 'bindings', ], ]; ´´´
eddieace left a reply on Can $collection->increment('field') Fail?
Actually, I don't know if it misses it or not. I just look at all the other statistics I have, which display the same results but redirects lately dropped a lot.
@Snapey I'm redirecting to a view because that view displays a message before it redirects to its final destination. But it needs to hit this method before being redirected.
eddieace started a new conversation Can $collection->increment('field') Fail?
I have a redirect function that looks like this. For some reason, it looks like it's sometimes missing to increment the item. I'm wondering if it sometimes can be so that it misses this because some caching or something?
public function redirect($key) { $item = $this->item->findOrFail($key); $item->increment('redirects'); $encode = urlencode($item->_url); return view('item.redirect', ['url' => ($encode)]); }
eddieace started a new conversation Blacklist Emails
I have an application where people fill in a form including their email. Lately, some Chinese bot has been able to break through the CSRF protection and is abusing this service. I need to come up with a soluting to blacklist emails, or agents. What solution would you guys suggest?
eddieace started a new conversation Computed Property With Multiple Checkbox Filters
I am trying to make a solution for filtering results using checkboxes as simple as possible and as readable as possible.
I have a computed property called filteredPositions that looks like this. But it won't work with multiple filters on one array. Does anyone have a good solution for this problem?
Here is the computed property.
filteredPositions() { if (this.checkedFilters.includes("SE")) { return this.positions.filter(position => position.country_id == 1); } if (this.checkedFilters.includes("US")) { return this.positions.filter(position => position.country_id == 2); } }
Testdata
data() { return { positions: [], filters: [ { name: 'SE', }, { name: 'US', } ], checkedFilters: ['SE', 'US'], } }, ´´´
eddieace started a new conversation "laravel/cashier":"~7.0" Not Compatible With "stripe/stripe-php": "^6.1"
I get an error when I'm trying to run
composer require "laravel/cashier":"~7.0"
The error
Problem 1 - laravel/cashier v7.0.9 requires stripe/stripe-php ~4.0 -> satisfiable by stripe/stripe-php[v4.0.0, v4.0.1, v4.1.0, v4.1.1, v4.10.0, v4.11.0, v4.12.0, v4.13.0, v4.2.0, v4.3.0, v4.4.0, v4.4.1, v4.4.2, v4.5.0, v4.5.1, v4.6.0, v4.7.0, v4.8.0, v4.8.1, v4.9.0, v4.9.1] but these conflict with your requirements or minimum-stability.
Maybe it should be updated so it can use the latest version of stripe-php sdk?
Anyone solved it or have a fix for it?
eddieace left a reply on Failed To Mount Component: Template Or Render Function Not Defined
I solved this by adding .default when declaring my components.
Vue.component('example-component', require('./components/ExampleComponent.vue').default);
eddieace started a new conversation Failed To Mount Component: Template Or Render Function Not Defined
All of a sudden I got this error. I have tried to delete node modules and package-lock.json and reinstalled everything using npm install.
Any clues?
[Vue warn]: Failed to mount component: template or render function not defined. found in
eddieace left a reply on Vue.js File Upload
Here is my solution.
imgUpload(e) { if (!e.target.files.length) return; var data = new FormData(); data.append('image', e.target.files[0]); axios.post('/image', data) .then(response => { this.ad.image = response.data.path }) .catch(error => { console.log(error) }); },
<input type="file" @
eddieace started a new conversation Refactoring Objects Using Laravel Collections Fails
What I try to do is that I need to return an array with key-value pairs from an array of objects.
From an api I get objects that looks something like this.
array:8 [▼ 0 => TargetingSearch {#229 ▼ #data: array:6 [▼ "id" => "6005609368513" "name" => "Software" "audience_size" => 565991450 "path" => array:4 [▶] "description" => "" "topic" => "Technology" ] #_type_checker: TypeChecker {#228 ▶} }
The simple way to do it is to loop through the objects and push the values into an array.
$codes = []; foreach($objects as $object) { $codes[] = [ 'id' => $object->id, 'name' => $object->name, ]; }
Which will return this that is exactly what I need.
['id' => 321, 'name' => "item1"], ['id' => 321, 'name' => "item1"], ['id' => 321, 'name' => "item1"],
I think that this is a little hard to manage and what I try to do is something a little more readable.
For example, by using the Laravel collection classes I could do something like this.
$codes = collect($objects)->pluck('id', 'name')->toArray();
The problem here is that this does not return the keys.
["item1" => "123"], ["item2" => "321"], ["item3" => "213"],
If I use
$codes = collect($objects)->only('id', 'name')->toArray();
It returns an empty array because the object itself is messing it all up.
anyone knows how to solve this?
eddieace started a new conversation Valet And Laravel 5.5 Access Denied For User 'root'@'localhost'
Hello. I just started a new project and I use Valet for all my new projects. I also use a mysql DB that is installed on my local machine. It works on all my old projects using Laravel 5.4, 5.3 and 5.2. For some reason, I get this error.
SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO) (SQL: select * from `users` where `email` = [email protected] limit 1)
My .env file looks like this.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=new_project DB_USERNAME=root DB_PASSWORD=
And as I said before, this works on all my old projects.
If I run tinker and for example run a simple call to the database, the connection works. So this error is only in the browser.
$users = App\User::all(); => Illuminate\Database\Eloquent\Collection {#752 all: [], } >>>
Any clues?
eddieace started a new conversation Eloquent Using Multiple WhereNotIn
I'm trying to make a query where I use multiple whereNotIn arrays. For some reason, they block each other and ignores the other query parameters.
Any clues on how to solve this?
$products = Products::orderBy('id','DESC') ->where('status', '=', 4) ->whereNotIn('category', $excluded) ->whereNotIn('location', ['New York', 'Boston', 'Washington, DC', 'Charlotte']) ->take(400) ->get();
eddieace started a new conversation Running A Laravel Application Worldwide
Hey!
I'm in that stage where I need to scale my Laravel application worldwide. This means that I need to reduce latency on my site in the US and Asia. There are several ways to do this. What I think is that I should use a CDN of some kind. There are also services like Amazon lambda, but that does not run with PHP code. Another option would be to run a VPS in the US, one in Asia and one in Europe, and deploy it to three VPS at the same time.
what do you think is the best strategy for this?
eddieace started a new conversation Curl Not Working In Homestead
For some reason, I can't use CURL to send post requests in homestead. It just returns null and here is my code.
Additional, headers are not being set, even if it's application/json it returns HTML/charset.
any clues?
$ch = curl_init(env('app_url') . 'applications/' . $position->ats_reference . '/import'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([ 'token' => $user->token, 'data' => [$data] ])); curl_exec($ch); $info = curl_getinfo($ch); dd($info); curl_close($ch);
eddieace started a new conversation Multiple Domains Per Langauge
Hello, I have a project where I want to have one domain per language. So my sites are pointing to the same domain, but for some reason, one of my domains are being redirected to the other.
To clarify. example.com example.org
example.org is pointed to the same directory as example.com.
When I visit example.org, I get redirected to example.com
I don't know if the problem is that I use LetsEncrypt SSL on both domains.
I use Forge to configure my servers. And I have setup two sites with 2 nginx conf files.
Any clues?
Here is my nginx files
example.com
# FORGE CONFIG (DOT NOT REMOVE!) include forge-conf/example.com/before/*; server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name example.com; root /home/forge/example.com; # FORGE SSL (DO NOT REMOVE!) ssl_certificate /etc/nginx/ssl/example.com/xxx/server.crt; ssl_certificate_key /etc/nginx/ssl/example.com/xxx/server.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers 'XXXXXX-$.com/server/*; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ /(public/mail-signature/.*)$ { } location = /favicon.ico { access_log off; log_not_found off; } location = /robots.txt { access_log off; log_not_found off; } access_log off; error_log /var/log/nginx/example.com-error.log error; error_page 404 /index.php; location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php/php7.1-fpm.sock; fastcgi_index index.php; include fastcgi_params; } location ~ /\.ht { deny all; } } # FORGE CONFIG (DOT NOT REMOVE!) include forge-conf/example.com/after/*;
example.org
# FORGE CONFIG (DOT NOT REMOVE!) include forge-conf/example.org/before/*; server { listen 80; listen [::]:80; server_name example.org; root /home/forge/example.com; # FORGE SSL (DO NOT REMOVE!) # ssl_certificate; # ssl_certificate_key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers 'xxxxxxx-$.org/server/*; location / { try_files $uri $uri/ /index.php?$query_string; } location = /favicon.ico { access_log off; log_not_found off; } location = /robots.txt { access_log off; log_not_found off; } access_log off; error_log /var/log/nginx/example.org-error.log error; error_page 404 /index.php; location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php/php7.1-fpm.sock; fastcgi_index index.php; include fastcgi_params; } location ~ /\.(?!well-known).* { deny all; } } # FORGE CONFIG (DOT NOT REMOVE!) include forge-conf/example.org/after/*;
eddieace left a reply on API Route For Laravel 5.2 Access-Control-Allow-Origin
But for some reason, I can fetch the data using file_get_contents() in PHP. But not from a $http.get() request.
eddieace started a new conversation API Route For Laravel 5.2 Access-Control-Allow-Origin
Hey, I'm trying to build an API from a Laravel 5.2 app.
What i do is return data as this.
return response()->json($data);
Live on the server it works to call this API from an url.
But when I try to access it from another application running laravel 5.4. and using Vuejs it returns this error.
XMLHttpRequest cannot load. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is therefore not allowed access.
The request from vue looks like this.
created() { this.$http.get('') .then(response => { console.log(response); }) .catch(error => { console.log(error); }); },
any clues?
eddieace started a new conversation Chunk.sortModules();
I get this problem when I try to run NPM. Anyone have any clues?
test ⚑ → npm run dev master ✗ 2d > @ dev /Users/myuser/Code/testing/test > node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js 78% advanced chunk optimization/Users/myuser/Code/testing/test/node_modules/extract-text-webpack-plugin/dist/index.js:188 chunk.sortModules(); ^ TypeError: chunk.sortModules is not a function at /Users/myuser/Code/testing/test/node_modules/extract-text-webpack-plugin/dist/index.js:188:19 at /Users/myuser/Code/testing/test/node_modules/async/dist/async.js:3083:16 at eachOfArrayLike (/Users/myuser/Code/testing/test/node_modules/async/dist/async.js:1003:9) at eachOf (/Users/myuser/Code/testing/test/node_modules/async/dist/async.js:1051:5) at Object.eachLimit (/Users/myuser/Code/testing/test/node_modules/async/dist/async.js:3145:5) at Compilation.<anonymous> (/Users/myuser/Code/testing/test/node_modules/extract-text-webpack-plugin/dist/index.js:184:27) at Compilation.applyPluginsAsyncSeries (/Users/myuser/Code/testing/test/node_modules/tapable/lib/Tapable.js:206:13) at Compilation.seal (/Users/myuser/Code/testing/test/node_modules/webpack/lib/Compilation.js:579:8) at /Users/myuser/Code/testing/test/node_modules/webpack/lib/Compiler.js:493:16 at /Users/myuser/Code/testing/test/node_modules/tapable/lib/Tapable.js:289:11 at _addModuleChain (/Users/myuser/Code/testing/test/node_modules/webpack/lib/Compilation.js:481:11) at processModuleDependencies.err (/Users/myuser/Code/testing/test/node_modules/webpack/lib/Compilation.js:452:13) at _combinedTickCallback (internal/process/next_tick.js:131:7) at process._tickCallback (internal/process/next_tick.js:180:9) npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! @ dev: `node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the @ dev script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /Users/myuser/.npm/_logs/2017-09-04T13_55_30_770Z-debug.log
eddieace started a new conversation In 5.4 Mailables In Browser While Editing Css
In 5.4 is there any way to view Mailables in the browser while editing CSS?
eddieace started a new conversation Envoyer, Deploying With Npm Install And Gulp --production
Hi Envoyer fans!
On every deploy I have to run npm install and gulp. This results in longer deploy times.
Is it anyone who have a good solution for this? Cashing the node-modules folder or something like that?
eddieace started a new conversation Failed To Open Stream: HTTP Request Failed! HTTP/1.1 503 First Byte Timeout
When doing a get request to an API I get this error
failed to open stream: HTTP request failed! HTTP/1.1 503 first byte timeout
Anyone has any clues on how to solve it?
eddieace started a new conversation SSL Auto Renew With LetsEncrypt
In this series @JeffreyWay explain how to make LetsEncrypt automatically renew itself. As far as I can see, this is no longer supported in forge?
Or am I wrong?
eddieace left a reply on Helper To Retrive A Users Posts Checking Between Multple Dates.
By the way here is the sql query
select * from `posts` where `posts`.`user_id` = ? and `posts`.`user_id` is not null and `ends_at` between ? and ? or `published_at` between ? and ?
eddieace left a reply on Helper To Retrive A Users Posts Checking Between Multple Dates.
eddieace started a new conversation Helper To Retrive A Users Posts Checking Between Multple Dates.
Hello!
I have written a helper class to get active posts from a specific time span. The problem here is that the condition after orWhereBetween it does not include the user_id.
This would work if i only would like to check one date, but in this case I would like to check both ends_at and published at to get all active posts that touches a specific time span.
Here is my helper method in my User class.
My question is, how do I solve this?
public function activePosts($from, $to) { return $this->hasMany(Post::class)->whereBetween('ends_at', [$from, $to]) ->orWhereBetween('published_at', [$from, $to]) ->get(); }
eddieace started a new conversation Move Images From Old Server To S3 From Url
Hi!
I'm trying to write a script where I'm trying to move images from an old server to s3. Is it possible to do by downloading the image from an url?
For example.
$companies = Company::all(); $companies->each( function ($company) { //some method to download file $file = download($company->logo); //Store on s3 $filename = $file->storeAs('images', uniqid('img_') . "." . $file->guessClientExtension(), 's3'); //Get the new path $new_path = Storage::disk('s3')->url($filename); //save the new path to logo $company->logo = $new_path; //save the new path $company->save(); }
eddieace started a new conversation Validator Max:255 On Url Not Working
Hello!
I have a validator that looks like this. For some reason it does not validate max:255 on url. Why? Otherwise the validator works fine.
$this->validate($request, [ 'title' => 'required', 'url' => 'url|max:255' ]);
eddieace left a reply on Vagrant Up | VBoxManage: Error: Could Not Open The Medium '/Users/myuser/VirtualBox VMs/homestead-7/box-disk1.vmdk'.
I don't really know what the answer is. But must have something to do with permissions for the users on my mac. What I did was that i did some updates on my mac, using an old user which I had forgotten the login details for. After that, I was able to destroy the current VM and create a new one using vagrant up.
eddieace started a new conversation Vagrant Up | VBoxManage: Error: Could Not Open The Medium '/Users/myuser/VirtualBox VMs/homestead-7/box-disk1.vmdk'.
For some reason I got this error.
Any clues on how to solve this?
´´´
There was an error while executing
g `VBoxMan, a CLI used by Vagrant
for controlling VirtualBox. The command and stderr is shown below.
Command: ["startvm", "be05f1d7-efdc-4367-a47f-3373aae0ac78", "--type", "headless"]
Stderr: VBoxManage: error: Could not open the medium '/Users/myuser/VirtualBox VMs/homestead-7/box-disk1.vmdk'. VBoxManage: error: VD: error VERR_FILE_NOT_FOUND opening image file '/Users/myuser/VirtualBox VMs/homestead-7/box-disk1.vmdk' (VERR_FILE_NOT_FOUND) VBoxManage: error: Details: code NS_ERROR_FAILURE (0x80004005), component MediumWrap, interface IMedium
eddieace left a reply on Eloquent Take 25 Random Out Of 400 First Rows Laravel 5.2
My solution.
´´´php $result = Model::where('status', '=', 0) ->orderBy('id', 'desc') ->take(400) ->get() ->random(25); ´´´
eddieace started a new conversation Eloquent Take 25 Random Out Of 400 First Rows Laravel 5.2
Hi I need to make an eloquent request with top 400 rows, and select 25 random.
Right now the query looks like this. I get the latest 400 rows
$result = Model::where('status', '=', 0) ->orderBy('id', 'desc') ->limit(400) ->get(); ```php I know that I can do something like this, but then it will take all rows with status 0 but I want 25 out of the top 400. ```php $result = Model::where('status', '=', 0) -inRandomOrder() ->limit(25) ->get();
eddieace started a new conversation Notifications Bulk Email Laravel 5.3
Hi!
I have a problem sending bulk emails with notifications in Laravel 5.3
The problem is that it's a loop, but it does only send out one email, the first one. Any clues?
Here is the handle method
public function handle() { $users = User::all(); $users->each(function ($user) { $users->notify(new SendSomething($user)); }); }
And here is the notification itself
namespace App\Notifications; use App; use Log; use App\User; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; class SendSomething extends Notification { use Queueable; private $position; /** *) { $user = $this->user; return (new MailMessage) ->to($user->email) ->from('[email protected]', 'example') ->subject('Some subject') ->greeting('Hello ' . $user->name . '!') ->line('How are you?') ->action('Do something', url('/somewhere/')) ->line('Kind regards, <br> u bro'); } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return [ // ]; } }
eddieace started a new conversation Echo And Blade Escapes Strings
I have a codeblock that looks like this.
The ptoblem is that everything after the var _globalObj row becomes green (the whole file)
<script> var _globalObj = '<?php echo json_encode(array('_token'=> csrf_token())) ?>'; var enableUrl = '{{url("admin/positions/enable-editor/" . $position->id)}}'; </script>
I would like to have it something like this
<script> var _globalObj = '{{ json_encode(array('_token'=> csrf_token())) }}'; var enableUrl = '{{url("admin/positions/enable-editor/" . $position->id)}}'; </script>
But for some reason blade escapes alot some json stuff like back slashes etc.
Any clues on how to solve this?
eddieace left a reply on Wordpress On Forge Upstream Sent Too Big Header While Reading Response Header From Upstream
Here is the solution.
You enter the settings
fastcgi_buffers 16 16k; fastcgi_buffer_size 32k;
into etc/ngin/sites-available/example.com
and add it into the location ~ .php$ block
like this.
location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php/php7.1-fpm.sock; fastcgi_index index.php; include fastcgi_params; fastcgi_buffers 16 16k; fastcgi_buffer_size 32k; }
eddieace started a new conversation BelongsToMany With UpdateOrCreate
Hi I have this function. It runs every once in a while and I just added every location that a postition have. In a pivot table. The problem now is that every time it runs it adds a new record in the database. So the position gets new locations every time it runs.
Here is the function:
$position = Position::updateOrCreate(['title' => $position->title, company_id => $company_id], $position); foreach($position->locations() as $location) { $location = Location::firstOrCreate(['name' => $location->name]); $position->locations()->attach($location->id); }
Is there some way I could
if (if position_location not already exists) { $position->locations()->attach($location->id); }
eddieace started a new conversation Wordpress On Forge Upstream Sent Too Big Header While Reading Response Header From Upstream
Hi I have a wordpress site running on forge. I get this error.
502 Bad Gateway
From log:
017/03/07 09:40:30 [error] 12586#12586: *13909 upstream sent too big header while reading response header from upstream, client: 46.59.124.52, server: example.com, request: "GET /wp-admin/post.php?post=123&action=edit HTTP/1.1", upstream: "fastcgi://unix:/var/run/php/php7.1-fpm.sock:", host: "example.com", referrer: ""
Online I have found a few solutions.
The first one is this but the problem is that I don't know where to add it. I have tried both in etc/nginx/nginx.conf and in the location block in sites-available.
fastcgi_buffers 16 16k; fastcgi_buffer_size 32k;
Any clues on how to fix this?
eddieace left a reply on Import Packages With Yarn Or Npm And Install Them Correctly
So @vipin93 you mean like this?
So this is my. */ require('bootstrap-tagsinput'); require('typeahead.js'); Vue.http.interceptors.push((request, next) => { request.headers.set('X-CSRF-TOKEN', Laravel.csrfToken); next(); });
eddieace started a new conversation Import Packages With Yarn Or Npm And Install Them Correctly
Hi, I wonder if there is a complete guide on to instal packages with yarn or NPM. I have done this successfully a few times but it's always a struggle to get it to work together with gulp and elixir.
That are a few packages that you need in alot of projects, for example
bootstrap-datepicker bootstrap-tagsinput datatables font-awesome
What I do when i add these packages is to run;
1. Int the terminal i run yarn add bootstrap-tagsinput
It is then loaded into my package.json
2. Secondly I runyarn to install all my dependencies`
3. Then i need to import it both in my resources/assets/js and resources/assets/sass
Here comes the tricky part. I then want to import all the code into app.js and app.css so i need to import the files from assests
I do something like this. in the app.js
/** * First we will load all of this project's JavaScript dependencies which * include Vue and Vue Resource. This gives a great starting point for * building robust, powerful web applications using Vue and Laravel. */ require('./bootstrap'); require('./bootstrap-tagsinput');
In the css i do this.
// Fonts @import url(); // Variables @import "variables"; // Bootstrap @import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap"; @import "node_modules/bootstrap-tagsinput/dist/bootstrap-tags-input"; @import "style";
I then guess that gulp should import all these files into app.css and app.js in my public folder.
Is this correct?
eddieace started a new conversation Migrate From Outside Homestead
Hi!
I wonder if someone have a soloution on how to use migrate commands outside of homestead?
SQLSTATE[HY000] [2002] Connection refused (SQL: select * from information_schema.tables where table_schema = epoch and table_name = migrations)
I get this error and I have to vagrant ssh onto the virtual machine.
eddieace left a reply on Notification Select Who To Send To
I have now realized that the key is to look into the MailMessage class
<?php namespace Illuminate\Notifications\Messages; class MailMessage extends SimpleMessage { /** * The view for the message. * * @var string */ public $view = [ 'notifications::email', 'notifications::email-plain', ]; /** * The view data for the message. * * @var array */ public $viewData = []; /** * The "from" information for the message. * * @var array */ public $from = []; /** * The recipient information for the message. * * @var array */ public $to = []; /** * The "cc" recipients of the message. * * @var array */ public $cc = []; /** * The "reply to" information for the message. * * @var array */ public $replyTo = []; /** * The attachments for the message. * * @var array */ public $attachments = []; /** * The raw attachments for the message. * * @var array */ public $rawAttachments = []; /** * Priority level of the message. * * @var int */ public $priority; /** * Set the view for the mail message. * * @param string $view * @param array $data * @return $this */ public function view($view, array $data = []) { $this->view = $view; $this->viewData = $data; return $this; } /** * Set the from address for the mail message. * * @param string $address * @param string|null $name * @return $this */ public function from($address, $name = null) { $this->from = [$address, $name]; return $this; } /** * Set the recipient address for the mail message. * * @param string|array $address * @return $this */ public function to($address) { $this->to = $address; return $this; } /** * Set the recipients of the message. * * @param string|array $address * @return $this */ public function cc($address) { $this->cc = $address; return $this; } /** * Set the "reply to" address of the message. * * @param array|string $address * @param null $name * @return $this */ public function replyTo($address, $name = null) { $this->replyTo = [$address, $name]; return $this; } /** * Attach a file to the message. * * @param string $file * @param array $options * @return $this */ public function attach($file, array $options = []) { $this->attachments[] = compact('file', 'options'); return $this; } /** * Attach in-memory data as an attachment. * * @param string $data * @param string $name * @param array $options * @return $this */ public function attachData($data, $name, array $options = []) { $this->rawAttachments[] = compact('data', 'name', 'options'); return $this; } /** * Set the priority of this message. * * The value is an integer where 1 is the highest priority and 5 is the lowest. * * @param int $level * @return $this */ public function priority($level) { $this->priority = $level; return $this; } /** * Get the data array for the mail message. * * @return array */ public function data() { return array_merge($this->toArray(), $this->viewData); } }
eddieace started a new conversation Notification Select Who To Send To
Hi, I have a question regarding notification email receiver.
I have an object that have multiple email-adresses and I only want to notify one of them.
How do I choose what email to notify?
eddieace started a new conversation Vue Rangeslider Mousedrag Not Working
I'm trying to get my rangeslider in vue.js to work. For some reason draggin by using mobile or mousebutton is not working. Clicking is working perfectly. Any clues?
Here is my RangeSlider.vue file
<script> export default { props: { min: { required: true, }, max: { required: true, }, suffix: { required: false, default: '', }, name: { required: true, } }, data() { return { dragging: false, value: 0, id: '', }; }, mounted() { $(window).mouseup(e => { if (this.dragging) { this.dragging = false; } }); $(window).mousemove(e => { if (this.dragging) { this.move(e); } }); this.id = this.makeid(); }, methods: { drag() { this.dragging = true; }, drop() { this.dragging = false; }, move(e) { const sliderPos = $('#' + this.id + ' .range-slider-slider').offset().left; const sliderWidth = $('#' + this.id + ' .range-slider-slider').width(); const min = 0; const max = sliderWidth - $('#' + this.id + ' .range-slider-handle').width(); const position = Math.min(max, Math.max((e.pageX - 25) - sliderPos, min)); $('#' + this.id + ' .range-slider-handle').css({ left: position + 'px', }); const n = this.max - this.min; const k = position / sliderWidth; const v = Number(Math.ceil(n * k)) + Number(this.min); if (v == this.max) { this.value = v + '+'; } else { this.value = v; } }, makeid() { var <input v- <div class="range-slider-slider" @</div> <div :<span class="ranger-slider-label">{{ value }} {{ suffix }}</span></div> </div> </template>
And here is my form-group
<div class="form-group"> <label for="experience">{{ trans('position.experience') }}</label> <range-slider</range-slider> </div>
eddieace left a reply on Vue 2 And Initial Input Form Values
@phoenixcorp do you have an example of how you solved this issue?
eddieace started a new conversation Validation Error Using Form Request.
I have a problem.
I'm using a Form Request but also Vue on my form. My problem is that old('') variables does not work together with Vue v-model.
Here is an example of the input field.
<div class="form-group"> <label for="name">{{ trans('messages.name') }}</label> <input type="text" name="name" v- @if($errors->has('name')) <span class="help"> {{trans('Validations.name')}} </span> @endif </div>
If I remove the v-model="name" the {{ old('name') }} variable works.
This is the error i get from Vue in the browser.
<input v-: inline value attributes will be ignored when using v-model. Declare initial values in the component's data option instead.
and here is my .vue file
<script> import RangeSlider from './RangeSlider.vue'; export default { components: { RangeSlider, }, props: ['fields'], data() { return { name: '', email: '', phone: '', loading: false, errors: {}, }; }, methods: { onSubmit() { this.loading = true; } } }; </script>
eddieace started a new conversation Customizing Emails Notifications Laravel 5.3
Hello! I'm trying to send an email using notifications in 5.3. My problem is that i have one email where i need to loop through an array of multiple items and display them in the email. Is it possible to get the array inside of the email template?
eddieace left a reply on UpdateOrCreate Matching Multiple Attributes Like Company And Record
Well, something else was wrong. This code works perfectly.
eddieace started a new conversation UpdateOrCreate Matching Multiple Attributes Like Company And Post
What I'm tring to do is adding records with the same title and company so that company one and two can have a record with the same title. I'v been trying to use the updateOrCreate method but with no success.
Here is my code, any clues?
$company_id = 12345; $xml = simplexml_load_file($url); $records = array(); foreach ($xml->channel as $x) { foreach ($x->item as $item) { $record[] = [ 'company_id' => $company_id, 'title' => (string)$item->title, 'location' => (string)$item->location, 'description' => (string)$item->description, } } foreach($records as $record) { Model::updateOrCreate(['title' => $record['title'], 'company_id' => $company_id], $record); }
eddieace started a new conversation Nginx Error If I Activate LetsEncrypt Certificate And All Sites Becomes Disabled
Hello fellow Forge Enthusiasts!
I have a problem that if I obtain a LetsEncrypt certificate and activate it something in my nginx configuration returns an error. It also makes all my sites on that server deactivated.
This happens when I try to restart nginx.
Job for nginx.service failed because the control process exited with error code. See "systemctl status nginx.service" and "journalctl -xe" for details. nginx.service is not active, cannot reload.
I wish I could show you how my nginx config in sites-enabled would look like but I have obtained to many already.
I wonder if anyone knows what could be wrong? Could anyone link a working nginx config?
I host all my sites on a AWS EC2 Instance.
eddieace started a new conversation Upstream Timed Out (110: Connection Timed Out) While Reading Response Header From Upstream
I get this error when I run GET requests in my commands. This is the error I get in the log
upstream timed out (110: Connection timed out) while reading response header from upstream, client: xx.xxx.xxxx.xxx, server: stage.myapp.cpm, request: "GET /script/run HTTP/1.0", upstream: "fastcgi://unix:/var/run/php/php7.0-fpm.sock", host: "stage.myapp.cpm,"
As I have understood I should change som settings but i don' know how and where?
Should I change something in sites-enabled? Here is an example
# FORGE CONFIG (DOT NOT REMOVE!) include forge-conf/test.test.com/before/*; server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name test.test.com; root /home/forge/test.test.com/current/public; # FORGE SSL (DO NOT REMOVE!) ssl_certificate /etc/nginx/ssl/test.test.com/122138/server.crt; ssl_certificate_key /etc/nginx/ssl/test.test.com/122138/server$ ssl_prefer_server_ciphers on; ssl_dhparam /etc/nginx/dhparams.pem; index index.html index.htm index.php; charset utf-8; # FORGE CONFIG (DOT NOT REMOVE!) include forge-conf/test.test.com/server/*; location / { try_files $uri $uri/ /index.php?$query_string; } location = /favicon.ico { access_log off; log_not_found off; } location = /robots.txt { access_log off; log_not_found off; } access_log off; error_log /var/log/nginx/test.test.com-error.log error; error_page 404 /index.php; location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php/php7.0-fpm.sock; fastcgi_index index.php; include fastcgi_params; } location ~ /\.ht { deny all; } } # FORGE CONFIG (DOT NOT REMOVE!) include forge-conf/test.test.com/after/*; | https://laracasts.com/@eddieace | CC-MAIN-2019-30 | refinedweb | 5,485 | 51.34 |
Hi to all, I've been trying to write one small program, and I got stuck. I mean, it is finished, it compiles, but does not work as it is supposed to. The task is to keep accepting input from user (words, one by one) until the program spots a four-letter word. That's when it stops and displays the smallest and longest word entered so far.
What is wrong? Well, the "count" variable does not record the new value when entering the while loop again at all. It keeps being incremented by next entered word... What's more, the length of smallest/largest word is not counted at all.
I will appreciate your fresh look at my code...I will appreciate your fresh look at my code...Code:
#include <stdio.h>
#include <string.h>
#define LEN 20
int main()
{
int count;
int i = 0;
int count_smallest;
int count_largest;
char word[LEN];
char smallest_word[LEN];
char largest_word[LEN];
char ch;
do {
printf("Enter a word: ");
while( (ch = getchar()) != '\n')
if(i < LEN)
word[i++] = ch;
word[i] = '\0';
count = strlen(word);
count_smallest = strlen(smallest_word);
count_largest = strlen(largest_word);
if(count <= count_smallest)
strcpy(smallest_word, word);
else
strcpy(largest_word, word);
}
while(count != 4);
printf("Smallest word is %d letters long and it is: ",
count_smallest);
puts(smallest_word);
printf("\n");
printf("Largest word is %d letters long and it is: ",
count_largest);
puts(largest_word);
printf("\n");
return 0;
} | https://cboard.cprogramming.com/c-programming/62097-some-help-plz-finding-long-shortest-words-printable-thread.html | CC-MAIN-2017-13 | refinedweb | 233 | 74.59 |
Hi Everyone,
This is my first post on this forum. I am pretty new to programming so any help is greatly valued here. Was hoping someone could steer me in the right direction with this Dice-Poker style program I am trying to write in C#.
So far I am able store random numbers between 1 and 6 in two arrays(compRoll and userRoll) and print the results.
Where I'm stuck right now is how to use a function to find matching elements in the array itself. Then storing the number of matches, even their values so that I can print whether there are 2 of a kind, 3 of a kind, etc. The player with more matches wins. In the event of a tie between the comp and user I would just need to measure the value of the matches to determine the winner. In an all out tie I guess you just re-roll.
If you have any suggestions on how I can find the matches in the array, then use them to determine the winner, I'd be very grateful.
If I am posting this in the wrong place kindly point me to the right place. Thanks for reading this.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Project_3 /*Dice Game by Brett * Computer rolls five dice and user rolls five dice. * Rank: 5 of a kind > 4 of a kind > 3 of a kind > 2 of a kind. * If both computer and user have a pair, higher dice value wins. * If both pair values are same then next highest number in the hand wins. * If all of both computer and user values are identical, Tie game. * If either player doesn't at least have a pair highest number wins.*/ { class Program { static void Main(string[] args) { const int DICE = 5; int[] compRoll = new int[DICE]; int[] userRoll = new int[DICE]; int x = 0; ComputerRoll(x,compRoll,compHand,DICE); UserRoll(x,userRoll,userHand,DICE); } static void ComputerRoll(int x,int[] compRoll,int DICE) { Random RandNum = new Random(); Console.Write("{0,-20}","Computer Rolled: "); for (x = 0;x < DICE;x++) { compRoll[x] = RandNum.Next(1, 7); Console.Write("{0,-2}",compRoll[x]); } } static void UserRoll(int x,int[] userRoll,int DICE) { Random RandNum = new Random(); Console.Write("\n\n{0,-20}", "You Rolled: "); for (x = 0; x < DICE; x++) { userRoll[x] = RandNum.Next(1, 7); Console.Write("{0,-2}", userRoll[x]); } } } } | https://www.daniweb.com/programming/software-development/threads/263499/finding-duplicate-elements-in-an-array | CC-MAIN-2017-17 | refinedweb | 409 | 66.54 |
06 February 2019 0 comments Javascript, ReactJS
React 16.8.0 with Hooks was released today. A big deal. Executive summary; components as functions is all the rage now.
What used to be this:
class MyComponent extends React.Component { ... componentDidMount() { ... } componentDidUpdate() { ... } render() { STUFF } }
...is now this:
function MyComponent() { ... React.useEffect(() => { ... }) return STUFF }
Inside the
useEffect "side-effect callback" you can actually update state. But if you do, and this is no different that old
React.Component.componentDidUpdate, it will re-run the side-effect callback. Here's a simple way to cause an infinite recursion:
// DON'T DO THIS function MyComponent() { const [counter, setCounter] = React.useState(0); React.useEffect(() => { setCounter(counter + 1); }) return <p>Forever!</p> }
The trick is to pass a second argument to
React.useEffect that is a list of states to exclusively run on.
Here's how to fix the example above:
function MyComponent() { const [counter, setCounter] = React.useState(0); const [times, setTimes] = React.useState(0); React.useEffect( () => { if (times % 3 === 0) { setCounter(counter + 1); } }, [times] // <--- THIS RIGHT HERE IS THE KEY! ); return ( <div> <p> Divisible by 3: {counter} <br /> Times: {times} </p> <button type="button" onClick={e => setTimes(times + 1)}> +1 </button> </div> ); }
You can see it in this demo.
Note, this isn't just about avoiding infinite recursion. It can also be used to fit your business logic and/or an optimization to avoid executing the effect too often.
Follow @peterbe on Twitter | https://www.peterbe.com/plog/avoid-infinite-recursion-in-react.useeffect | CC-MAIN-2019-18 | refinedweb | 238 | 52.46 |
The sinc function is defined by
sinc(x) = sin(x)/x.
This function comes up constantly in signal processing. Here’s a plot.
We would like to find the location of the function’s peaks. Let’s focus first on the first positive peak, the one that’s somewhere between 5 and 10. Once we can find that one, the rest will be easy.
If you take the derivative of sinc and set it to zero, you find that the peaks must satisfy
x cos x – sin x = 0
which means that
tan x = x.
So our task reduces to finding the fixed points of the tangent function. One way to find fixed points is simply to iterate the function. We pick a starting point near the peak we’re after, then take its tangent, then take the tangent of that, etc.
The peak appears to be located around 7.5, so we’ll use that as a starting point. Then iterates of tangent give
2.7060138667726910 -0.4653906051625444 -0.5021806478408769 -0.5491373258198057 -0.6119188887713993 -0.7017789436750164 -0.8453339618848119 -1.1276769374114777 -2.1070512803092996 1.6825094538261074
That didn’t work at all. That’s because tangent has derivative larger than 1, so it’s not a contraction mapping.
The iterates took us away from the root we were after. This brings up an idea: is there some way to iterate a negative number of times? Well, sorta. We can run our iteration backward.
Instead of solving
tan x = x
we could equivalently solve
arctan x = x.
Since iterating tangent pushes points away, iterating arctan should bring them closer. In fact, the derivative of arctan is less than 1, so it is a contraction mapping, and we will get a fixed point.
Let’s start again with 7.5 and iterate arctan. This quickly converges to the peak we’re after.
7.721430101677809 7.725188823982156 7.725250798474231 7.725251819823800 7.725251836655669 7.725251836933059 7.725251836937630 7.725251836937706 7.725251836937707 7.725251836937707
There is a little complication: we have to iterate the right inverse tangent function. Since tangent is periodic, there are infinitely many values of x that have a particular tangent value. The arctan function in NumPy returns a value between -π/2 and π/2. So if we add 2π to this value, we get values in an interval including the peak we’re after.
Here’s how we can find all the peaks. The peak at 0 is obvious, and by symmetry we only need to find the positive peaks; the nth negative peak is just the negative of the nth positive peak.
The peaks of sin(x)/x are approximately at the same positions as sin(x), and so we use (2n + 1/2)π as our initial guess. In fact, all our peaks will be a little to the left of the corresponding peak in the sine function because dividing by x pulls the peak to the left. The larger x is, the less it pulls the root over.
The following Python code will find the nth positive peak of the sinc function.
def iterate(n, num_iterates = 6): x = (2*n + 0.5)*np.pi for _ in range(num_iterates): x = np.arctan(x) + 2*n*np.pi return x
My next post will revisit the problem in this post using Newton’s method. | https://www.johndcook.com/blog/2021/01/17/reverse-iteration-root-finding/ | CC-MAIN-2021-21 | refinedweb | 556 | 74.69 |
This article covers a selection of best practices related to the internals of the project “sandbox”. The sandbox is understood as a folder with a complete structure containing the source files of a specific product.
This is Part II of “Agile Sandbox” article. Make sure you've read Part I.
As previously mentioned in this article, CodeBase is a sandbox in a sandbox designed for working from Visual Studio. The main rule that we know now regarding Visual Studio and this folder – never try swimming against the current. Let me try to explain the rule using a couple of examples:
The thesis is the following: inside CodeBase, agree with Visual Studio in everything. Let it create the AssemblyInfo.cs it deems correct, let it put the binaries into the standard bin and obj folders, don’t intervene. Just make sure to add all the side products of Visual Studio to the SVN-ignore-list: *.user, *.suo, bin, obj (by the way, VisualSVN does it all automatically). The contents of the CodeBase folder are intended for developers only and are not real builds. Real ones with correct assembly metadata, keys and other attributes can be created by NAnt. That’s what we are going to take a look at below.
Practice shows that it’s better to name projects in the following manner: YourCompanyName.ProductName.Qualifier. As namespace and assembly name are initially inserted into the project name, they will automatically comply with Microsoft guidelines if this rule is observed.
YourCompanyName.ProductName.Qualifier
This approach has the following advantages:
Another useful rule: the structure of namespaces must match the folder structure and the names of source files must match the types they define. Observing this rule will eliminate any ambiguities in juxtaposing type names and files, namespaces and folders. Such juxtaposition may be required for build automation with NAnt. In fact, in order to stick to this rule, you just don’t need to hamper Visual Studio: it automatically generates namespaces according to the following formula: RootNamespace.Level1Subdirectory.LevelNSubdirectory. In our case, RootNamespace is YourCompanyName.ProductName.Qualifier, therefore the resulting namespace will have a proper form.
RootNamespace.Level1Subdirectory.LevelNSubdirectory
RootNamespace
If a source file defines only one type and the name of the file is the same, Visual Studio also associates them with one another and will, for instance, rename (refactor) the type if the file is renamed. The only exception pertains to enums and interfaces. They are all defined at once in Enumerations.cs and Interfaces.cs respectively. Their definitions are always compact and, so allocating a separate file to each of them is unpractical – visually, it only complicates the structure and makes it less readable.
enum
A couple of words about unit tests. Or, to be specific, about the projects containing them. The names of such projects correspond to the names of “tested projects” and have a “Tests” qualifier. For example, a test project for YourCompanyName.ProductName.Core would be called YourCompanyName.ProductName.Core.Tests. This scheme allows you to easily filter out all assemblies with tests using the *.Tests.dll mask knowing that the tested and test projects are stored together in Solution Explorer. Ironically, we concluded that we had to break the above namespace/folder matching rule inside test projects. Not that you need to create anarchy in them, no. Let me use an example. Imagine a project called Company.Project.Core. It will be tested by Company.Project.Core.Tests with the same root namespace. Everything’s fine when types from the root namespace are tested. The Company.Project.Core.SomeTypeToTest type will be available from the Company.Project.Core.Tests namespace according to .NET rules. Now try imagining a type called Company.Project.Core.Network.Helpers.SomeTypeToTest. It won’t be available from Company.Project.Core.Tests or Company.Project.Core.Tests.Network.Helpers, which will be suggested separately. You will have to add a number of “using” directives to the Test Fixture file:
YourCompanyName.ProductName.Core
YourCompanyName.ProductName.Core.Tests
Company.Project.Core
Company.Project.Core.Tests
Company.Project.Core.SomeTypeToTest
Company.Project.Core.Tests namespace
Company.Project.Core.Network.Helpers.SomeTypeToTest
Company.Project.Core.Tests.Network.Helpers
using
using Company.Project.Core.Network.Helpers
using Company.Project.Core.Network
Their number will increase along with the depth of the namespace. For the example above, the “right” namespace for Test Fixture is Company.Project.Core.Network.Helpers.Tests. This helps avoid creating multiple “using” directives, be more flexible in terms of refactoring, although forcing you to correct the default namespace while creating any file of level 2 and deeper in a test project.
Company.Project.Core.Network.Helpers.Tests
There are plenty of holy wars being waged about it on the Internet. Some claim that only one file is needed for all projects; others advocate for a “one solution – one deployment entity” approach or an intermediate variant. We use one solution per group of projects, which form something useful and self-sufficient for a specific type of consumers. If it’s an online game, then one sln file contains all the server-related stuff, the other one - the end-user client and the third one holds the level editor. Of course, different solutions can use the same projects. This approach causes no problems, except for one: during automatic refactoring that changes the interface of types in common projects, these changes will become known only to those consumers who are defined in projects belonging to the currently opened solution. Other solutions will show something like “error CS0246: The type or namespace name ‘Foo’ could not be found” during the build process.
Foo
In practice, this has never been a major problem. We quickly made changes manually. Although in difficult cases, you may want to create a temporary .sln file for all the projects.
You could also notice 2 subfolders in CodeBase: Libraries and MSBuildExtensions. MSBuildExtensions contains all the .targets and .dll files of MSBuild, which are not available in the default .NET Framework package. For instance, if you need to build an ASP.NET application in Visual Studio 2003 style under version 2005, you will need the Microsoft.WebApplication.targets extension; that’s the right place for it. In reality, the contents of this folder are not used for work within CodeBase. They are required for building with NAnt to guarantee the possibility of building on any system. We’ll talk about it later, however.
Microsoft.WebApplication.targets
The Libraries category contains all third-party .NET assemblies used in the product. Please note that it contains absolutely all libraries, even those ones that have a nice and comfortable installer to the GAC. This is related to providing independence from the machine used for building. That is why any reference in your project is either an assembly from the standard .NET framework or a reference to an assembly in the Libraries folder.
I also want to note that even the nunit.framework.dll assembly is stored here. Building test projects and their testing are totally different things. That is why nunit.framework.dll is separated from the main distributive located in the mentioned BuildTools folder.
An assembly can end up being in Libraries only if it is available from the manufacturer in a precompiled form or if it was built without any changes being made to the source codes. In other cases, its source files should be placed into CodeBase along with your own ones and be a part of the build process. Why would you need that? It’s simple: if you do not save the history of changes in the library source files, then, when an update is released, you will face serious problems trying to combine “your” and “their” modifications.
In fact, modifying third-party libraries is a separate topic. The more drastic your changes are and the longer the time since your first modification, the greater the possibility that you will be unable to combine your own changes and those of the manufacturer. That is why, each time when you are going to “slightly fix” the source codes of a third-party product, think: is it a quick hack for satisfying your personal needs or a useful change to complement and improve the manufacturer’s functionality. If it’s a hack, try to forget about it - sooner or later this decision will yield some pretty bad results. If it’s something useful, make sure you do the following: implement your changes in the product’s style, make a patch and send to the manufacturer. The next version will feature your changes by default, and the source codes can be replaced by a precompiled library. So the goal is to get rid of the source codes of “alien” libraries.
To be continued: Part. | http://www.codeproject.com/Articles/24441/Agile-Sandbox-Part-II | CC-MAIN-2015-32 | refinedweb | 1,460 | 57.57 |
Things You'll Need:
- Vitamin C
- Vitamin B-6
- Whole-grain Bread
- Evening Primrose Oil
- Multivitamins
- Magnesium Supplement
- Fresh Fruit
- Calcium Supplement
- Vitamin E
- Dark Leafy Green Vegetables
- Step 1
Reduce or eliminate caffeine intake.
- Step 2
Avoid alcohol and sugar during the time of month when you usually begin getting PMS symptoms.
- Step 3
Add leafy green vegetables, fresh fruit, cereals and whole grains to your diet.
- Step 4
Cut back on or eliminate dairy products from your diet.
- Step 5
Avoid salty foods, red meat and processed foods for at least one week before the expected onset of PMS symptoms.
- Step 6
Take a multivitamin with 100mg of vitamin B-6, 400mg of vitamin E, 1,000mg of vitamin C and about 1,500mg of evening primrose oil.
- Step 7
Take calcium and magnesium supplements to help prevent cramps.
- Step 8
Get checked for food allergies.
- Step 9
Exercise regularly.
- Step 10
Find constructive outlets for stress.
brandyprice said
on 2/20/2009 Thanks for the natural tips :-) I love the natural way.
Indigoabby said
on 12/18/2008 These are great ideas. I find it's important for me to do something to relax right before the PMS symptoms get bad. I like to get a massage (when I can afford it!) Or sit in a hot tub or bath for a long time. I find relaxing just before PMS kicks in alleviates a lot of the symptoms.
Anonymous said
on 4/3/2006 Try using a few drops of Agnus Castus (Chaste Berry) available from Health Food Stores. An inexpensive remedy that really works. Tastes disgusting, so I put a few drops in a sweet drink. It works like magic.
Anonymous said
on 1/25/2006 Many women with PMS turn out to be low in progesterone during the symptoms. Low progesterone can cause cramping, irritability, anxiety, depression, mood swings, insomnia, increased headaches in some women (particularly migraine sufferers), history of miscarriage in some, and a variety of other symptoms. Long term, low progesterone can lead to an increase in cell-proliferative disorders, like cysts, fibroids, endometriosis, and even cancer.
The synthetic progestins in birth-control (BC's) and Provera are not a good substitute for progesterone. They help with some of the symptoms, but often make the psychological symptoms worse. They also compete with your own progesterone for binding sites and discourage the body from making as much progesterone (which can also worsen symptoms). Some (not all) women's PMS gets better when they discontinue BC's; in any case you should discontinue BC's before trying progesterone. The progesterone won't work well with the BC's in your system (sorry!).
Progesterone supplementation can be done without prescription with products such as Pro-Gest by Emerita. You may apply the cream twice daily from day 14 of your cycle (or when symptoms begin) until the day your period is due. At that point, most women can use a 1/2 dose for 2 days, then stop until symptoms return (or day 14 of the next cycle). The effects of the progesterone can often be felt within 1 hour of application.
Side effects: if one gets too much progesterone, it can delay the beginning of the period; can cause drowsiness/lethargy in some; in a very few women, even a small amount of progesterone might cause a headache (as opposed to the majority of women, who get less headaches with progesterone). Bear in mind that the increase in progesterone you are creating with supplementation is nowhere near the high levels that one reaches during pregnancy. Progesterone supplementation is much less likely to cause harm than many other hormones might, which is why it is allowed to be sold without a prescription.
It would be even better, of course, to have a health practitioner follow and occasionally test your supplementation. But, most prescriber's are unfamiliar with this use of progesterone. Since it is not patentable, no large drug manufacturer is interested in it; so no magazine ads, no prime-time spots, no multi-million dollar studies, and no free, fancy, "continuing-education" dinners for the doctors.
Many alternative medicine prescriber's are familiar with it, but often they are not covered by insurance. Fortunately, most women can "dose-to-symptoms" and find a reasonable dosage that way.
Progesterone consumption increases greatly under stress; during stressful times the dose may need to be temporarily increased to cover the symptoms. Also, women with migraines frequently need much higher doses than average. If the standard dosage on the package seems inadequate, I strongly advise them to seek out an alternative medical practitioner with experience in hormones.
To find one: first find a compounding pharmacy in your area (call 1-800-927-4227); ask the pharmacist whom they would recommend. The pharmacist may also be able answer any other questions you have about progesterone therapy.
Do check this out. It is much better to find out you're low in progesterone now than after a miscarriage or a hysterectomy.
Anonymous said
on 11/22/2005 Usually, a hot cup of tea or coffee and 2 Tylenol menstrual or Panadol does the trick. For those who have unbearable cramps, try a shot glass of rum. A bowl of ice cream or Jell-O regularly does the trick. Seriously avoid Coca Cola or Pepsi, try other sodas. And drink lots of milk based drinks and yogurts! | http://www.ehow.com/how_1962_avoid-getting-pms.html | crawl-002 | refinedweb | 905 | 63.09 |
Where do UDC files come from?
Where do UDC files come from? - I knew you’d ask. (For those of you who are wondering what a UDC file is, you should go read my post entitled "Making data connections work in browser forms.")
There are a couple of ways to go about it. UDC files are just xml files with a specific namespace and schema, so once you have a few examples you can probably get around handily with notepad and cut and paste. However, we’ve made it easier than that with the new Convert functionality on the Manage Data Connections dialog. (For those intrepid souls who prefer the notepad route, a schema reference is being prepared for publication.)
If you start out by designing your data connection the way you normally would, you can then use the Convert button to change the connection from settings in the form template to settings in a data connection file. (In fact, you can open any existing form template in InfoPath 2007 and convert existing data connections the same way.)
To start with, make sure you have write permissions to a data connection library (henceforth "DCL") on the Microsoft Office SharePoint 2007 server you’re going to publish your form to. Then, using InfoPath 2007 Beta 2 or later, create your data connection or open a form template with an existing data connection. Make sure the connection is to a source supported by UDC. (E-mail connections, connections to a Microsoft Access database, or connections to an XML file in the form template cannot be converted to UDC connections.)
Here’s the data connections dialog showing a few connections I threw together (you can get to this dialog off of the "tools" menu in InfoPath design mode):
Click the Convert button and specify the path to your data connection library. If you click "Browse...", InfoPath will suggest a filename based on the name you gave the data connection when it was created.
If you choose a data connection file that already exists, InfoPath will use the settings in the file you chose - don’t expect it to overwrite the original file with new settings. This could have unexpected results if the file that’s already in the library is a different connection type or returns data that does not conform to the schema your form template expects.
For most cases, you want to leave the default connection link option. Choosing "centrally managed connection library" will cause InfoPath and Forms Services to look for the UDC file in the "Manage data connection files" library in SharePoint central admin. This is fine, but it means that you need to copy the file from the DCL where you created it to that location before you can use it. This presumes you have access to SharePoint Central Admin. See my last blog post entitled "Making data connections work in browser forms" for more information on this option.
Once you click "OK" on this dialog, your UDC file will be created and saved to the location you specified, and the connection in the form template will be modified to retrieve settings from the UDC file rather than from the form template.
NOTE: There’s a known issue in the Beta 2 release where you will see an "invalid URL" dialog at this point. This is benign and is no longer seen in the technical refresh.
You now have a UDC file in your DCL, but you’re not quite done. By default, a DCL will require content approval before anyone other than the file’s owner can use the UDC file you uploaded. Unless the content approval requirement has been removed, a site administrator or someone else with the content approval right will need to set the file’s status to "approved."
Adding Authentication
InfoPath does not automatically configure server-only authentication options for you. However, when creating a UDC file, InfoPath automatically creates an authentication block within the UDC file that is preconfigured to use Office Single Sign-on. In order to use this authentication option, you’ll need to uncomment the authentication block within the file and add both the SSO application ID and the CredentialType. Most of the time, you’ll want to use the SSO credential to log onto Windows, for which you’ll need to specify "NTLM" as the CredentialType. The full list of possible credential types is as follows:
Reusing existing UDC files
Once you’ve created your UDC file, you may want to use the same connection for other form templates. Among other things, this has the benefit of sharing settings for multiple forms in a common location. Changing the settings in the UDC file will cause all of the related forms to pick up the changes the next time they are used.
There are several places in InfoPath where we expose the ability to re-use data connection settings exposed as UDC files in a data connection library. Here are a few examples:
All of these entry points lead to this dialog:
When you specify one or more SharePoint sites to search, this dialog allows you to browse available UDC files containing in DCLs on those sites. Based on the context, this dialog is filtered to show only applicable connections (for example, if you start from the "Design a form" dialog, this dialog will only show Web service and database connections).
Once you’ve specified the UDC file to use, you may need to specify some properties for the connection that are not contained in the file (for example, for a SharePoint list connection, you’ll be asked to specify which columns to include in the data source), but otherwise, you’re done.
- Nick Dallett
Program Manager | https://docs.microsoft.com/en-us/archive/blogs/infopath/where-do-udc-files-come-from | CC-MAIN-2020-10 | refinedweb | 958 | 57.3 |
Friday, January 7, 2011 | 50¢
Uwharrie panel discusses potential, resources at first meeting Commission-
ers, talk-
JOn C. LaKey/sALIsBUrY PosT FILe PhoTo
Activity around high rock Lake’s dam may be among issues See UWHARRIE, 2A the Uwharrie Commission looks into.
JUST A-SWINGIN’
Three face charges in credit card scheme BY SHELLEY SMITH ssmith@salisburypost.com
sean meyers/For The sALIsBUrY PosT
Bob and Laura Williamson practice their moves during a Big Band Bash preparation dance class at the City Park Center.
Dance practice precedes Big Band Bash BY EMILY FORD eford@salisburypost.com
et into the swing of things with swing dance lessons. People attending the Big Band Bash on Saturday can take a free swing dance lesson today from 6 to 7 p.m. at the City Park recreation center. People who aren’t headed to the bash — a fundraiser for the Salisbury Symphony Orchestra — can sign up for paid swing dance lessons that start next month. Instructor Diana Moghrabi, who works for Salisbury Community Planning Services, has donated her expertise for the past two nights to teach free lessons at City Park. “I just love to see people dance,” she said. This is the second year she’s offered lessons before the Big Band Bash. Moghrabi specializes in teaching beginners. Moghrabi also will teach a paid dance class through the Salisbury Parks and Recreation Department. The class will run from 7 to 8 p.m. Fridays, beginning Feb. 4 and ending March 11. The cost is $30 for singles and Bob and Dotty Clement keep their eyes on $50 for couples. To sign up, call their toes during a dance class. 704-638-5295. Big Band Bash attendees who want a free lesson Friday can just said. show up at City Park. Twenty people Contact reporter Emily Ford at 704had the place swinging Wednesday. 797-4264. “We had a great time,” Moghrabi
The Salisbury Police Department arrested three people late Wednesday who are accused of using counterfeit credit cards to buy gift cards from Walmart, Police Chief Rory Collins reported Thursday. A tip came from the Concord Police Department less than an hour before the arrest. Concord Police were investigating a case at a Concord Walmart where three people had bought $1,000 worth of gift cards with a fraudulent credit card. Concord officers called Salisbury Police to warn that the suspects could target Salisbury. Salisbury Police called Walmart to let them know of Concord’s case, and 10 minutes later, police received word from Salisbury Walmart’s loss prevention that a female suspect was in the electronics section of the store trying to buy gift cards. When officers arrived, they immediately arrested Michelle Latrice Bracey, 38, of 10 Idaho Drive, Sumter, S.C.
See CHARGES, 2A
G
Annmarie Templeton and Patrick Malloy, both from Lexington, practice a few dance moves during a Big Band Bash preparation dance class, taught by Diana Moghrabi at the City Park Center.
Fancy footwork was on display during the practice session Thursday.
[|xbIAHD y0 0 1rzu
Today’s forecast 45º/22º Chance of showers
Deaths Please recycle this newspaper
Wayne Shanks William Alexander, Jr. Sando Kimba Blanche Julia Baker Lambert
Contents
BRACEY
FORD
EDWARDS
Man survives gunshot to head BY SHAVONNE POTTS spotts@salisburypost.com
DeMario “Mario” Whisonant is a self-professed family man. But if things went different, Thursday morning could have been the last time he saw his family. Whisonant, 22, was robbed and shot in his own neighborhood Thursday while walking near Fulton Street businesses Latin Mix and Cut Up and Dye to meet his cousin. At about 5:30 p.m., three young men and a woman approached him and asked if he had a cigarette. When he pulled out the cigarettes from his pocket, he pulled $40 out with it. Whisonant said he didn’t intend to take the money out, but as he did, one of the males pulled out a gun and pointed it at him, demanding the money. He spoke with a Post reporter just hours after the incident. “I asked, ‘Why y’all doing this?’ ” he said. Whisonant stepped back, but the man got closer and fired. Instinctively, Whisonant swiped at the gun. The bullet grazed his forehead, creating a gash near his hairline as it whizzed past. “I felt it hit me,” he said, a bandage still cover-
Bridge Classifieds Comics Crossword
See SHOT, 12A
11B 5B 10B 10B
Deaths 4A Home & Garden 10A Horoscope 11B Opinion 8A
Second Front 3A Sports 1B Television 11B Weather 12B
2A • FRIDAY, JANUARY 7, 2011
Landis seeks new parks director BY SHAVONNE POTTS spotts@salisburypost.com
LANDIS — The town is advertising for a new director of parks to fill a position formerly held by Julie Noblitt. Town Manager Reed Linn said Thursday that Noblitt is no longer with the town and has not been since August. He did not elaborate about the circumstances surrounding her departure. The town is looking for a director who can develop the parks, and for someone with an extensive background with writing grants and working with the private and corporate sector to secure funds for its passive park and to develop the wilderness area near Lake Corriher and the town’s reservoir. In an advertisement, the town is not only seeking someone to be able to secure grant funding, but also create the park department’s annual budget, attend board meetings and inspect the facilities weekly. The town hopes to fill the position by early February. Linn said the new director, depending on qualifications, would have a salary comparable to Noblitt’s Noblitt began as a parttime seasonal lifeguard with the town in 1997. In February
CHARGES FROM 1a She had just bought $700 in gift cards. Police found several other gift cards in her purse, police said. The investigation continued and the credit cards used to buy the gift cards came back as fraudulent — the numbers on the cards did not match the names on the cards. “It appears the card was fake,” Police Chief Rory Collins said. The other two suspects with Bracey — Don Marshall Ford Jr. and Terrence Antonio Edwards — were searched, as was their car, and police say they found more gift cards, credit cards and cash.
2001, she was appointed to the position of parks director with an annual salary of $26,500. Noblitt maintained the same position until leaving Aug. 23 with an annual salary of $30,766. Town Attorney Rick Locklear noted the town had long been moving toward much of its active programs being taken over by volunteers. Discussion about a league that would take over the ball programs began in June when the town decided it would no longer handle such programs. The town board had on two occasions voted to disband the recreation department. At Noblitt’s insistence, the board made some cuts and reorganized. The Southern Rowan Sports League, which is managed by volunteers, was formed in July. The league buys and provides all necessary equipment, secures team sponsors and establishes league schedules — duties that used to be handled by the recreation director. In April, the town opted to have an outside company manage and maintain its pool, which is now handled by Charlotte Swim Club Management Inc. in Huntersville. Locklear said he believes the direction the town is heading in is one of a passive recre-
Police notified the Concord Police Department, which sent officers to Salisbury to file charges, and contacted the Secret Service, in case they need to be involved in the case. Bracey was charged with four felony counts of obtaining property by false pretenses and given a $25,000 secured bond. Ford, 26, of 544 S. Sumter St., Sumter, S.C., was also charged with four felony counts of obtaining property by false pretenses and given a $25,000 secured bond. Edwards, 42, of 6215 Bennettsville Lane, Charlotte, was charged with four felony counts of obtaining property by false pretenses and one misdemeanor count of possession of stolen goods. The three suspects will appear in Rowan County court
Posters Deadline for posters is 5 p.m. • VFW Post 3006 breakfast to benefit veterans — 7-11 a.m., Saturday, Jan. 8, all you can eat, adults $6, children 10 and under $3, VFW Post on Brenner Ave., 704-636-2104. • Elmwood UMC Brunswick stew dinner, 11 a.m.-2 p.m., Saturday, Jan. 8, $7 all-you-can-eat, also pint-quart-gallon available. 3232 Old US Hwy 70, call Sylvia 704-872-1070 or Wilda 704-528-3685, if no answer, leave message. • Salisbury Seventh-day Adventist Church, 305 Rudolph Rd., Saturday, 11 a.m., Pastor Sven F. Behm, “This Ministry.” Saturday Sabbath school, 9:45 a.m. • Jerusalem Baptist Church’s men’s ministry health fair, Saturday, Jan. 8, 1-3 p.m., church fellowship hall. Guest speaker, Diane Griffin of the Salisbury VA Medical Center. Open to the public.
Lottery numbers — RALEIGH (AP)— The winning lottery numbers selected Thursday in the N.C. Education Lottery: Daytime Pick 3: 9-4-0 Evening Pick 3: 5-3-3 Pick 4: 1-9-2-8 Cash 5: 08-09-20-25-28 STOCKS OF LOCAL INTERESTm ... 2.02e .98 ... .62 ... ... .44 1.44 1.45f 1.12 2.48
14 ... 8 ... 12 ... 16 10 53 18 17 69 14 14
YTD Last Chg %Chg 39.35 4.36 10.32 72.50 17.74 .55 44.39 20.39 6.90 24.13 63.80 43.91 27.98 43.90
+.47 +2.7 ... +.3 -.02 -.4 -1.69 -1.6 -.03 -.4 +.13 +69.2 -.60 -10.7 -.12 ... -.14 -1.1 -.55 -3.8 +.08 +1.6 -.41 +.2 -.09 +.1 +1.13 +1.0
Name
Div
PE
YTD Last Chg %Chg
RedHat
...
93 46.25 -.30
+1.3
RexAmRes
...
9 15.80 -.07
+2.9
ReynAm s 1.96f
14 33.85 +1.00
+3.8
Ruddick
.52f
15 35.10 -.32
-4.7
SonocoP
1.12
17 34.93 +.08
+3.7
SpeedM
.40
28 15.53 -.06
+1.4
SunTrst
.04
... 28.65 -1.10
-2.9
UnivFor
.40
61 39.21 +.04
+.8
VulcanM
1.00
... 40.49 -.77
-8.7
.20
13 32.15 -.22
+3.7
WellsFargo
HOW TO REACH US........
Daily & Sun. Sunday Only
SALISBURY POST
S TAT E / A R E A
Home Delivered Rates: 1 Mo. 3 Mo. 6 Mo. 12.00 36.00 70.50 8.00 24.00 46.80
Yr. 141
ation department. In addition to allowing people to fish at Lake Corriher, the town also talked in August about clearing an area near Lake Wright for a walking trail, which would connect to the J. Fred Corriher Y. All of the parks and greenways are a part of the town’s Parks and Recreation master plan, which was unveiled at a July 2010 meeting. Locklear said Noblitt received a severance package. “The agreement was for three months salary for September, October and November,” he said. Noblitt was paid for all accumulated vacation time. The town will hold her sick leave in accordance with the town’s personnel ordinance that states if she becomes employed by any other government agency or municipality, her sick leave will roll over to that entity. Locklear said the departure was amicable, but he did not provide details as to whether Noblitt was terminated or resigned. Attempts by the Post to contact Noblitt were unsuccessful. Contact reporter Shavonne Potts at 704-7974253.
this morning. Collins called the discovery of people using counterfeit cards “unusual” for Salisbury.
Deeds
UWHARRIE FROM 1a ing DENNIS-7974222.
State’s first flu death of year a teenager RALEIGH (AP) — As flu cases spike around the Southeast, North Carolina health officials on Thursday urged residents to get vaccinated against the illness in light of the death of a 15-year-old. The state Department of
Health and Human Services said the teenager, whose name, hometown and gender are being withheld over privacy concerns, died Wednesday. The teen had not been vaccinated, and was otherwise healthy.
“Our flu season is just ramping up,” said state Health Director Dr. Jeff Engel, who added that flu season in North Carolina typically peaks in late February or early March. Illnesses being reported have been increasing lately.
McLamb, $190,000. Charles T. Lefler and wife to Christopher American Land Corporation-Charlotte Inc. Michael Chapman, $60,000. Real estate transfers filed in the office to Wendy S. Poe, $70,000. Wallas Hylton and wife to Michael E. Mock American Land Corporation-Charlotte Inc. of Register of Deeds Harry L. Welch Jr. with and wife, $95,000. sale price indicated by revenue stamps. to Wendy S. Poe, $15,000. HSBC Bank USA, N.A., as trustee to EH Deeds with no stamps are not listed. Pooled 1010 LP, $55,000. Providence Township James W. Hartsell and wife to Joshua C. Atwell Township Wells Fargo Financial NC 1, Inc. to DudOvercash, $137,000. Christopher G. Williams and wife to Mar- ley Denison and wife, $120,000. John T. Callicotte Jr. and wife to Thomas cus B. Shore and wife, $15,000. Jeff R. Bodenheimer to Robert M. ButterStrobl and wife, $175,000. Charles W. Clodfelter and others to worth and wife, $390,000. Robert Francis Schuberth and wife to Leonardo Lopez Cabrera and wife, $25,000. Gary L. Helms to Robert J. Walker Jr. and Daniel P. Crowe and wife, $345,000. Jeffrey Kidd and wife to Curtis Dean Roy- wife, $65,000. Nancy Moore to Walter Ray Snider, al and wife, $390,000. $87,500. Guy Stephen Patterson and wife to Ger- Rowan Township Marilyn F. Penley Crowell and husband to ald Staton and others, $59,000. G. Robert Turner III, as substitute trustee Anthony Chiccarello and wife to Randy to Sharonview Federal Credit Union, Frances Gillespie, $127,000. Jason Tuggle and wife to Julie E. Smith, Hughes and wife, $693,000. $265,000. Wells Fargo Financial NC 1 Inc. to Luther $112,500. Farmers & Merchants Bank to Hilton J. Lyerly, $26,000. China Grove Township Jonathan G. Vernon and wife to Mitchell Michael Ketchie, $276,000. Lorie N. Lucas to Stephen R. Newton and Tarheel Property Group, LLC to Tamara Lesslie and wife, $137,000. wife, $50,000. Carl Wright, as substitute trustee to Bank A. Carter, $95,500. Cathy Charlene Barbee to Tiffany N. Hilyoud E. Houston to John Allen Huston of North Carolina, of Davidson County, Pressley and husband, $92,000. and others, $25,000. Elizabeth B. Ells, as substitute trustee $153,500. Darrell J. Spells and wife to James W. DEW Holdings, LLC to John David Dalton to CitiFinancial Inc., $75,000. Hartsell and wife, $330,000. Jerry D. McCullough and wife to Brittany and wife, $275,000. James Lee Bowen, as executor to CornerBrock & Scott, PLLC, as substitute trustee Corson and other, $107,000. William Wade and others to Julia E. Clod- to BAC Home Loans Servicing, LP, $97,000. stone Church of Salisbury, Inc., $34,000. US Bank National Association, as trustee Andrew Norman Frick and wife to Jeremy felter, $110,000. to Katona Properties, LLC, $6,000. Mark A. Misenheimer and others to R. Alderman and wife, $277,500. Brock & Scott, PLLC, as substitute trustee Beneficial Mortgage Co. of NC to Robert George F. Stirewalt Sr. and others, to Wells Fargo Bank, NA, $111,500. Gibson Howle, $35,500. $1,328,000. American General Financial Services, Inc. Dewey Duke Burleson Jr. and others to Branch Banking and Trust Company to to Patrick Neil Hancock, $50,000. Jimmy D. Carver and wife, $55,000. Maria Rubiselia Toledo, $40,000. Wells Fargo Bank, N.A. to Rodney Craig Craft Development, LLC to True Homes, Janet Louise Jordan and others to Lori Pierce, $12,500. LLC, $35,000. Jordan McRorie and husband, $77,500. The Bank of New York, as trustee to JNA RBC Bank to Mark C. Ryan and wife, James E. McGee and wife to Albert C. Properties, LLC, $39,000. $45,500. Campbell and wife, $87,000. Elizabeth B. Ellls, as substitute trustee Earle Smith to Livingstone College, to Wells Fargo Bank Minnesota, NA, $179,000. Cleveland Township Richard J. Kania, as substitute trustee to $82,000. H.H. Wisecarver and others to Leonard Carolyn F. Marlow and others to Davis E. Wells Fargo Bank, N.A., $17,500. M. West and wife, $16,000. Timberlake Properties, LLC to JNA Prop- Black, $71,500. Bank of NC to Adam Davis Baird and otherties, LLC, $118,500. Franklin Township Jessie Powell to Joan Evelyn Havill and ers, $337,000. Earnest Eugene Rainey and wife to Max Secretary of Housing and Urban Dev. of husband, $185,000. Imino Lemus, $35,000. David A. Simpson, P.C., as substitute Washington, D.C. to Mahmoud Attia, Thaddeus M. Rivers and wife to Mary Eliztrustee to Deutsche Bank Trust Co., $55,500. abeth Trexler Rabon, $15,000. Charles R. Kennerly and others to Wendy Habitat For Humanity of Rowan County $132,000. Adam M. Gottsegen, as substitute trustee Pruell Hardy, $6,000. to Kesha D. Grant, $101,000. Wells Fargo Bank, NA, as trustee to Carl Jeremy R. Varner and wife to Juan L. Ro- to Premier Federal Credit Union, $29,000. Nationstar Mortgage, LLC to Ethel El- F. Weaver Jr., $83,000. driguez and wife, $90,000. Brock & Scott, PLLC, as substitute trustee Jean C. Anderson to Daniel L. Mixon and dridge, $75,000. Nathan Lynn Burgess and others to Orin to Wells Fargo Bank, NA, $170,500. wife, $172,000. Homesales, Inc. to Rupert Wade Deal and Calloway, $67,000. Branch Banking and Trust Company to wife, $37,000. Gold Hill Township Edwin L. Snuggs and wife to David HolDewey H. Moose Jr. and wife to Amanda Jane D. Welborne and husband, $680,000. Betty Bonner Steele as administratrix to man, $110,000. C. Edwards, $68,500. Ray O. Hackett and wife to John D. Bar- Richard Garrett Allen, $63,000. L. Ragan Dudley, as substitute trustee to Salisbury Township ber and wife, $175,000. Martha Vernell Lee to Teresa Mercado CRM Mid-Atlantic Properties, LLC, $32,000. Robert Thomas Williams Jr., as executor L. Ragan Dudley, as substitute trustee to and wife to NGA Properties, LLC, $40,000. Garcia, $18,000. Phillip Bradshaw and wife and others to CRM Mid-Atlantic Properties, LLC, $36,000. John J. Pfeiffer and wife to Joseph RanSubstitute Trustee Services, Inc., as sub- dall Campbell and wife, $165,000. Andrew Benson Christenbury Sr., $15,000. Rena Fay Fowler and others to Dale B. stitute trustee to SunTrust Bank, Inc., Said Jakupovic to Travis L. Martin, $125,500. Bassinger and wife, $29,500. $130,000. Carlos Randolph Emory and wife to B.E. Rena Fay Fowler to Lucas W. Merrell, Leigh Ammons Grimes, as executrix and Pre Foreclosure Services/Management others to Robert William Clark and wife, $102,000. Andrew J. Foy and wife to Robert Alan Corp., $50,000. $106,000. B.E. Pre Foreclosure Services/ManageParnell and others, $195,000. Historic Salisbury Foundation Inc. to Acey ment Corp. to David L. Kamp and others, L. Worthy and wife, $208,000. $65,000. Douglas H. Jones and wife to Innes Street Litaker Township Vincent C. Benedetto and wife to Benedet- Holdings, LLC, $150,000. Charles Terry Funderburk and wife to to Family Limited Partnership, $390,000. Knight Custom Construction, LLC to Frank Brandon M. Rogers and wife, $252,500. Jeffrey J. Goebel, as substitute trustee E. Whisnant and wife, $157,000. Verlen Acres, LLC to Shady Pines of to NexBank, SSB, $390,000. Dorothy B. Truesdale to John W. Hughes, Rowan, LLC, $10,000. State Employee Credit Union to Douglas $138,500. M. Lesley, $123,000. Kelly Deanne Batchelor to Iris H. DaughLocke Township Carolyn Trexler Lyerly and others to Mark try, $80,000. Yorleny Rivera Shoff and husband to Martin Luther Kimble and wife to Martin Harold W. Deaver Jr. and wife, $201,000. A. Misenheimer and wife, $237,000. Mark A. Lucas to Jason McManus, Luther Kimble and wife and others, $1,500. Weatherstone Land Group, LLC to J. Je$74,000. sus Rodriguez-Vega and others, $7,000. Michael Koehler to Mark Lucas, $77,000. Steele Township Weatherstone Land Group, LLC to J. JeStarburst Properties, LLC to Starburstsus Rodriguez-Vega and other, $7,000. Tom E. Smith and wife to Johnny C. Nebuli, LLC, $327,000. Moore, $508,500. Thomas D. Schwalm and wife to Alison Dewey R. Turman and wife to Michael E. Morgan Township Slusarz, $210,500. Michael P. Horaz and wife to Christopher Louise Box, $115,000. The Bank of New York Mellon to Ronald Ruth P. Gaynor to Tina Miller Musselwhite, Elliott, $50,000. $126,000. Franklin T. McSwain and wife to Clifton P. Campbell, $126,000. CRM Mid-Atlantic Properties, LLC to Wilbur Lee Dement Jr. and wife, $3,500.
Mt. Ulla Township
SECONDFRONT
The
SALISBURY POST
Search yields marijuana, firearms The Salisbury Police Narcotics Unit served a narcotics search warrant at 425 S. Church St. Wednesday and found 232 grams of marijuana, a stolen Springfield .40 caliber handgun, a Lorcin .380 handgun, a Keltic .380 handgun and two sets of digital scales. Malcolm Toomer, 18, was arrested and charged with possession with intent to sell and deliver a schedule VI controlled substance and possession of a stolen firearm. He was jailed under a $10,000 seM. TOOMER cured bond. Kevin Toomer, 22, of the same address, was arrested for an outstanding order for arrest and placed in jail under a $750 secured bond. A third person, Kyheem Martinez, 17, of 2660 Grubb Ferry Road, Spencer, was arrested for an outstanding warrant for unauthorized use of a motor vehicle and was released on a written promise. K. TOOMER Salisbury Police Chief Rory Collins said the search warrant resulted from an investigation by the drug unit. Information had come from several sources that drug activity was taking place at the residence. “The Salisbury Police Department takes this type of information and these matters very seriously,” Collins said. “We want to do all we MARTINEZ can to help improve the quality of life for those who live within our community. “Taking a hard, zero-tolerance approach to drug activity is one way that we will do just that,” he said.
BY SHELLEY SMITH ssmith@salisburypost.com
A Statesville man was found asleep, vodka bottle in hand, with his truck running on the side of Third Creek Church Road in Cleveland around 5 p.m. Tuesday. Authorities say the man was unresponsive and had to be taken to Rowan Regional Medical Center for a blood alcohol test. According to the Rowan County Sheriff’s Office, a volunteer firefighter called the office Tuesday afternoon to let deputies know of a vehicle on the side of the road, running, with two people asleep inside. When deputies arrived, they saw two men in the truck, asleep, with the driver of the truck, 40-year-old Steven Ray Dalton, of Statesville, DALTON behind the wheel with an open bottle of vodka in his hand. The deputy was able to take pictures of Dalton asleep behind the wheel without waking him up, which will be used as evidence, authorities reported. “Certainly that’s good evidence,” Capt. John Sifford said. Two open bottles of alcohol were also seized as evidence, and the truck was towed. Dalton was taken to Rowan Regional, and then to the magistrate’s office where he was charged with driving while impaired, driving while license revoked, driving while consuming alcohol and possession of an open container. He was given a $1,500 secured bond. The Sheriff’s Office said it is investigating the possibility of a new charge — habitual driving while impaired. There was no information available about the other person in the truck.
Overdose leads to felony charges BY SHELLEY SMITH ssmith@salisburypost.com
Two people are in jail after an accidental overdose got in the way of their escape after being caught entering a Landis home, the Rowan County Sheriff’s Office reported Thursday. On Tuesday around 7:15 p.m., deputies responded to a break-in on Rice Street in Landis. Marvin Kendall, who reported the break-in, told deputies he was there taking care of a sick friend. While the friend was running errands, Kendall walked up the road to check on a family member. When Kendall returned, he said he saw a truck
See CHARGES, 4A
3A
Cleveland home damaged by fire
SUBmITTeD PhOTO BY DeNISe BAkeR
Neighbor Denise Baker took this photo of the smoke coming from 145 Rocky Point. B Y S HELLEY S MITH
Man found passed out behind wheel of truck
FRIDAY January 7, 2011
ssmith@salisburypost.com
CLEVELAND — A Thursday afternoon fire at a mobile home at 145 Rocky Point is under investigation. Curtis Hayes, owner of the home, is being treated at Rowan Regional Medical Center for a sudden illness and was not home at the time of the fire. Neighbors say Hayes’ wife, Cheryl, left the home minutes before they saw the smoke. “People say she had just left when smoke started rolling out,” Hayes’ mother Patsy said. Cheryl Hayes was at the hospital when firefighters responded and was not available for comment. Next-door neighbor Roger Gallo called 911 to report the smoke. “I saw a lot of smoke, came over and popped the door open,
Shelley Smith/SALISBURY POST
The siding on mobile home melted in the flames. and smoke started rolling,” Gallo said. Cleveland, Scotch Irish, Locke, Wayside and Rowan-
Iredell fire departments responded, as well as the Rowan Rescue Squad. Cleveland Assistant Fire
Chief Greg Summitt, who was having trouble communicating with the firefighters inside the house, decided to step onto what he thought was a concrete block beside the home to yell at the firefighters on the porch. The concrete turned out to be a large and deep fish pond that Summitt fell into through a sheet of ice covering the pond. The water soaked him from head to toe and the ice cut his hands and face. He also lost his radio. Firefighters attempted to empty most of the fish pond to retrieve the radio, but the water would not drain. They decided to use a chain saw to cut the wood beams supporting the pond, allowing more water to flow into the yard. The Rowan County Fire Marshal’s Office is investigating.
SUV, tractor-trailer collide on Stokes Ferry Road A Salisbury woman was sent to Rowan Regional Medical Center with very minor injuries Thursday afternoon after Highway Patrol Troopers and witnesses say she pulled out in front of a tractor-trailer on Stokes Ferry Road, and was hit. According to Chris Misenheimer, who was driving his tractor-trailer east on Stokes Ferry Road, the driver of the white Suzuki SUV, Wendy Kluttz, was stopped at the stop sign at the intersection of Agner Road before pulling out in front of him. “I wasn’t expecting her to ever attempt to come out,” Misenheimer said. A witness, Jon Davis, was stopped at the intersection at St. Peters Church Road, and saw the accident. Shelley Smith/SALISBURY POST “When her front hit him, the An employee of Crawford’s Garage loads the Suzuki SUV onto a trailer to be towed away. The back swung around,” he said. bumper and a road sign lay in the grass next to Stokes Ferry Road. Davis checked on Kluttz, prying open the door of her SUV to her fault.” Liberty Fire Department direct- Rogers with the Highway Patrol make sure she was OK. Kluttz was cited for failure ed traffic as the front left tire investigated. Rowan EMS also “She said she had a was replaced on the tractor- responded, taking Kluttz to the headache,” Davis said. “She got to yield for a stop sign. Firefighters with the West trailer. Troopers Motsinger and hospital. out saying sorry and that it was
S47496
4A • FRIDAY, JANUARY 7, 2011
StateBriefs
Blanche J. B. Lambert
NC businesses, workers get primer before NHL game
Judge allows lawsuit against Greensboro police
NC SBI touts DNA database as crime-fighting tool
RALEIGH (AP) — Wake Technical Community College wants to make sure business owners and hospitality workers put on Raleigh’s best face for the NHL All-Star Weekend. The school is offering a special presentation of its award-winning Customer Service training at the RBC Center on Thursday. The All-Star Customer Service Class is presented in partnership with the Greater Raleigh Convention and Visitors’ Bureau. It is open to all front-line hospitality staff, including managers and employees of hotels and restaurants, as well as small business owners and retail salespeople. The goal is to help the business owners and hospitality workers sharpen their customer service skills. The NHL’s big weekend in Raleigh is scheduled for Jan. 28-30.
GREENSBORO (AP) — A federal judge is allowing two lawsuits by more than three dozen black officers to continue against the Greensboro Police Department. The News & Record of Greensboro reported Thursday that Judge Thomas Schroeder dismissed charges of civil conspiracy and retaliation in the lawsuits, but left intact an overall charge of discrimination. The black police officers say they were not treated equally and their supervisors created a hostile working environment. The officers say former Police Chief David Wray and his deputy used a special unit in the department to target black officers for investigation. Wray left the department in 2006.
RALEIGH (AP) — The North Carolina State Bureau of Investigation is touting the effectiveness of its crime-fighting DNA database a month before a significant expansion. Attorney General Roy Cooper says the database recorded 420 “hits” in 2010, an all-time high. A “hit” occurs when crime scene evidence matches the DNA profile of a convicted felon. Starting Feb. 1, the database will get larger. Police will be allowed to collect DNA samples from people arrested for certain serious felonies and misdemeanors, rather than from convicted felons only. Cooper says the expanded collection will help solve more crimes than ever. But civil liberties groups say collecting DNA from people who haven’t been convicted raises troubling Constitutional questions.
NC-based hospital group combs data for best result CHARLOTTE (AP) — A North Carolina-based alliance of 2,400 hospitals is taking early steps to link the nation’s hospitals into a network able to pinpoint the most effective treatments. The Charlotte-based Premier healthcare alliance and IBM Corp. are announcing Thursday that they’re building an information system allowing hospitals to share and analyze data safely. The country’s new health care reform law is pushing hospitals to use and share medical data to cut excess treatments, medical errors and hospital readmissions. The Premier alliance includes 40 percent of the nation’s hospitals. It was created four decades ago to help hospitals save money by buying drugs and supplies as a group. Here is contact information for area members of Congress:
U.S. Senate • Sen. Kay Hagan (D) 521 Dirksen Senate Office Bldg. Washington, D.C. 20510 202-224-6342
• Sen. Richard Burr (R) 217 Russell Senate Office Bldg. Washington, D.C. 20510-3306 202-224-3154
U.S. House • Rep. Howard Coble (R)
Furniture retailer kept money, stays in prison HIGH POINT (AP) — A former North Carolina furniture store owner is staying in prison after judges decided he chose to live well instead of repaying customers he cheated. The High Point Enterprise reported Thursday that 48-year-old Kenneth Lee Cornelison will stay behind bars on a sentence running until 2015. Cornelison was convicted in 2003 of taking more than $300,000 from nearly 160 customers of his High Point store who paid in advance for furniture they never received. Cornelison was freed on probation on condition that he make monthly payments to repay his customers. The state Court of Appeals ruled this week that Cornelison increased his personal spending while falling behind in restitution payments.
N.C. District 6 2468 Rayburn House Office Bldg. Washington, D.C. 20515-3316 202-225-3065
• Rep. Larry Kissell (D) N.C. District 8 512 Cannon House Office Bldg. Washington, D.C. 20515-3308 202-225-3715 • Rep. Mel Watt (D) N.C. District 12 2304 Rayburn House Office Bldg. Washington, D.C. 20515-3312 202-225-1510
Amtrak schedule altered for track work RALEIGH – Passengers on North Carolina’s Amtrak Piedmont and Carolinian trains that travel between Raleigh and Charlotte will experience a smoother ride and better ontime reliability this spring after one of the rail corridor’s largest track and bridge reconditioning projects is completed. While work is underway, there will be temporary service suspensions and adjusted service schedules. Passengers should plan their travel accordingly. On Monday, Feb. 14, Norfolk Southern Railway will begin making track, signal and bridge improvements to the Raleigh to Charlotte rail corridor. Crews will perform the work Monday through Thursday each week, with completion scheduled for Thursday, April 21. To accommodate the work, the Piedmont mid-day service (Trains 74 and 75) will be temporarily suspended Monday through Thursday, from Feb. 14 to April 21. No alternate transportation will be provided. Friday, Saturday and Sunday service will operate on adjusted schedules
during this time. The Piedmont morning and evening service (Trains 73 and 76) and the Carolinian morning and evening service (Trains 79 and 80) will run on adjusted schedules from Feb. 14 to April 21. The temporary service suspensions and schedule adjustments are necessary to complete the project in just 10 weeks. Without the accelerated work schedule, the project would last through the summer and severely impact all passenger train operations during peak travel months. Passengers should visit to download adjusted schedules for both the Piedmont and Carolinian trains or call 1-800BYTRAIN for information. North Carolina’s Amtrak Piedmont and Carolinian trains are sponsored by the N.C Department of Transportation. gov/, and paid for with state funding and passenger fares. Reservations are required. Passengers are encouraged to book their tickets early for the best fares.
CHARGES
took off, spinning out of the driveway and over a ditch, and headed toward Landis, Kendall told officers. Kendall described the suspects: an older, blonde white female and a younger male — and their truck, a black or red Ford Ranger. The homeowner returned and found several medications missing, the report said. While deputies were questioning Kendall and the homeowner, they got a call of an accidental overdose from the fire department. When a deputy arrived at 1745 N.C. 153 N., he recognized the overdose victim as 23-year-old Dustin Sloop; the deputy saw an older woman with blonde hair inside the home. Parked out back was a Ford Ranger. When EMS arrived, Sloop refused to cooperate. As he was frisked for weapons, a pill bottle belonging to the
FROM 3a in the driveway of the friend’s home, with a blonde older woman behind the wheel. A younger man came through the front door with a Michael Jordan collector’s plate in his hands. Kendall told authorities he asked the man what he was doing. The suspect said the homeowner told him he could have the plate. Kendall asked the man to wait until the owner returned, and the man put the plate back and tried to leave. Kendall then asked him if he’d wait until the homeowner returned so he could make sure nothing else was missing. The suspect said he would wait, but wanted to tell the woman in the truck what was going on. When the man entered the truck, the driver
SALISBURY POST
A R E A / S TAT E / O B I T U A R I E S
Students can find teaching materials on iTunes RALEIGH (AP) — A wealth of curriculum and professional development material for teachers and students in North Carolina can now be found in a familiar place: iTunes. The state education department has worked with other agencies around the state to create a section of the iTunes store offering free downloads of educational materials. The North Carolina Department of Public Instruction and Partners section of the popular online store includes audio and video files designed to help teachers, students and parents. It includes everything from curriculum materials to lessons posted by the state Museum of History about North Carolina’s past.
Rowan County Literacy Council to hold Tutor Training Workshop The Rowan County Literacy Council will hold a four-session tutor training workshop starting on Wednesday, Jan. 19, January 24 and 26 from 5:30 to 9 p.m. and January 29 from 8:30 a.m. to 1 p.m. The registration fee for these three
sessions is $20 to cover the cost of materials. In order to be certified as a tutor, participants must attend all four sessions. Please make your reservations for the Jan. 19 orientation as soon as possible by calling the literacy office at 704-216-8266 or by emailing rclc@rowancounReservation tync.gov. deadline is Friday, Jan. 14. Rowan County Literacy Council is a volunteer organization and a United Way Agency. Visit the literacy website at.
Suspect in Winston-Salem robberies arrested in Spencer SPENCER — Authorities have arrested a man who is a suspect in two WinstonSalem armed robberies. Sean Wendell Harrison, 42, was arrested Thursday at 1007 Elizabeth Ave. by Rowan County Sheriff’s Office deputies and officers with the Spencer Police Department, a press release said. Harrison’s listed address is in Winston-Salem. It wasn’t clear Thursday why he was in Spencer. Harrison was charged with two counts of armed
robbery with a dangerous weapon and transferred to the Forsyth County jail, where he was placed under a $100,000 bond. Television station WGHP in Winston-Salem reported that Harrison is one of two suspects in the armed robberies. The other remained at large Thursday evening. The robbery and attempted robbery of two WinstonSalem businesses happened little more than an hour apart the evening of Dec. 18, WGHP reported.
Tourism development committee to meet.
Rice Street homeowner was found in his boot. Sloop told deputies he had no idea whose bottle it was or how it got there, but deputies arrested him, the report said. Kendall was transported to the scene where he identified Sloop as the man who took the plate, and the woman, Gail Ann Jaycox, 52, as the driver of the SLOOP truck. Bags on the porch of the home on N.C. 153, which Sloop asked someone inside to bring to him, contained five hypoderJAYCOX mic needles,
two pre-filled syringes of lidocaine and naloxone and an IV bag of dopamine, deputies reported. Sloop, of 555 Red Leaf Lane, China Grove, was charged with felony breaking and entering and felony larceny, and given a $20,000 secured bond. He refused medical treatment. Jaycox, of 1745 N.C. 153 N., China Grove, was also charged with felony breaking and entering and felony larceny, and given a $20,000 secured bond. Deputies contacted the emergency rooms of Rowan Regional Medical Center and NorthEast Medical Center to see if the needles or IV bag were missing. Officials at NorthEast Medical Center said they had recently filed a report with the Concord Police Department for the missing dopamine and syringes.
KANNAPOLIS — Blanche Julia Baker Lambert, 82, died Thursday, Jan. 6, 2011 at the Bob & Carolyn Tucker Hospice House, Kannapolis, where she had been for over a month. She was born July 29, 1928 in Cabarrus County, the daughter of the late John Henry Baker and Blanche Viola Ward Hipp. She was educated in the Cabarrus County Schools. Blanche was employed with the former Cannon Mills Company, Plt. # 1, #7 Weave Room after many years of service until her retirement. She was a member of Landis Baptist Church, Landis, where she sang in the choir, a member of the Ladies Group, and helped in any way that she could in the church. She is fondly remembered for her sitting with sick people and taking care of the elderly. In addition to her parents, she is preceded in death by her husband, Noah E. Lambert; a son, Roger Dale Tutterow; a grandson, Michael Dale Tutterow; three brothers, Robert Lomax, Jack Baker, and Bobby Baker; one sister, Juanita Baker; and a son-in-law, Doug Hagler. Survivors include two sons, Randy Darnell Tutterrow and James Edward Lambert; four daughters, Kathy Almond and husband Gary, Betty Jean Welch and husband Donald, Hilda Smith, and Janice Faye Hagler; one brother, Jim Baker; 21 grandchildren; and 31 great-grandchildren. Funeral Service: 1 p.m. Saturday, Jan. 8, 2011 at Landis Baptist Church, Landis, officiated by the Rev. Billy Honeycutt and Rev. Jeremy Morton. Burial will follow at Carolina Memorial Park, Kannapolis. Visitation: The family will receive friends from 6-8 p.m. Friday, Jan. 7, 2011 at Whitley's Funeral Home. At other times, the family will be at the home of daughter, Kathy Almond, 6727 Bealgray Road. Memorials: Memorials may be made to Hospice & Palliative Care of Cabarrus County, 5003 Hospice Lane, Kannapolis, NC 28081. Online condolences may be left at.
William Alexander, Jr.,
Sando Kimba
— Mr. SALISBURY William "Duke" Alexander, Jr., age 52 of 420 Boundary St., ES, died, Wednesday, Jan. 5, 2011 at Brian Center. Born in Rowan County Feb. 23, 1958, he was the son of the late and William Lizzie Barrett Alexander, Sr. He was a graduate of Salisbury High School, Livingstone College, where is received a Bachelor of Arts degree, and Xavier University, where he earned a Masters of Education. He was last employed in Shreveport, La. School system, and was a member of Thomas Street Church of Christ. Those who will forever cherish his memory are a daughter, Giana Alexander, of Salisbury; brother, Amos Blakeney, of Anchorage, Alaska; sisters, Carolyn Logan, of East Spencer, Linda Alexander, of Salisbury, Shaenita Barrett, of Winston-Salem; and an aunt, Truelove Johnson, of Winston-Salem. Visitation will be Saturday, Jan. 8, at 3 p.m. Funeral 4 p.m. at Thomas Street Church of Christ, brother William Latten, Pastor officiating. At other times, the family will at the home of his sister, Carolyn Logan, 227 Hall St., East Spencer. Hairston Funeral Home, Inc., is serving the family. Online condolences may be sent to.
SALISBURY — Ms. Sando Kimba, 32, of 118 Martin Luther King Blvd., Salisbury, passed away Dec. 10, 2010, at Rowan Regional Medical Center. She was born June 16, 1978, in Monrovia, Liberia, Robert to Gbessie Kima and the late Sando Freeman. She was educated in the schools of Monrovia. Previously employed with the Brian Nursing Center, Sando was a member of Rowan International Chuch. Survivors are are her children, Miatta Dassin of Canada, Johnson Freeman of Monrovia, Liberia, Salimutua Kimba, Ishmael Kaijuway and Varney Fahnbulleh of the United States; mother, Sando Free and stepfather, Sansee Dominic Kemokai, of Monrovia, Liberia; sisters, Salimutuu Kemokai Reeves and Maitta Kemokai; and a host of relatives and friends in the United States. Visitation: 6-10 p.m. Friday, Jan. 7, 2011 at Rowan International Church. Funeral: 10 a.m. Saturday, Jan. 8, 2011 at Rowan International Fellowship Church with the Pastor Jacob Doe, officiating. Burial will be in Oakwood Cemetery. Services entrusted to Hairston Funeral Home, Inc.
Wayne Shanks COOLEEMEE — Wayne Shanks, 53, died Tuesday, Jan. 4, 2011. He is survived by his mother, Thelma Viola Davidson of Cooleemee; two daughters, Angela S. (Cavin) Caldwell of Statesville and Tameka S. (Jaime) Moreles of Taylorsville; two brothers Kenneth Shanks of Cooleemee, and Charles Neely of Cleveland; one sister, Rochella Shanks of Cooleemee; and four grandchildren. Contact family at 150 Oak Creek Rd., Statesville, and 220 Jerusalem Ave., Cooleemee. Funeral Service & Visitation: 4 p.m. Sunday, Jan. 9, 2011, at Graham Funeral Home. Family will receive friends at the funeral home one hour before the service. Graham Funeral Home is assisting the Shanks family.
Express your feelings. Leave a message in our online Obituary Guest Book at
Mildred Johnson Correction SALISBURY — Mildred Johnson, 91, of 1310 Old Wilkesboro Rd., passed away Monday, Jan. 3, 2011, at her residence. She was also survived by her granddaughter, Marian Withers, who was reared in the home. Her name was omitted from an earlier obituary. Noble & Kelsey Funeral Home is serving the family.
Mr. Alvin Leroy Knoll 1:30 PM Saturday Summersett Memorial Ch. Visitation: 6-8:00 PM Friday
SALISBURY POST
FRIDAY, JANUARY 7, 2011 • 5A
N AT I O N
Meet the new boss: Daley is Obama’s chief of staff WASHINGTON (AP) — Overhauling his team at the top, President Barack Obama on Thursday named banker and seasoned political fighter William Daley as his new chief of staff, hoping to rejuvenate both a White House storming into re-election mode and an economy still gasping for help.elected.. Not so with Daley. U.S..”
aSSOCiaTED PRESS
President Barack Obama applauds as his new White House Chief of Staff as William Daley makes a statement in the East Room of the White House on Thursday in Washington.
GOP strikes early in global warming battlekilling. A bill that would have placed a limit on heat-trapping gases died in the Senate last year, after it passed the then Democratic-led House. Boxer said there are no plans to pursue another one because there are not enough votes.
BELK.COM
price breaks
shop Friday-Monday, Jan. 7-10
new reductions just taken
look for these great savings & more plus our storewide clearance
FRIDAY-MONDAY, JANUARY 7-10 with your Belk Rewards Card
50 R128395
% off
Troyer Medical Eric Troyer, MD 107 South Central Ave., Landis, NC. (704) 855-2101 Providing comprehensive medical care to patients of all ages
Kim Rogers® sweaters for misses, petites & today’s woman Orig. 36.00-58.00 Sale 18.00-29.00
%
EXTRA
25
OFF
Imported Merchandise not in all stores
clearance purchases* storewide
Coupon excluded
20% OFF home and shoes
20% OFF clearance purchases* storewide
OR with this shopping pass
15% OFF home and shoes
50-60%off Izod and Chaps fleece, sweaters & long sleeve knits Orig. 44.00-79.50 Sale 21.99-39.75
Walk-ins will always be accommodated and we offer extended and Saturday hours. Cosmetic services - microdermabrasion, permanent hair removal and facial rejuvenation (Winter Sale rates in effect)
*Only excludes cosmetics/fragrances, Brighton in dept. 276, fashion accessories, small leather goods, handbags, hosiery, junior denim, Belk & Co. Fine Jewelers and all lease departments. Not valid on prior purchases or special orders. Cannot be redeemed for cash, credit or refund, used in combination with any other discount or coupon offer. Valid January 7-10, 2011.
43833142
40-% 50off
Excludes Everyday Value Also in Big & Tall sizes at slightly higher prices. Imported
Individualized weight loss programs
Coupon excluded
Quality, courteous and prompt medical care when you need us, not 3 days later
Blankets and comforters from Home Accents Wide assortment of colors and styles. Full/queen or king Orig. 30.00-100.00 Sale 15.00-60.00
Many (more) insurances are accepted. Star Trek costume and prop museum on site
Imported
Coupon excluded
CURRENTLY ACCEPTING APPLICATIONS FOR PART-TIME PHYSICIAN/PA/NP. R128330
For more information or to make an appointment, please call us at 704-855-2101.
R128411
FREEshipping Find us on Facebook at facebook.com/belk
when you shop BELK.COM Jan. 7-9 with purchase of $75 or more
TEXT-N-SAVE Text BREAK3 to BELK1 (23551) for coupon
6A • FRIDAY, JANUARY 7, 2011
SALISBURY POST
N AT I O N
Findings boost chance of criminal charges from oil spill usual-
Jail calls ended for suspects in Dugard kidnapping PLACERVILLE, Calif. (AP) — A Northern California couple charged with kidnapping Jaycee Dugard and holding her captive for 18 years temporarily lost the right to talk to each other on the telephone Thursday because jail officials suspect they have been using the calls to coordinate their testimony. El Dorado County Superior Court Judge Douglas Phimister suspended the monthly phone conversations he had granted Phillip and Nancy Garrido in May. The judge acted on a request by a lawyer for the Sheriff’s Department who said the two inmates were abusing the privilege. Outside court, County Counsel Edward Knapp said he did not yet have details on what the couple discussed during the five-minute chats that jail officials have been recording and reviewing.
The judge instructed Knapp to submit written evidence next week explaining why the calls should be discontinued permanently. “Conversations between defendants in the same case are very problematical. We generally don’t allow it,” Knapp told reporters. “They are able to conform their testimony, to create false testimony in general.” The Garridos have been in custody since August 2009, when they were arrested in connection with the kidnapping of Dugard, then 11, outside her South Lake Tahoe home in 1991. Prosecutors say Dugard and her two daughters fathered by Phillip Garrido were hidden in a compound of sheds and tents in the backyard of the couple’s Antioch home. Nancy Garrido has pleaded not guilty. Criminal proceedings against Phillip Garrido
have been put on hold because his public defender has expressed concern about his mental state. He has undergone three court-ordered psychiatric evaluations, and a hearing on his competency to stand trial is scheduled to start Feb. 28. El Dorado County District Attorney Vern Pierson said he wants a jury to reach a verdict on the competency issue instead of having a judge decide the matter. Phillip Garrido’s lawyer, Susan Gellman, said she may seek to have the hearing moved from El Dorado County because it has attracted so much interest and publicity. Phimister said he was still considering a request from The Associated Press and other media organizations to unseal the transcripts from the grand jury that indicted the Garridos largely based on Dugard’s testimony.
Payment Plan with CareCredit
Mike Morton Dentistry 201 Security Street, Kannapolis, NC 28083 info@mikemortondentistry.com 704/938-3189
JERRY’S SHELL SERVICE Jerry Alligood Yvonne Alligood Todd Alligood Michael Alligood
Kluttz, Reamer, Hayes, Randolph, Adkins & Carter, LLP
Pam Ketner Allen Vasser John Persinger Randall Clary
John L. Holshouser, Jr.
Todd Retdorfels Justin Wolfe
A UNC Law graduate, John is returning to private practice after his recent service as Superior Court Judge. He will engage in general civil practice with emphasis on damage negotiation and litigation. He welcomes the opportunity to be of service.
Waeppreciate your ess! busin
Tyou’ll he only law firm ever need
Proudly Serving You Since 1971
(704) 636-3803 600 Jake Alexander Blvd. W. Salisbury, NC Mon-Sat 7am til 7pm
129 N. Main Street, Salisbury • 704-636-7100
R128574, Fla. • Bishop Eddie Long of New Birth Missionary Baptist Church and Bishop Eddie Long Ministries of Lithonia, Ga.; Long was recently sued by four young men who claim he coerced them into sexual relationships. The bishop has denied the allegations. Meyer released a statement Thursday affirming her pledge of financial transparency. Hinn said in a statement that his ministry’s experience with the Finance Committee “has caused us to renew our commitment to always honor our partners’ sacrificial giving.” Long said he was “relieved” that the inquiry was done and said New Birth has always operated with integrity. Representatives for the other ministries did not immediately respond to calls and e-mails seeking comment. Grassley said he hoped the review would lead to an update in tax rules governing religious groups so abuses don’t occur. The Evangelical Council for Financial Accountability, an independent accrediting group for churches and religious nonprofits, plans to create a national commission in response to the Grassley report to lead a review on accountability and policy.
• Tooth Colored Crowns start at $495 • Dental Implants for $695 • Zoom Whitening $300 • Cleanings, Fillings and Extractions
from everyone at
IMPRESSIVE Cars Affordable Prices 03 BUICK CENTURY
05 NISSAN ALTIMA 2.5S 4Dr, 4Cyl, P/W, P/L, New Tires K3669A
V6, Leather, Very Clean, 76K Miles K3700C
7,990
$
5,990
$
07 FORD EXPEDITION EDDIE BAUER
09 TOYOTA COROLLA LE Auto, CD, P/W, P/L, Very Clean K3747
2WD, Leather, 3rd Row Seat, Only 51K Miles K3716A
10,990
$
22,990
$
Come In For A FREE Appraisal We will buy your vehicle whether it is paid for or not.
941 S. Cannon Blvd. • Exit 58 Off I-85 • Kannapolis R129069
cal organizations worried that Grassley’s inquiry could lead to changes in tax rules for all religious nonprofits, so the groups protested. The flagship magazine of centrist evangelicals, Christianity Today, editorialized in 2008 that the Grassley investigation amounted to an “oversight overstep” that risked delving improperly into theology. The Alliance Defense Fund, a religious liberty legal group founded by James Dobson of Focus on the Family and other influential evangelicals, protested. The National Religious Broadcasters, a trade association, said the questions Grassley asked were too broad. All six of the targeted televangelists insisted they comply with tax regulations for religious nonprofits. Two — Joyce Meyer Ministries based in Missouri and Benny Hinn Ministries based in Irving, Texas — told Grassley they have made changes in how they govern their ministries or set compensation. But four of the televangelists would not provide full information to Grassley. Some pastors questioned whether Grassley had the authority to conduct the investigation. Others accused him of violating their religious freedom. Grassley’s staff said in the report that they did not issue subpoenas to further the investigation because witnesses feared retaliation if they spoke out publicly and the Finance Committee did not have the time or resources to enforce the subpoenas. The four ministries that refused to provide full information are: • Kenneth and Gloria
pital chain — is thriving despite paying a record $1.7 billion fine for massive Medicare fraud involving guilty pleas to 14 felonies that occurred when the company was known as Columbia/HCA..
Need Dental Work?
Merry Christmas and Happy New Year
Televangelists escape penalty in Senate inquiry NEW YORK (AP) —owned. Grassley, a Republican, began the investigation in November 2007 and released the report at the end of his tenure as the ranking member of the Senate Finance Committee. The senator will remain on the Finance Committee, but will become the ranking member of the Judiciary Committee. The six televangelists targeted in the investigation preach some form of the prosperity gospel, which teaches that God wants to bless the faithful with earthly riches. Ministers in this tradition often hold up their own wealth as evidence that the teaching works. Many conservative Christians condemn the prosperity gospel and consider the televangelists an embarrassment. Still, leading evangeli-
ly hos-
R122513related economic losses over three years. That could translate into a more than $45 billion criminal fine.
R128701. Criminal charges would cause fines to soar. Under the Clean Water
R126628
NEW ORLEANS (AP) — Months of investigation by a presidential commission and other panels reinforce the likelihood that companies involved in the Gulf oil spill will be slapped with criminal charges that could add tens of billions of dollars
704/933-1077 *All prices plus tag, tax & $389 admin fee
PRICES GOOD
Other GREAT deals at THRU 01-14-11
THE BEST DEALS ARE UNDER THE SIGN ON HWY 29!
SALISBURY POST
FRIDAY, JANUARY 7, 2011 • 7A
N AT I O N
SEC rule likely to trigger Facebook IPO in 2012 sued’s’s own partners.
Disturbing video shows attacks on disabled victims “He then hoisted himself onto the floor, scooted across the floor, out of the doorway and disappeared from the camera’s view,�. “After one horrendous assault, one of the victims was picked up and thrown back into a wheelchair,� Sgt. Dan Scott said. Detectives hope that by going public with the case, someone will recognize a suspect or a location where an assault took place. They also
Initial data show Marine suicides declined in 2010 SAN DIEGO (AP) — in March. Martin said it is difficult to pinpoint an exact reason for the drop but he said prevention efforts appear to be changing the mindset of troops in a branch of the military where toughness and self-reliance have been especially prized for generations. “We’re not sure why the drop has happened,� Martin told The Associated Press on
Thursday. “We do know that Marine attitudes toward mental fitness, toward seeking help, are starting to change and that may be related to the drop.�’s. “Not as many Marines before thought it was safe to go seek help,� Martin said. “Now they are realizing it is not only safe as far as their career goes, it is also my duty as a Marine to stay fit not only physically but mentally.�. “We’re absolutely not satisfied with 37 suicides,� he said. “We’re glad for the drop but there is nothing positive about having 37 deaths. We’re headed in the right direction but (this means) keep working harder.�
UP TO 500 in FEDERAL TAX CREDITS on QUALIFYING SYSTEMS PROGRAM ENDS DEC. 31, 2011
90 DAYS UP TO 12 MONTHS
r nte Wi le
Same Day Service On Repairs & Relines Repairs $50 & up Relines $175 per Denture
WINDOWS
Sa
All Styles • Doors 100 Styles & Colors
FACTORY DIRECT DISCOUNTS
J.A. FISHER
A Specialty Contractor Since 1979 With Over 7000 Completed Jobs
704-788-3217
Salisbury
Dr. B. D. Smith, General Dentistry
Kannapolis
DePompa’s
Taste the Best Kept Secret in Kannapolis
C O M F O RTA B L E F O O D S
Restaurant • Catering • Frozen EntrÊes to go
Tuesday
5-8:30
Wednesday
5-8:30
Mexican Buffet
Pizza & Pasta Buffet
Join the fiesta with our authentic mexican buffet... just $6.99
Try a great variety of homemade pizza, pastas, salad bar & dessert... just $6.99! (1/2 price for kids under 6)
Thursday
5-8:30
Get Your Country Fixin’ Buffet with our southern style country buffet! Famous chicken pot pies and other favorites...just $7.99
Buy One Buffet - Get One 1/2 Off!!
Dentures $475 ea.; $950 set Partials $495 & up Extractions $150 & up Most Insurance Accepted Now Accepting Medicaid
CreTax dit
“The Best Insulated�
SAME AS CASH FINANCING with approved credit’s growth has been, just how much the business is worth remains a hotly debated topic. The $50 billion market value implied in Goldman Sachs’ investment is 25 times higher than the $2 billion in revenue that analysts believe the company had last year. Google, the Internet’s biggest moneymaker so far, ended Thursday with a market value of $196 billion, about seven times its annual revenue.
with this coupon
215 West A Street (on the corner of West A St & Oak Ave in Cannon Village)
704.932.1555 Mon 11-2, Tues-Thurs 11-8:30, Fri & Sat 11-9
1905 N. Cannon Blvd., Kannapolis
(704) 938-6136
Howard Brown Agency Inc. COMPLETE INSURANCE IS OUR SPECIALTY
New Year’s Savings! MARCH MATTRESS SALE! Tempur-Pedic In-Stock & Floor Samples 20% OFF Last Year’s Mattress Models! 25% OFF Mattress Floor Samples!
10-15% OFF!
No Additional Charge for Mattress Foundations
Since 1987
704-638-0610
• Auto • Home • Life • Motorcycles • Boats • RV’s • Business • Health • Medicare Supplements • Long Term Health Care
Night Dimensions Park PlaceSet Mattress
$ Queen $ Set ...................... $ $ 279
Orange Full Euro TopQueen Twin
Call For FREE & Fast Phone Quotes
1121 Old Concord Rd. Salisbury
Includes 2 FREE Pillows!
149
NEW SHIPMENT
S47811
189
199
Sensa Adjustable Beds Starting at
$
999
Park Place Mattress Set Plush, Firm, & Super $ QueenTop Plush or Firm.... Pillow Queen Set
399
Park PlaceBeautyrest Red Rose Simmons Plush,Mattress Firm, or PlushSet Pillowtop
699
$ Queen Pillowtop.... Queen Set ..........$299
Heaters
Have Just Arrived!
705 W. Ryder Ave. Landis, NC 28088 Lic. #: 19627
704-857-5684 R129064
3900 Twin/Twin Albany Futon Discovery Panel Bed Spice Collection Bedroom Group Metal Bunkbed $199 $ $
169 15% OFF
SUPPLIES ARE LIMITED
of Rockwell
704.279.5269
289
Voted 18 Times Best Place to Buy Beds!
FINANCING AVAILABLE!
Kannapolis Kannapolis
229 East Main Street Rockwell, NC, 28138
Hardware
Twin Inner Springs Mattress....$79 each Includes standard 6� Mattress.
Drawers&& Nightstand Nightstand sold Drawers Soldseparately Separately
Get Yours While They Last
Call now for the lowest payments on high efficiency Trane equipment from S.A. Sloop Heating & AC, Inc. Visit us on Facebook:
DENTURES
Bigger Isn’t Always Better We Are Your Professional & Personal Agency Preferred Rates • Multi-Policy Discounts
Low Down Payment E-Z Payment Plan COMPARE OUR RATES!
$
want to speak to the man who gave them the videos and stressed that he could remain anonymous. “He is not in any trouble, we are just seeking more information from him,� Scott said. The videos were mainly captured by security cameras in the victims’ room, though some recordings are from hand held cameras. One suspect was wearing a baseball cap with “LA� on it and another has an orange Tshirt that is printed with the year 2008. Authorities think the videos were made locally in the last three years but could have come from anywhere in the country. Detectives are working with TV show “America’s Most Wanted,� which is planning a segment on the case, Anderson said.
R103631
videos. After the footage was enhanced, they were able to capture the images of four men who carried out assaults, though there could be as many as 10 suspects total. “It shocked the conscience,� said Detective Ron Anderson of the special victims unit, which reviewed the DVDs. “These people are truly defenseless.� woman’s bed, removes both his own and her diaper, then assaults her, authorities said.
R128723
LOS ANGELES (AP) — Graphic video footage obtained by the sheriff’s department shows several men sexually assaulting at least 10 profoundly disabled women, some of them in diapers, officials said Thursday. The assaults came to light when an unknown man dumped a bundle of 11 DVDs at the Los Angeles County sheriff’s.
R124210’s person of the year for 2010, wanted to avoid the public limelight so he would have more time to mature as a leader. To help keep the company private, Facebook sought and received an SEC exemption in 2008 that assured employees who received a class of stock wouldn’t be counted toward the 500-shareholder barrier. The stock awarded those employees won’t be is-
R129070
ments are only being given to an elite group selected to buy a stake in Facebook through a fund packaged by the company’s newest investor, Goldman Sachs Group Inc. Surpassing 500 shareholders will catapult Facebook over a hurdle likely to lead to the company’s’s fiscal year ends Dec. 31, meaning it would have until late April 2012 to comply.
R128323
SAN FRANCISCO (AP) — With so many investors becoming fans of the company, Facebook will be legally required to begin sharing more information about its finances and strategy by April 2012, according to documents distributed to prospective shareholders. Some of the numbers that began trickling out Thursday were eye-popping — most notably a net profit margin of nearly 30 percent, much higher than most people had previously speculated. The owner of the world’s docu-
HOME&GARDEN SALISBURY POST
Deirdre Parker Smith, Copy Editor, 704-797-4252 dp1@salisburypost.com
FRIDAY January 7, 2011
8A
Know what you want when choosing a lawn care company BY DARRELL BLACKWELDER For the Salisbury Post
Lawn care and landscape maintenance is big business in Rowan County. In the early ’80s, there were only a few landscape maintenance companies. Today, there are well over 50 established lawn care and landscape companies and the number is increasing. Increased popularity for lawn care services can be attributed to a number of reasons. Many property owners just don’t have time and pre-
fer to hire a company. Older age has crept up on some, limiting their ability to take care of landscapes, while others don’t understand fertilization and weed control. Some have done a cost analysis and feel it’s more cost effective to hire a company and not invest in the tools needed for proper upkeep. Regardless of your situation, many people are considering hiring a lawn maintenance company. There are basically three different types of service: partial lawn
care, total lawn care and full lawn and landscaping services. Below are a few tips in selecting a lawn care company. • Determine which level of service you need. Some people only want weed control and fertilizer application. They opt to cut grass themselves. Others will want a total package handling everything from lawn care to keeping bird feeders stocked. Part-time workers often fit the bill for those who only need their lawn mowed once in a while, but
keep in mind that these companies are limited. Those that apply pesticides must have and maintain a commercial pesticide license. This requires 10 hours of training every five years. • Make sure the company follows proper lawn care procedures as recommended by N.C. Cooperative Extension. Do these companies offer soil testing? Do they follow accepted recommendations when applying seed and fertilizer? Lawn care and landscape companies
should be able to outline their maintenance program in detail to give customers assurance of their capabilities. • Lawn care companies should provide some guarantee of their work unless, of course, there are extenuating circumstances such as bad weather, insects or diseases. Customers must realize that some problems take time to resolve and also realize that if they impose certain restrictions, problems may still exist. For example, some people want a weed-free lawn
Winter damage
without the use of herbicides. Unfortunately, this is quite difficult, bordering on impossible in most situations. • Obviously, another important method of choosing a lawn maintenance company is to review their work. Most lawn maintenance companies are conscious of their work and regard a well maintained landscape as a living billboard for advertisement. A personal inquiry from friends and homeowners is a key factor in choosing a company that will meet your expectations.
Jazz up walls with artwork BY MARY CAROL GARRITY Scripps Howard News Service
Darrell BlackwelDer/for the salisbury post.
salt used in the driveway to melt ice and snow has seriously damaged edge plantings.
Rock salt does good job on snow, bad job on plants W
ith more ice and snow predicted over the next few days, sidewalks, driveways and entryways may be extremely treacherous with ice and snow. Many people will apply rock salt to quickly melt the ice and snow on sidewalks and drives. There are now products on the market used for rapid ice melt that will not damage plants, but some DARRELL people still use rock BLACKWELDER salt. Rock salt should be applied sparingly, avoiding placement near
valuable landscape materials to avoid salt run-off, which damages plant material. Rock salt works well but can damage landscape plant materials and can also be a runoff pollutant that may damage our streams. Normally, two or more light salt applications are no cause for concern. Snow, ice and normal rainfall usually leach salt through the soil, preventing plant damage. In colder northern climates, which often require routine salting, it causes extensive damage to turf and shrubs. Salt damage to landscape plants is similar to over-fertilization. Leaf margins and tips easily burn, with eventual defoliation. Extreme damage shows itself quickly, in a mat-
ter of days, whereas slight salt damage may not manifest itself until spring or early summer. Try to keep salt and other de-icing granules as far away from trees and shrubs as possible when applying to entranceways, sidewalks or roads. Be sure to read and follow the instructions and apply only as needed. Those who apply salt on a routine basis should plan to leach shrubs with water during the spring. Salt damage can be avoided by using rock salt substitutes. These de-icers effectively melt ice and are safe on the plants and the environment. Ice melting substitutes are available in both granular and liquid formulations for easy appli-
cation. Sand is also an effective saltsubstitute. Actually, sand does not melt ice or hard packed snow, but does provide good traction to prevent slipping. It’s messy and somewhat unattractive, but sand stays on the surface of the ice through its duration and is easily swept off when sidewalks dry. It is the safest way to protect tender shrubs or trees. Darrell Blackwelder is the County Extension director with horticulture responsibilities with the North Carolina Cooperative Extension Service in Rowan County. Learn more about Extension events and activities on Facebook or at.
Early January is the best time to do an honest assessment of your decor and come up with a list of projects, like getting the rugs and upholstery cleaned, touching up paint and rearranging accents. While you’re making your list, be sure to put “hang artful artwork displays” at the top, because filling your home with wonderful art is one of the simplest and most effective ways to dramatically improve its look. Scrutinize the walls. Are many of them blank? Do others feature lackluster displays, like a small painting hung all by itself in the middle of a big open wall? If so, “finish” the rooms by decorating the walls. Try a grid. I love this technique of hanging a mass of similar pieces together to create one huge square or rectangle. The repetition of shape, subject and color scheme, amassed as one large group, is not only arresting, it’s a great way to use a number of smaller, inexpensive pieces. When designing montages, let your creative instincts lead. Start by gathering a wide array of artwork that includes a range of media, such as oils, pastels and engravings. Blend different frames — natural wood, metal, gilded gold — and even canvases that have no frame at all. Mix up the subject matter, too, including portraits, landscapes, architectural drawings and abstracts. If your style is mostly traditional, throw in a piece of modern art, or vice versa. Be sure to get a wide variety of sizes, too, from very large statement pieces down to tiny masterpieces that measure no more than a few inches. Don’t discount the big role that diminutive pieces play in the arrangement’s overall look. They give a big punch by breaking up the monotony of standard-size frames.
Hobbies: Create a 3-D daily scrapbook from Rolodex BY SANDI GENOVESE Scripps Howard News Service
If an apple a day promotes good health, then I wonder what the result would be of a photo a day? This year, I’m going to find out. With a new year beginning, my thoughts usually turn to calendars. But with smart phones and all kinds of electronic scheduling devices, it seems like paper calendars may be becoming extinct. So I decided to combine my love of paper calendars with my love of photos in creating a threedimensional, daily scrapbook. I started with a standard Rolodex rotary card file, converting it into a diarystyle journal by making monthly dividers from black card stock, labeled with a white pen and 30 to 31 colored pages to go behind each divider. I thought the only tricky part would be cutting out the holes that bind the pages to the holder. Turns out that’s easy, with the aid of an inexpensive punch that Rolodex makes. Both the hole punch and the rotary card file are available at any office supply store.
Instead of using my handmade “calendar” to keep track of upcoming appointments, I will use it to keep a daily journal of whatever I want to remember. Instead of a calendar, think of it more like an informal journal of daily events. Most pages will be made from a photo, trimmed to fit the card shape and inserted into the file to mark special days like birthdays and everyday events like the cat sleeping in the discarded holiday boxes. The back of each photo is perfect for noting the story behind the picture, and the monthly dividers have scrapbook embellishments that coordinate with each month. Because a picture really is worth a thousand words, it’s not necessary to write very much. Most of the talking is done with the photographs. This three-dimensional scrapbook will look great sitting on a table and will provide a unique look back at my life during 2011. Contact Sandi Genovese at sgenovese1@cox.net. and find free video demonstrations of more photo projects at.
scripps howard news service
combine paper calendars with photos to create a three-dimensional, daily scrapbook.
SALISBURY POST
FRIDAY, JANUARY 7, 2011 • 9A
HOME & GARDEN
Disorderly home life creates problems for kids and adults
Don’t toss your old car floor mats, reuse them Dear Sara: I’m thinking about buying new floor mats for my car, but I do not want to throw out the old ones. Do you have any ideas? — Melissa, e-mail Dear Melissa: I’d use them in the garage, either for under your car to catch any leaking fluids or as door mats to store shoes or to keep dirt or debris from being tracked into your home. Or keep a couple in your trunk in case anything SARA leaks in your NOEL trunk or if you ever are in need of extra tire traction. Wash one and use it under a child’s car seat to protect your seats. Have you tried washing them? Some car washes have mat-cleaning machines. Or take it to a self-service car wash and use the high-pressure hose to wash them. If
they have carpet on them, use a scrub brush and carpet cleaner, and then rinse with the pressure hose. You might discover that you don’t need new car mats. Dear Sara: Do you know of any homemade cleaners to clean a brass lamp? — Polly, Pennsylvania Dear Polly: First, try using a wet toothbrush and buffing with a cloth. If you’re not happy with the results, use vinegar and salt. Add 1 teaspoon salt to 1/2 cup vinegar, and add enough flour to make a paste. Rinse and buff. Or use lemon juice and baking soda, cream of tartar or salt, made into a paste. Please note: This is for nonlacquered pieces. If it’s lacquered, use only a damp cloth. Dear Sara: We were reading your reply about dish washing and adding Lemi Shine to the dishwasher. We thought we would give it a try, but we can’t find Lemi Shine. Could that be a misprint? — Margaret B., e-mail
Dear Margaret: No, it’s not a misprint. It’s manufactured by Envirocon Technologies Inc. It’s typically found in the dishwashing-product aisle. You can call the company for information at 888-336-2582. There is a store locator at ucts/Store-Locator.html. You can fill out a request form and give it to your local store manager, too. It’s at. Dear Sara: I really like your column and enjoy trying some of your ideas. I would like to try to make my own fabric wrinkle release. But in the newspaper the amount of water or whatever liquid I mix with the 1 teaspoon of fabric softener was not mentioned. Could you let me know? Thanks for your help. — Ann G., e-mail Dear Ann: My apologies. Here’s the recipe. Fill a spray bottle (32 ounces) with distilled water. Add 1 teaspoon liquid fabric softener. Shake
to mix. Spray the wrinkled garment until it’s slightly damp. Pull to smooth out wrinkles. Hang until dry. It works well as a fabric freshener, too. You can increase the amount of liquid fabric softener up to 1 tablespoon. Dear Sara: I don’t make piecrusts. I buy them frozen. Is there a way to fix broken frozen piecrusts? — Emily J., Indiana Dear Emily: Let it thaw. You can either use your fingers (wet them) to press it back together or re-roll it. Or brush some melted butter on it and sprinkle on cinnamon and sugar and bake a treat.. United FeatUre Syndicate
Seven simple ideas for setting Asian-influenced tabletops Home and Garden Television
A continuing compendium of tips and tricks from Home & Garden Television: Asian-influenced tabletops can have a variety of looks, from calm and serene to vibrant and exciting. The key to all of them is composition. Asian tabletops are all about balance, color, placement and the simplicity of the objects. Here are some ideas for setting various moods with Asian elements: 1. Use deep reds and golden highlights to set an opulent Chinese-inspired tabletop. A gold platter with Chinese inscriptions adds drama when used as a charger under red lacquer plates, with the gold-
en hues repeated in amber stemware. The centerpiece could be a small group of stone figures flanked by small bunches of red roses. 2. For a serene mood, try a soothing muted green and move the party into the living room. Incorporate a coffee table for serving, and sit on pillows. 3. Look for geometric shapes, unusual colors (from bright to muted), bamboo linens and placemats, and natural textures such as reed and silk that blend into a balanced presentation. Few elements are needed to get an Asian feel: Put glazed ceramic plates over bamboo placemats and use black iron lanterns for festive but sim-
ple centerpieces. 4. A reproduction Chinese cabinet is a wonderful backdrop for a buffet table decorated with vegetation. Cabbage can overflow from a wrought-iron vase while a row of miniature pineapples stand at attention underneath. 5. Use ordinary rice in a tray with the plates set on top or in a vase with flowers or fresh vegetables. Or line an oblong wooden bowl with rice and place votive candles on top to use as the centerpiece. 6. Wrap the outside of cylindrical glasses in plastic for protection, moisten spring-roll wraps and drape them around the outside of each glass. Once dry, remove the wraps and place a votive
HOURS: Monday-Friday 9am-5pm
Golf Bags Cart Bag
NOW $129.99
WAS 99.99
$
20 off
Stand Bag
NOW 79.99
Scoreboard Clock % $
r nte i W le
No Leaf
Sa
Gutter
FREE FLOWING WATER CONTROL
J.A. FISHER
A Specialty Contractor Since 1979 With Over 7000 Completed Jobs
704-788-3217
Salisbury
Kannapolis
Spa Pedicure .......................$1999 Kid Spa .................................$1500 Spa Head (45 min)................... $3099
Gel Nails w/white tips........$2999 Full Set ............................$1999 Massage Available ...1 Hr. $50/ 1/2 Hr. $30 Fill-in ...............................$1299 Eyelashes.....................................$1999
FREE Hot Stone Massage with pedicure service
Refreshments Served
OPEN SUNDAY 12-5
1040 Freeland Dr., Ste 112 Salisbury, NC 28144
Please bring ad to receive special pricing. Exp. 1/30/11
704.636.0390
To advertise in this directory call
704-797-4220
Quality Haircut
$
4.99 DEBBIE’S HAIR DESIGNS for new customers only
men • women • children 1008 S. Main Street • Salisbury, N.C. Call for an appointment
704/630-9970 or 704/433-0595 Chad Mitchell, Chairman Carl Ford, Vice Chairman Jon Barber Raymond Coltrain Jim Sides
Gary Page, County Manager Carolyn Athey, Clerk to the Board John W. Dees, II, County Attorney
Rowan County Board of Commissioners 130 W Innes St. • Salisbury, NC 28144 Telephone 704-216-8180 • FAX 704-216-8195
NOTICE
The Rowan County Board of Commissioners will hold a public hearing on Tuesday January 18, 2011 in the J. Newton Cohen, Sr. Meeting Room on the second floor of the J. Newton Cohen, Sr. Administration Building, 130 W Innes Street, Salisbury, NC. The public hearing will be held during the meeting commencing at 6:00 PM. In accordance with the North Carolina General Statutes 153A239.1, the purpose of the hearing is to entertain public comment for the following road name: Trexler Memorial Ln; South off 4500 E NC 152 Hwy
Those wishing further information may contact the County Manager’s Office at 704-216-8180 or the Rowan County Planning Department at 704-216-8588. This the 3rd day of January 2011.
Carolyn Athey, CMC, NCCCC Clerk to the Board/Assistant to the County Manager County of Rowan, North Carolina
R124898
Sacred Heart School
Open House Saturday, January 8th or Thursday, January 20th 9am to 12noon
WAS $169.99
Quantities are limited on all of these Items! In-stock items only!
holder inside. 7. Place a seaweed wrap between each plate and charger for decoration. Moisten udon noodles and wrap them in a small circle to use as napkin rings once dry, and tie individual name cards to pears with raffia. Rest a pair of chopsticks on a tiny pepper next to each plate. For thousands of other ideas visit. Distributed by Scripps Howard News Service.
monials, amazing. I’ll run gan Ave., Chicago, IL 60611. some of these letters in future Amy Dickinson’s memoir, columns. “The Mighty Queens of Freeville: A Mother, a DaughSend questions via e-mail ter and the Town that Raised to askamy@tribune.com or by Them” (Hyperion), is availmail to Ask Amy, Chicago able in bookstores. triBUne Media SerViceS Tribune, TT500, 435 N. Michi-
R124211
er instruct your daughter to hit someone. I understand your logic, but if this boy can’t control his impulses, then your daughter retaliating could bring on nothing more productive than a backyard brawl. You should instruct your daughter to tell this boy, “No hitting!” and to leave the area (and tell an adult) if he does. Children usually have an instinct to stay away from a volatile child. You should encourage your daughter to listen to her own instincts in this regard and stay well away from this cousin. Dear Amy: Your effort to persuade readers to give books to children for Christmas is laudable. My parents gave books to us. Now my siblings and I give books to our children. I honestly feel that this is the most significant opportunity for learning and growth we have offered our kids. — Happy Reader Dear Reader: I am delighted to say that my effort to put a “Book on Every Bed” has been a runaway success. The response has been overwhelming and the testi-
R128577
with his sister and her children. One of her children inevitably hits one of our children at least a couple of times during each visit. Sometimes the parents will discipline him, but more often than not they let this behavior slide. I have told my daughter that if this boy hits her she should tell an adult (namely, the boy’s parents), but time and again they do nothing about it. Sometimes they even try to suggest that my daughter is lying when she reports that she has been hit. This boy has quite a few behavior issues and should not be playing unsupervised with the other children, but his parents don’t supervise him. I don’t like to penalize my daughter by forcing her to remain under constant supervision for her own safety. Is there ever a point where it is OK to tell her that if this child hits her that she can hit him back? I fear that this is the only way he will learn to stop hitting her. — Annoyed Mom Dear Mom: You should nev-
S47812
says that he is crazy about her. My fiance and I both fear commitment and divorce. We sit in limbo, afraid to get married or to separate, although the last time we talked about it he said he does want to get married. I don’t know what to do. — Sober but Confused Dear Sober: Do you really think this mess boils down to your refusal to leave your children with a baby sitter? Honestly, the way you portray the atmosphere in your home, the kids might be better off with a sitter. Now that you are sober, you should focus your energy on staying sober. Ask your counselor to help you explore your choices and their consequences, and ask your fiance to come into therapy with you. Your primary commitment should be to do what’s best for your children. Living in the midst of this volatile and chaotic relationship is definitely not good for them. You two could repair your relationship, but until you do so, a peaceful separation might be best for the kids. Dear Amy: My husband and our two children spend time
R124390
Dear Amy: Six months ago, I got drunk and woke up in bed with another man. My fiance was yelling at him. It has been hard, but I quit drinking, got counseling and made it my purpose in life to be a better mother and partner. I had been unhappy for years because my fiance never goes anywhere with me, and if we ASK go out, we go AMY separately because we don’t like to hire baby sitters for our two kids. Now, my fiance has come back from a work trip where he had a weeklong affair. All the evidence was on display for me to find, but when I confronted him, he said it was just a mistake, not an affair. I asked him to leave, but he refused. The police have said that he doesn’t have to leave if he doesn’t hit me. His mistress has told me he is only staying with me for another couple of weeks. She
Now Enrolling Pre-K thru 8th Grade
All W elcom e
WAS $139.99
NOW 99.99
$
WAS 49.99 $
20 off NOW $39.99
Largest Selection of Collegiate Merchandise in Rowan & Cabarrus Counties
704-637-5144
R127753
No Districts. No Politics. No Distractions. Just 129 years of Great Education. 385 Lumen Christi Lane, Salisbury 704-633-2841
R128811
Scoreboard Alarm Clock %
OPINION
10A • FRIDAY, JANUARY 7, 2011
SALISBURY POST
A lesson from Old Bess
Salisbury Post “The truth shall make you free” GREGORY M. ANDERSON Publisher
U.S. CONSTITUTION
The president and his power GOP takes control With the Republican-led House drawing attention to the U.S. Constitution — and flexing its own legislative muscles — this may be a good time to review what the Constitution describes as the president’s powers:.
T
Check, please et’s be clear. When Charles Black paid his property tax bill Wednesday with 921 one-dollar bills and 83 pennies, he was paying city and county taxes. Black chose to pay this way as an act of defiance against Salisbury’s annexation of his property three years ago. But with or without annexation, Black would have been making a trip to the Rowan County Tax Collector’s Office. To really make a statement, he should have paid the county’s share with a check.
L
Common sense
(Or uncommon wisdom, as the case may be)
Mistakes are part of the dues one pays for a full life. — Sophia Loren
ld Bess is a dog that has lived out her best days. Yet she still has life left in her and is loved and adored by her master, Joe Thomas. She is a hunting dog, and even though she has aged, she may still have a good chase or two left in her. Joe Thomas is the pastor of Franklin Baptist Church in Salisbury. In his sermons, from time to time, he illustrates with a human interest story. He is also one who enjoys a good DICY MCCULLOUGH joke. One Sunday service, not long ago, he shared a funny incident that happened to Old Bess. Listening to the details that Sunday morning, I felt like I was an eyewitness to the events. As Pastor Joe begins the story, he has excitement in his voice: “One morning, Old Bess is sleeping on our front porch. She wakes up and notices a squirrel sitting at the far corner of the yard. Old Bess eyes the squirrel while the squirrel eyes Old Bess. “The squirrel looks as if he knows what’s going to happen next. In an instant, he takes off running, with Old Bess following in hot pursuit. Bess is a wonderful hunting dog, so I think I know how this is going to end. “The squirrel, much to my surprise, puts on brakes and stops dead in his tracks. Poor Bess isn’t expecting that move, and she tries to stop as quickly as she can. Unfortunately, she can’t stop fast enough, and winds up hitting the tree dead-on. Old Bess gets up, dazed, and looks around wondering what just happened.” Pastor Joe says he couldn’t help but laugh, and it seemed as if the squirrel was laughing too. The squirrel then took off in a different direction, leaving Bess to shake the cobwebs out of her head and limp to the porch with a bruised ego. How many times do we chase a fine-looking squirrel, only to hit the tree head-on? For many of us, material things in our lives are the squirrels that cause problems and headaches later down the road. When we have a family, sometimes we spend money we don’t have and finance things we shouldn’t. Perhaps that beautiful home will make an impression on family and friends, but it might take every penny to finance it. There are material things we think we can’t live without, but in reality we are not truly living with them. Our financial burden becomes the tree we hit head-on. Even when we realize the mess we’re in, it might take years to shake the cobwebs out. Just like with Bess, we think the squirrel is a quick catch, but instead it turns into a quick headache. I think about Old Bess from time to time, and I wonder if she ever thinks about that crazy squirrel. Pastor Joe says, “He wonders that too.” Then he adds, “One thing’s for sure, she hasn’t chased many squirrels since that day.” Just like Old Bess, we need to stop chasing squirrels that look enticing. Life may actually be better if we enjoy what we have instead of longing for material things we don’t need. This year, when you pull out the credit card, think about Old Bess dreaming of days gone by. Then, slowly put the card back in your wallet, and happily walk away. ••• Dicy McCullough is a freelance writer and poet who lives in Rowan County. She can be reached at 704278-4377.
O
704-797-4201 ganderson@salisburypost.com
Day One in power doesn’t go as planned
ops. The first days of the GOP takeover of the House of Representatives did not go quite as many Republicans intended. Having promised to cut $100 billion from federal spending (even as the national debt surpassed $14 trillion), the GOP leadership on Day One had to scale that back to $35 billion, arguing President Obama’s budget was not passed in 2010 so there wasn’t as much to cut as the GOP expected. After pledging that all legislation increasing ANN deficit MCFEATTERS the would be offset by strict spending budget cuts elsewhere, new House Speaker John Boehner, R-Ohio, had to backtrack. Vowing the House will repeal the health care law, he found out the non-partisan Congressional Budget Office says repeal would add $230 billion to the deficit, which Republicans can’t offset. Boehner said, oh well, the CBO’s numbers are off. Then Boehner had to defend his position that amendments will be permitted on pending legislation and must go through proper committee procedures — except for repealing the health care law. “I didn’t say every bill would be open,” he explained. Then there was the historic reading of the Constitution — apparently, never done before on the House floor. But the question immediately arose — which Constitution? “This is not a debate,” snapped the Republican in charge as a Democrat legitimately raised a parliamentary point of inquiry. As Republicans and Democrats lawmakers obediently lined up like schoolchildren to read the parts of the 4,500word document allotted to each, Democrats objected to reading parts nobody likes anymore. For example, the original Constitution counted a slave as three-fifths of a human being and decreed fleeing
O
New U.s. House speaker John Boehner and rep. eric cantor speak at a press conference about repealing the ‘jobs killing’ health care law. associated press
slaves be returned to their owners. The original Constitution stipulates many things we no longer hold dear. Legislatures no longer choose senators. Congress no longer assembles once a year on the first Monday in December. The House and Senate no longer have to get each other’s consent to adjourn for three days. The U.S. no longer regulates trade with “Indian tribes” or goes out of its way to punish all pirates. States no longer impose duties of $10 per person on citizens moving from other states. Armies are now raised and paid for longer than two years at a time. And don’t get us started on holding prisoners without lawyers, charges or speedy, public trials, all of which the Constitution forbids but which we have done in recent history, to the approval of many Republicans. Reading the Constitution turned out to be both bipartisan and uninspiring, except for the slight amusement of listening to legislators stumbling over unfamiliar words. Outgoing speaker Nancy Pelosi showed up all the men by having memorized her portion. Rep. Jay Inslee, D-Wash., remarked that, technically, the Constitution should not have been read since, under Boehner’s new rules, the Republicans did not alert Democrats to what version of the Constitution would be read, denying members the necessary 72 hours to consider the language
LETTERS Teen groups are doing good work Recently we had the privilege to serve at the community Christmas store provided by the Family Crisis Council. We were assigned to wrap gifts for customers and were fortunate to be grouped with four very fine teenage ladies who are students at Knox Middle School and Salisbury High School. Their names are Tamara, Bryce, Destini and Bria. They are members of a service club called the Me-Time Club and were serving the community as workers in the Christmas store. We felt compelled to write and inform the community not only about the importance of supporting service clubs such as the Me-Time Club but also about how young people are doing good things. It was refreshing to see these girls willingly serving with happy hearts and truly enjoying their time of service. They made the night so light and fun for the customers and for us. We laughed and talked for the three hours we were there and ended up
TO THE
before the House. He was joking. Or so we think. John Boehner and his sidekick Eric Cantor, R-Va., didn’t even listen to the reading and left the floor as soon as their parts were finished to hold a news conference. As their colleagues continued toiling over the reading of the (amended) Constitution, Boehner and Cantor preached to news media about killing the “jobs-killing” health care law. As legislators droned on through seven articles and 27 amendments, the White House took advantage of the quiet time to confirm that Bill Daley, Al Gore’s former presidential campaign manager, would be the president’s new chief of staff. Stumbling into their second week on the job, GOP legislators are lining up to propose un-Constitutional things. For example, some members plan to introduce bills denying citizenship to U.S.-born children of undocumented workers, which the Constitution forbids. Some members do not want to extend the debt ceiling, although the Constitution says we must pay our debts. Some people want to jail people who burn the flag, although the Constitution guarantees us free speech. The list is long. Here’s betting we won’t hear another reading of the Constitution any time soon. • • • Scripps Howard columnist Ann McFeatters has covered the White House and national politics since 1986. E-mail amcfeatters@nationalpress.
with new friendships and fond memories. If you are presented with the opportunity to attend an event produced by this service club or others in our high schools, or to support them in other ways, we encourage you to do so. Your support will be appreciated and productive. They deserve our commendations. — Scott and Diana Aldridge Salisbury
Message to thief To whoever stole the copper tubing out of my central air and heating unit on Wildwood Road, I hope the devil serves you graciously, and you will really deserve everything he does to you.
I hope you listen to the country music song “I will pray for you,” and that is exactly the way I feel about you. This is the third major theft I have had at that house, so the next time you strike, just take the whole house and you will give me peace of mind because there is not a whole lot of damage you can do to the land that will be left. May the devil live with you forever because you do not possess a conscience. Everything was fine Tuesday, Dec. 28, so you must have needed money to celebrate New Year’s. I hope you have a blessed New Year, and I hope you rot in jail when and if you are arrested. God is watching you. — Peggy Shuping Salisbury
SALISBURY POST
FRIDAY, JANUARY 7, 2011 • 11A
W O R L D / N AT I O N
A first: Constitution read on floor of US House
Packages ignite in Maryland government buildings
Spending cuts the talk from Republicans as they charge preelection.
Defense secretary plans to trim $78 billion over next five years WASHINGTON (AP) — Defense Secretary Robert Gates announced Thursday he will cut $78 billion from the Pentagon’s budget in the next five years — money that will come from shrinking the military’s ground force, increasing health care premiums for troops and other politically unpopular cost-saving measures. The plan also identifies a separate $100 billion in savings, including the cancellation of a $14 billion amphibious Marine vehicle. However, the services will be allowed to reinvest
associated press
emergency personnel confer outside of the Jeffrey Building in annapolis, Md., after smoke and the smell of sulfur poured from a package opened thursday. two employees were slightly burned, but no one was seriously injured in two separate incidents. that money in new weapon systems and programs that benefit troops, he said. The.
Okla. holds first execution of ’11; man tells family, ‘I’m all right’ MCALESTER, Okla. (AP) — ALVERSON all right.”
Illinois lawmakers OK plan to do away with death penalty punish-
ment.
Washington couple claim half of $380 million Mega Millions stash OLYMPIA, Wash. (AP) — The man who bought one of the two winning tickets in the $380 million Mega Millions lottery on Wednesday claimed his half of the second largest jackpot in history. Jim McCullar then promptly handed the oversized check to his wife, Carolyn, as their adult children looked on. “We’ve been married 41 years,” he said. “I know what to do with this check.” While the McCullars stepped forward to get their prize, officials and residents in neighboring Idaho were still waiting for whoever has the other winning ticket to claim their winnings.. He said the money will, of course, help his large extended family: six children, including two from an earlier marriage; 23 grandchildren and five great-grandchildren.
Suspect in Alaska theft left behind something important — his wallet FAIRBANKS, Alaska (AP) —.
Conspiracy convictions tossed in Anna Nicole case
STERN
EROSHEVICH
California Patients Bill of Rights passed in 2006 recognized the concept of the “pseudo addict,” which is defined as “a person whose drug seeking behavior is primarily due to the inadequate control of pain.” The judge, citing testimony about Smith’s quest for pain relief, said, “I certainly believed she was not an addict under the law.” After a three-week preliminary hearing and a nine-week trial, jurors returned guilty verdicts on few of the 11 charges against the three original defendants. Howard K. Stern, 41, and Dr. Khristine Eroshevich, 63, were convicted of conspiring to violate the false name statute to obtain painkillers for the former Playboy mod-
el. Eroshevich also was convicted of obtaining Vicodin by fraud. Dr. Sandeep Kapoor was acquitted of all the charges against him. Perry said he considered the minimal jury verdicts “a strong repudiation of the prosecution’s case,” which he described as overly complicated and not supported by sufficient evidence. During the trial, he said he saw weaknesses in the case but decided to let it go to the jury. Los Angeles County District Attorney Steve Cooley said he would appeal the dismissals. “His decision denigrates the substantial investigative efforts conducted by the state Department of Justice and the medical board,” Cooley said in a written statement. “It diminishes the huge social problem of prescription drug abuse facilitated by irresponsible caretakers and unscrupulous medical professionals.” The case was launched last year amid much fanfare by then-California Attorney General and now-Gov. Jerry Brown, who denounced the defendants as conspirators in
over-prescribing prescription drugs to Smith, whom he called “a known addict.” He also accused the defendants of being lured by Hollywood glamor. Judge Perry.
Lost Your Medicare Advantage Plan Dec. 31? You are entitled to a guaranteed issue F Plan Supplement until March 1, 2011. Lowest prices in N.C. on F, G, M and N plans. For simple enrollment call
Jeff Saleeby Agency 704-633-1311 or email: jsaleeby@carolina.rr.com R 12 87 24
LOS ANGELES (AP) — After a prolonged, costly prosecution that put Anna Nicole Smith’s prescription drug use under a legal microscope, a judge dismissed two conspiracy convictions Thursday against her boyfriend-lawyer and psychiatrist and reduced one remaining count against the doctor to a misdemeanor. It was an ignominious ending for prosecutors who had touted the high-profile case as a way to send a message to physicians who over-prescribe opiates to celebrities. Superior Court Judge Robert Perry suggested authorities had chosen the wrong case to prove their point, and indicated they did not understand the legislative intent of the law involving prescription drugs. .” The judge noted that the
SAM’S
An “Old” Name In Car Washing Established 1962
With “New” Innovations In Washing All Size Vehicles
SALTBUSTER SPECIAL Outside Wash, (hand finished) Underbody Wash & Rust-Inhibitor
$
Only 8.95 Limited Time Offer!
For the Best Wash & Safest Wash For All Vehicles Finishes Visit a Sam’s Car Wash Today!
800 E. Innes St. • 1022 W. Innes St. Salisbury
R129258
HANOVER, Md. (AP) —. One device was found in Hanover and the other was in Annapolis. Mailrooms at government offices across Maryland were evacuated. Two other suspicious packages were discovered, though one turned out to be a toner cartridge and the other was. One of the packages contained a message from a disgruntled person, a government official familiar with the investigation told the Associated Press. It had a zipper feature and when ripped open, a “flame popped out.” The official asked for anonymity because the person was not authorized to speak about the ongoing investigation.
WASHINGTON (AP) —. The reading also skipped the 18th Amendment that was ratified in 1919 to institute prohibition of alcohol. That amendment was overturned in 1933 by the 21st Amendment.
12A • FRIDAY, JANUARY 7, 2011
SALISBURY POST
BUSINESS/AREA
Slower retail figures from December disappoint investors
Shoppers won’t lose energy in ’11, some say.
Hiring outlook brightens as layoffs decline WASHINGTON .
30-year fixed mortgage at 4.77 percent NEW YORK (AP) — Rates on fixed mortgages dipped this week after rising steadily over the last two months. Freddie Mac said Thursday.
Retail sales show November drop in Europe, said Thursday that eurozone retail sales fell 0.8 percent in November from the previous month, and revised down its estimate for spending in October. Now it thinks that retail sales were stagnant during the month instead of its previous prediction of 0.5 percent growth..
associated press
Exhibitors and buyers at the Consumer Electronics Show walk by a display of LG HDTV screens Thursday in Las Vegas.
Microsoft not finding easy way to match iPad’s success SEATTLE (AP) — Instead of unveiling an elegant response to the iPad, Microsoft came to the tech industry’s premier gadget show with a collection of exposed computer guts, news about microchips and a shallow preview of yet another Windows. The uninspiring performance served as a reminder that the world’s largest software maker remains years from a serious entry into the tablet craze, raising more doubts about whether Microsoft Corp. will ever be able to grab a meaningful piece of this fastgrowing segment. If it can’t, Microsoft Corp.’s dominance of personal computers may become increasingly irrelevant as people embrace ever-sleeker portable devices. Win-
SHOT FROM 1a ing the wound. Whisonant fell back onto the ground and felt his head. “I hit the ground. I didn’t know what to think. I was stunned,” he said. The blood on his hands confirmed he had been shot, but Whisonant knew he wasn’t seriously wounded because he could stand, he said. His cousin was just arriving to the area and he drove Whisonant to the hospital.
The last thing Whisonant remembered was the four people walking away. Thinking back on what happened, Whisonant isn’t sure why he hesitated when the man asked for the money, except that he was in shock. Whisonant believes he’s still alive because of prayers. “My mom, she’s a churchgoer. She prays for me every night,” he said. “All I can think of is my mother had to be praying for me.” Whisonant said he’s not a troublemaker and never gets into altercations with anyone. “I don’t bother nobody. I’m courteous. Stuff happens
every day to good people,” he said. He believes the man didn’t have to shoot him. Whisonant, who has worked at the Post as a temp for about five years, said he works to provide for his 1-year-old daughter, Leyanna, but he would’ve gladly given the money. “My life revolves around my daughter. I work to take care of her,” he said. Whisonant is a Salisbury native. Salisbury Police officials did not return a phone call seeking details Thursday night. Contact reporter Shavonne Potts at 704-797-4253.
How To Get The Perfect Shoe Fit
go to view the
at
German industrial orders up in November BERLIN (AP) — German industrial orders in November rose by a strong 5.2 percent on the month fueled by brisk foreign demand for capital goods, official data shows. Domestic industrial orders in November rose by 1.5 percent and demand from abroad was up by 8.2 percent, leading to the strong overall increase of more than 5 percent, Germany’s Economy Ministry said. November’s uptick followed an increase of 1.6 percent a month earlier. German industrial orders in November were 21.7 percent higher than a year ago, when the financial crisis had plunged the country into its deepest postwar recession, the ministry added. The country’s recovery has made it a standout among the 17 countries that use the euro currency, where smaller economies such as Ireland, Greece and Portugal are struggling with huge debts and deep recessions.
dows amidst. Microsoft has not been absent from the tablet discussion — Windows tablets have been around for years, but the devices have never caught on with the mainstream.
MIDLAND — Authorities have charged three people in a string of recent break-ins in southeastern Cabarrus County. The arrests occurred early Tuesday, the Cabarrus County Sheriff’s Office said in a press release. A deputy was patrolling the Midland area and checking buildings around 3:30 a.m. when he saw a person duck behind a parked car. The deputy found a man later identified as Steven Sowell lying under the back of a vehicle, attempting to Two hide. other people — Joseph Baucom and SOWELL Rosa Biller — were found with Sowell. The deputy discovered that Baucom and Biller both were wanted in Charlotte in connection with breaking and entering cases. Due to the number of recent breakins in the Midland area, Cabarrus de- BAUCOM tectives were called out to investigate further. After an investigation and interviews in which much of the stolen property was recovered, the suspects were each charged with: Three counts of breaking or entering; three counts of larceny after breaking or entering; five counts of felony conto spiracy c o m m i t breaking or entering and BILLER larceny after breaking or entering; two counts of breaking or entering a motor vehicle; four counts of misdemeanor larceny. Additional cases are being investigated and could lead to additional charges, the release from Cabarrus County Sheriff Brad Riley’s office said.
R122864
NEW YORK (AP) — The holiday shopping season was the best since 2006, as a strong November more than offset spending that tapered off in late December. The strength of holiday sales from Oct. 31 through Jan. 1 suggests a recovery in consumer spending. For investors, whose expectations were riding high after a stronger-thanexpected November, the December figures were disappointing. That hurt retail stocks Thursday. Early holiday discounts, which started in late October, drove sales but also had shoppers finishing more gift-buying before December. A lull early in December and a blizzard Dec. 26 in the Northeast also took bites out of sales. From Oct. 31-Jan. 1, revenue at stores open at least a year rose 3.8 percent over last year, according to an index compiled by the International Council of Shopping Centers. That’s the biggest increase since 2006, when the measurement rose 4.4 percent. The index tailed off to a 3.1 percent increase in December after a 5.4 percent rise in November.
Three charged in Cabarrus break-ins
If you are
R129257
diabetic and are enrolled in
North Carolina Medicaid, you may be entitled to be fit for therapeutic footwear. This is designed as preventive medicine to ensure that you don’t develop diabetic foot complications and provide you with comfortable, supportive shoes.
S. Koreans say Google collected personal info SEOUL, South Korea (AP) — Google Inc. collected e-mails and other personal information from unsecured wireless networks in South Korea while taking photographs for its Street View mapping service, police said Thursday.khwa, a police officer in charge of the investigation. Jung said the police reached the preliminary conclusion after analyzing hard disks obtained from Google, noting that police plan to wrap up the investigation by the end of the month.
As a Board Certified Pedorthist, and an insulin dependent diabetic for 35 years, I can’t stress enough the importance of proper shoes for diabetics. Ralph L. Baker, Jr.
O W N E D
/
O P E R A T E D
428 N. Main Street, Salisbury, NC
704-636-1850 HOURS: MON.- SAT. 10:00-5:00
ralphbakershoes.com
God Bless America!
RALPH L. BAKER, JR.
SPORTS
College Football LSU’s Miles focused on Cotton Bowl, not Michigan/4B
FRIDAY January 7, 2011
SALISBURY POST
Ronnie Gallagher, Sports Editor, 704-797-4287 rgallagher@salisburypost.com
1B
In demand Cavaliers, NFL Films interested in homeless man BY TOM WITHERS Associated Press
AssociAted Press
ted Williams, a homeless man from columbus, ohio, is suddenly a wanted man.
As usual, ACC was mediocre
CLEVELAND —
life and radio career were ruined by drugs and alcohol, Williams has been offered a job by the NBA’s Cleveland Cavaliers, and the 53-yearold.
See HOMELESS, 4B
PREP BASKETBALL
Falcons top East
BY CAULTON TUDOR Raleigh News and Observer
The coach whose team won by the widest margin — Maryland’s Ralph Friedgen — got fired. He was replaced by a guy — Connecticut’s Randy Edsall — whose team lost its bowl game by 28 points. Academic heavyweight Stanford won 4012 over the best team in the conference — Virginia Tech — after winning 68-24 in regular season over one of the weakest, Wake Forest. Two league wins — North Carolina over Tennessee and the Terps over East Carolina — were against opponents that finished 6-7. Such has been the nature of Atlantic Coast Conference bowl play in the postseason of 2010. With one game left — Boston College (7-5) against No. 13 Nevada (12-1) on Sunday in the Fight Hunger Bowl — the ACC still has a chance to escape with a 5-4 record. But with only a few exceptions, the ACC football season is ending on much the same flat note it began — with several embarrassing September setbacks. Counting Virginia Tech’s humbling performance against Stanford in Monday’s Orange Bowl game, the ACC champion has lost 10 of its past 11 bowls. Not only have the ACC champs lost, only four of the 10 losses have been by ess than 10 points. After a 3-4 bowl record following the 2009 season some ACC coaches said it’s unfair to gauge a league’s reputation entirely on postseason scores. There’s some truth in that argument, of course, but it’s becoming predictable rationale. Other than North Carolina’s double-overtime win in Nashville, N.C. State’s Champs Sports Bowl upset over No. 22 West Virginia and Florida State’s win over SEC runner-up South Carolina, the ACC’s bowl run more or less reflected a regular season that was near void of inspiring non-league wins. In the final Associated Press poll of the 2009 season, Virginia Tech (No. 10) was the highest ranked ACC team. The league will be fortunate to have a team among the top 15 when the last 2010 poll is released next week. And the outlook for 2011 isn’t much brighter than in the past few years.
Gurley Earns 300th win at West BY MIKE LONDON mlondon@salisburypost.com
tyler buckwell/sALisBUrY Post
West rowan’s Jarvis Morgan skies the paint for shot over east rowan’s Avery rogers.
MOUNT ULLA — Clad in his familiar W. Rowan 59 light blue vest, West E. Rowan 47 R o w a (58,
tyler buckwell/sALisBUrY Post
thursday’s victory was the 300th at West rowan for coach Mike Gurley. did-
See WEST BOYS, 3B
West girls rout Mustangs BY MIKE LONDON mlondon@salisburypost.com
MOUNT ULLA — It was a strange W. Rowan 70 blowout. Leading E. Rowan 40 by just nine points and in desperate foul trouble late the third quarter, West Rowan wiped out rival East Rowan 70-40 in the West gym on Thursday. The Mustangs (3-9, 1-3) made just two field goals in the second half (none in the fourth quarter) and were outscored 29-8 in the last 10 minutes of the NPC contest. “We had a good combination on the floor in the third quarter to play man-to-man and we played our best man defense all season,” West coach Erich Epps said. “We had some girls that were really moving their feet.”
tyler buckwell/sALisBUrY Post
West rowan’s tabitha Ball, left, and shay steele, center, clamp down on east rowan’s taylor Honeycutt. West got 17 points from Ayana Avery and 13 from Brittney Barber. Olivia Sabo
scored 13 for East. It was an even game in the first quarter with East getting 3-pointers from Sabo, Ashley Goins and Mallory Drew. West (10-4, 3-1) was clinging to a 22-20 lead late in the first half when Avery caught fire. In a span of 84 seconds, she drilled three straight 3s. “Sometimes it just comes, and it came,” said Avery, who has 1,728 career points. “I started making some shots.” Avery ended the half with a behind-the-back dribble and a running scoop that beat the horn for a 35-27 West lead. “Just saw the defenders and was able to avoid them and hit the shot,” Avery said. Still, East, playing without 6-foot-3 freshman Karleigh Wike (elbow) appeared in decent shape with 3:18 left in the
tyler buckwell/sALisBUrY Post
West rowan’s Brittney Barber, left, who finished with 13 points, See WEST GIRLS, 3B tries to gain ground on east rowan’s steffi sides.
2B • FRIDAY, JANUARY 7, 2011 4A Central Piedmont
TV Sports Friday, Jan. 7 BOXING 10 p.m. ESPN2 — Ruslan Provodnikov (17-0-0) vs. Mauricio Herrera (15-1-0), for the vacant WBC Continental America’s and USBA light welterweight title, at Las Vegas COLLEGE FOOTBALL 7 p.m. ESPN2 — NCAA, FCS tournament, championship game, Delaware vs. E. Washington, at Frisco, Texas 8 p.m. FOX — Cotton Bowl, LSU vs. Texas A&M, at Arlington, Texas GOLF 5:30 p.m. TGC — PGA Tour, Tournament of Champions, second round, at Maui, Hawaii NBA BASKETBALL 8 p.m. ESPN — Houston at Orlando 10:30 p.m. ESPN — New York at Phoenix
Area schedule Friday, January 7 PREP BASKETBALL 6 p.m. North Rowan at Chatham Central Salisbury at West Davidson Mount Tabor at Davie 6:30 p.m. Carson at West Iredell East Rowan at North Iredell South Rowan at Statesville Hickory Ridge at A.L. Brown 7 p.m. Academy of Excellence at North Hills (boys) PREP WRESTLING 6:30 p.m. North Iredell at East Rowan Carson at West Iredell A.L. Brown at Mooresville TBA South Rowan in Boneyard Bash (Fayetteville) PREP SWIMMING TBA Salisbury at Davie Central, Robinson, A.L. Brown at WCY
Prep wrestling Middle school Corriher-Lipe 66, Knox 27 83 — Fields (CL) won by forfeit 93 — Winfield (K) d. Ozona 8-4 103 — Durham (CL) won by forfeit 112 — Ruiz (CL) p. Clark, 3rd 119 — Jackson (K) p. Livengood, 2nd 125 — Viars (CL) p. Brown, 1st 130 — Coleman (K) p. C. York, 2nd 135 — N. York (CL) p. Ralston, 3rd 140 — Turner (CL) won by forfeit 145 — Littlejohn (CL) won by forfeit 152 — Oglesby (K) p. Sanchez, 2nd 160 — Barton (K) p. Urey, 2nd 171 — Cop (CL) won by forfeit 189 — Parham (CL) won by forfeit 215 — Milem (CL) p. Stiller, 3rd Hwt — Stancil (CL) won by forfeit
Prep hoops Standings 1A Yadkin Valley Boys North Rowan Albemarle West Montgomery North Moore Chatham Central South Davidson East Montgomery Gray Stone South Stanly
YVC 5-0 2-0 5-1 3-1 3-3 2-4 1-3 1-4 0-6
Overall 9-3 4-1 5-4 6-4 4-7 5-6 2-4 2-9 0-9
Overall Girls YVC Chatham Central 6-0 8-2 Albemarle 2-0 3-2 North Moore 3-1 6-2 3-2 4-8 North Rowan South Stanly 3-3 3-7 East Montgomery 2-2 2-4 2-4 4-7 South Davidson West Montgomery 1-5 1-8 Gray Stone 0-5 0-8 Wednesday’s game North Stanly 64, Albemarle 55 Friday’s games Gray Stone at East Montgomery North Moore at South Stanly North Rowan at Chatham Central Albemarle at West Montgomery
2A Central Carolina Boys CCC Overall 0-0 7-4 Salisbury East Davidson 0-0 8-5 Central Davidson 0-0 6-5 0-0 4-5 West Davidson Lexington 0-0 4-8 Thomasville 0-0 3-8 Wednesday’s games Salisbury 59, West Rowan 52 East Davidson 60, Randleman 46 Oak Ridge 71, Lexington 49 Wheatmore 47, Thomasville 31 Overall CCC Girls Thomasville 0-0 11-1 Salisbury 0-0 9-1 0-0 9-2 Central Davidson 0-0 10-3 East Davidson Lexington 0-0 6-5 West Davidson 0-0 1-7 Wednesday’s games Salisbury 72, West Rowan 44 East Davidson 59, Randleman 46 Oak Ridge 66, Lexington 37 Thomasville 60, Wheatmore 45 Friday’s games Lexington at East Davidson Thomasville at Central Davidson Salisbury at West Davidson
3A North Piedmont Boys NPC Overall Statesville 4-0 9-3 3-1 5-8 West Rowan Carson 3-2 6-8 West Iredell 2-2 7-6 2-2 5-7 North Iredell South Rowan 0-3 3-10 East Rowan 0-4 0-12 Wednesday’s game Salisbury 59, West Rowan 52 Thursday’s game West Rowan 59, East Rowan 47 Girls NPC Overall North Iredell 4-0 11-1 Carson 4-1 10-4 West Rowan 3-1 10-4 South Rowan 1-2 4-8 East Rowan 1-3 3-9 West Iredell 1-3 2-10 Statesville 0-4 0-12 Wednesday’s game Salisbury 72, West Rowan 44 Thursday’s game West Rowan 70, East Rowan 40 Friday’s games Carson at West Iredell South Rowan at Statesville East Rowan at North Iredell
3A South Piedmont Boys SPC Overall Concord 4-0 11-1 A.L. Brown 4-0 8-2 NW Cabarrus 4-1 9-5 Hickory Ridge 3-1 8-4 Central Cabarrus 1-3 7-5 Cox Mill 1-4 3-10 Robinson 0-4 4-7 Mount Pleasant 0-4 4-8 Wednesday’s games NW Cabarrus 44, Cox Mill 37 West Stanly 65, Mount Pleasant 58 Girls SPC Overall Hickory Ridge 4-0 8-4 Concord 4-0 6-5 Robinson 3-1 9-3 A.L. Brown 2-1 5-5 NW Cabarrus 2-3 3-8 Mount Pleasant 1-3 7-6 Cox Mill 0-4 1-10 Central Cabarrus 0-4 0-8 Wednesday’s games NW Cabarrus 49, Cox Mill 24 Mount Pleasant 66, West Stanly 56 Friday’s games NW Cabarrus at Central Cabarrus Robinson at Cox Mill Mount Pleasant at Concord Hickory Ridge at A.L. Brown
Boys Reagan Davie County Mount Tabor R.J. Reynolds North Davidson West Forsyth
SALISBURY POST
SCOREBOARD CPC 1-0 1-0 0-0 0-0 0-1 0-1
Overall 12-0 12-1 12-1 3-7 7-4 5-6
Overall Girls CPC Mount Tabor 1-0 10-2 West Forsyth 1-0 8-2 1-0 5-6 Reagan R.J. Reynolds 0-1 7-3 North Davidson 0-1 5-6 0-1 5-9 Davie County Friday’s games Mount Tabor at Davie Reagan at West Forsyth R.J. Reynolds at North Davidson
College hoops Standings SAC SAC Overall Lincoln Memorial 3-0 11-0 2-1 7-4 Wingate Anderson 2-1 8-5 Brevard 1-1 3-3 1-1 4-9 Tusculum Newberry 1-2 6-5 Catawba 1-2 5-6 1-2 4-7 Carson-Newman Mars Hill 1-2 4-7 Lenoir-Rhyne 1-2 2-9 Saturday’s games Lincoln Memorial at Newberry Tusculum at Wingate Mars Hill at Brevard Catawba at Anderson Carson-Newman at Lenoir-Rhyne
Conference Carolinas CC Overall 4-0 9-2 Limestone Pfeiffer 4-0 6-4 Queens 3-0 7-4 2-2 7-5 Barton Coker 2-2 3-7 Mount Olive 1-2 6-5 1-2 4-6 St. Andrews Belmont Abbey 1-3 5-6 Lees-McRae 0-3 3-7 0-4 0-8 Erskine
ACC ACC Overall Duke 1-0 14-0 Boston College 1-0 11-4 1-0 11-4 Florida State Virginia 1-0 10-5 North Carolina 0-0 10-4 0-0 10-4 N.C. State Georgia Tech 0-0 7-6 Wake Forest 0-0 7-8 0-1 11-4 Clemson Miami 0-1 11-4 Maryland 0-1 10-4 0-1 9-4 Virginia Tech games Maryland at Duke, 8 p.m., FSN Jan. 11 Georgia Tech at Clemson, 7 p.m., RSN N.C. State at Boston College, 9 p.m., ESPNU
Southeastern Eastern SEC Overall Kentucky 0-0 12-2 0-0 11-2 Georgia Vanderbilt 0-0 11-2 Florida 0-0 10-3 0-0 10-4 Tennessee South Carolina 0-0 9-4 Western SEC Overall 0-0 11-3 Mississippi Arkansas 0-0 10-3 Mississippi State 0-0 8-6 0-0 8-6 Alabama LSU 0-0 8-7 Auburn 0-0 7 Cent. Conn. St. 61, St. Francis, NY 43 Long Island U. 75, Bryant 55 Quinnipiac 72, Monmouth, N.J. 70 Vermont 60, Albany, N.Y. 48 Wagner 83, Robert Morris 78, OT SOUTH Alabama St. 50, Grambling St. 47 Coastal Carolina 109, VMI 87 Coll. of Charleston 76, Furman 72 Denver 62, W. Kentucky 59 E. Kentucky 64, Jacksonville St. 61 Fla. International 75, Arkansas St. 70 Florida Atlantic 65, South Alabama 57 Fresno St. 63, Louisiana Tech 56 Liberty 68, Charleston Southern 54 Morehead St. 76, Tennessee Tech 64 Murray St. 64, Tennessee St. 53 Presbyterian 78, Gardner-Webb 44 Samford 68, UNC Greensboro 64 UNC Asheville 88, Winthrop 67 Villanova 83, South Florida 71 Wofford 78, The Citadel 60 MIDWEST Cincinnati 66, Xavier 46 Detroit 83, Loyola of Chicago 71 Illinois 88, Northwestern 63 N. Dakota St. 80, Oral Roberts 74 Wright St. 71, Ill.-Chicago 63 FAR WEST Cal Poly 43, Pacific 39 Montana St. 61, Sacramento St. 59 N. Arizona 82, Idaho St. 80, OT Stanford 55, Arizona St. 41 UC Santa Barbara 77, UC Davis 65 Washington 87, Oregon 69 Washington St. 84, Oregon St. 70 Thursday, Jan. 6 GoDaddy.com Bowl
Miami, O. 35, Middle Tennessee 21 Friday, Jan. 7 Cotton Bowl Texas A&M (9-3) vs. LSU (10-2), 8 p.m. (FOX))
GoDaddy Bowl Miami (O) 35, Mid. Tenn. 21 Middle Tennessee 14 0 7 0 — 21 Dolphins (Ohio) 7 7 14 7 — 35 First Quarter MTSU—Tanner 18 run (Gendreau kick), 4:37. MiO—Merriweather 3 run (Cook kick), 2:29. MTSU—Dasher 49 run (Gendreau kick), :40. Second Quarter MiO—Merriweather 3 run (Cook kick), 13:11. Third Quarter MiO—Nunley 52 interception return (Cook kick), 13:22. MTSU—Tanner 54 run (Gendreau kick), 12:32. MiO—Givens 17 pass from A.Boucher (Cook kick), :54. Fourth Quarter MiO—Harwell 5 pass from A.Boucher (Cook kick), 5:25. A—38,168. MTSU MiO 15 21 First downs Rushes-yards 32-208 40-118 Passing 162 298 18-29-4 23-37-2 Comp-Att-Int Return Yards 0 168 Punts-Avg. 6-40.2 6-28.8 1-1 2-0 Fumbles-Lost Penalties-Yards 6-58 6-53 Time of Possession 21:15 38:45 INDIVIDUAL STATISTICS RUSHING—Middle Tennessee, Dasher 17-90, Tanner 11-87, Kyles 3-24, Cunningham 1-7. Dolphins (Ohio), Merriweather 27100, Robinson 4-23, A.Boucher 6-1, Woods 1-0, Team 1-(minus 1), Harwell 1-(minus 5). PASSING—Middle Tennessee, Dasher 18-29-4-162. Dolphins (Ohio), A.Boucher 22-35-2-289, Scherpenberg 1-1-0-9, Team 0-1-0-0. RECEIVING—Middle Tennessee, Tanner 5-34, Andrews 4-36, McDonald 3-43, Beyah 2-24, Blissard 2-20, Drake 2-5. Dolphins (Ohio), Harwell 7-86, Robinson 4-81, Givens 4-60, Paine 3-33, Merriweather 2-13, Bruton 1-14, Woods 1-7, Ju.Semmes 1-4. AP-WF-01-07-11 0510GMT
NHL
Standings EASTERN CONFERENCE Atlantic Division GP W L OT Pts GF 42 26 12 4 56 136 Pittsburgh Philadelphia 40 25 10 5 55 135 N.Y. Rangers 41 23 15 3 49 121 N.Y. Islanders 38 12 20 6 30 90 New Jersey 40 10 28 2 22 71 Northeast Division GP W L OT Pts GF Boston 39 21 12 6 48 111 Montreal 41 22 16 3 47 102 39 16 18 5 37 108 Buffalo Ottawa 40 16 19 5 37 90 Toronto 39 15 20 4 34 96 Southeast Division GP W L OT Pts GF Tampa Bay 41 24 12 5 53 123 Washington 41 23 12 6 52 120 43 22 15 6 50 134 Atlanta Carolina 39 18 15 6 42 112 Florida 38 18 18 2 38 104 WESTERN CONFERENCE Central Division GP W L OT Pts GF 40 25 10 5 55 138 Detroit Nashville 39 20 13 6 46 99 St. Louis 39 20 13 6 46 106 Chicago 42 21 18 3 45 130 40 20 17 3 43 103 Columbus Northwest Division GP W L OT Pts GF 39 26 8 5 57 134 Vancouver Colorado 41 21 15 5 47 136 Minnesota 40 20 15 5 45 103 41 18 20 3 39 108 Calgary Edmonton 39 13 19 7 33 100 Pacific Division GP W L OT Pts GF 41 24 13 4 52 118 Dallas San Jose 40 21 14 5 47 118 Phoenix 40 19 13 8 46 112 43 21 18 4 46 110 Anaheim Los Angeles 39 22 16 1 45 116 Thursday’s Games Toronto 6, St. Louis 5, SO Montreal 2, Pittsburgh 1, SO Minnesota 3, Boston 1 Philadelphia 4, New Jersey 2 Phoenix 2, Colorado 0 Edmonton 2, N.Y. Islanders 1 Nashville at Los Angeles, late Buffalo at San Jose, late.
GA 97 106 104 122 128 GA 88 97 118 121 118 GA 130 107 127 117 98 GA 113 94 110 122 118 GA 96 130 114 118 132 GA 113 112 115 123 96
NBA Standings EASTERN CONFERENCE Atlantic Division W L Pct GB Boston 27 7 .794 — 20 14 .588 7 New York Philadelphia 14 21 .400 131⁄2 Toronto 12 23 .343 151⁄2 10 25 .286 171⁄2 New Jersey Southeast Division W L Pct GB Miami 28 9 .757 — 23 12 .657 4 Orlando Atlanta 24 14 .632 41⁄2 CHARLOTTE 12 21 .364 14 8 25 .242 18 Washington Central Division W L Pct GB Chicago 23 11 .676 — Indiana 14 18 .438 8 Milwaukee 13 20 .394 91⁄2 Detroit 11 24 .314 121⁄2 Cleveland 8 27 .229 151⁄2 WESTERN CONFERENCE Southwest Division W L Pct GB San Antonio 29 6 .829 — Dallas 26 9 .743 3 New Orleans 21 15 .583 81⁄2 Houston 16 19 .457 13 Memphis 16 19 .457 13 Northwest Division W L Pct GB Utah 24 12 .667 — 1 ⁄2 Oklahoma City 24 13 .649 Denver 20 14 .588 3 Portland 19 17 .528 5 Minnesota 9 27 .250 15 Pacific Division W L Pct GB L.A. Lakers 25 11 .694 — Phoenix 14 19 .424 91⁄2 Golden State 14 21 .400 101⁄2 L.A. Clippers 11 24 .314 131⁄2 Sacramento 7 25 .219 16 Thursday’s Games Oklahoma City 99, Dallas 95 Denver at Sacramento, late.
Notable box Thunder 99, Mavericks 95 OKLAHOMA CITY (99) Durant 11-22 4-5 28, Green 7-17 2-6 16, Krstic 3-6 0-0 6, Westbrook 5-16 5-6 15, Sefolosha 1-2 1-2 3, Ibaka 6-6 1-3 13, Collison 3-3 0-0 6, Harden 1-6 4-4 7, Maynor 25 0-0 5. Totals 39-83 17-26 99. DALLAS (95)
Stevenson 5-12 0-0 14, Marion 12-17 12 25, Chandler 3-5 8-10 14, Kidd 0-7 0-0 0, Terry 9-16 1-1 19, Barea 5-11 2-3 14, Haywood 3-5 1-2 7, Cardinal 0-3 2-2 2, Jones 0-1 0-0 0, Mahinmi 0-2 0-0 0. Totals 37-79 15-20 95. Oklahoma City 23 28 22 26 — 99 Dallas 30 25 15 25 — 95 3-Point Goals—Oklahoma City 4-15 (Durant 2-6, Maynor 1-2, Harden 1-5, Westbrook 0-1, Green 0-1), Dallas 6-20 (Stevenson 4-8, Barea 2-2, Marion 0-2, Terry 0-2, Cardinal 0-2, Kidd 0-4). Fouled Out—Ibaka. Rebounds—Oklahoma City 48 (Krstic, Green 9), Dallas 52 (Chandler 18). Assists— Oklahoma City 23 (Westbrook 9), Dallas 18 (Kidd 7). Total Fouls—Oklahoma City 18, Dallas 17. A—20,282 (19,200).
Transactions BASEBALL American League BALTIMORE ORIOLES—Agreed to terms with 1B Derrek Lee on a one-year contract. CLEVELAND INDIANS—Designated INF-OF Jordan Brown for assignment. MINNESOTA TWINS—Announced the retirement of Twins Sports Inc. president Jerry Bell. TEXAS RANGERS—Agreed to terms with OF David Murphy on a one-year contract and with LHP Zach Jackson and OF Erold Andrus on minor league contracts. National League ATLANTA BRAVES—Agreed to terms with 2B Dan Uggla on a five-year contract. CINCINNATI REDS—Agreed to terms with RHP Jared Burton on a one-year contract. PHILADELPHIA PHILLIES—Agreed to terms with LHP J.C. Romero on a one-year contract. BASKETBALL National Basketball Association NBA—Promoted Kerry D. Chandler to executive vice president, Chris Granger to executive vice president, team marketing & business operations, and Danny Meiseles to executive vice president and executive producer, production, programming and broadcasting. MIAMI HEAT—Reassigned C Dexter Pittman to Sioux Falls (NBADL). WASHINGTON WIZARDS—Assigned C Hamady Ndiaye to Dakota (NBADL). FOOTBALL National Football League ARIZONA CARDINALS—Fired Bill Davis defensive coordinator. CLEVELAND BROWNS—Signed OL Branndon Braxton, OL Pat Murray, OL Phil Trautwein, RB Tyler Clutts and RB Quinn Porter, TE Tyson DeVree and DB DeAngelo Smith from practice squad. DALLAS COWBOYS—Named Jason Garrett coach. COLLEGE ARKANSAS—Announced QB Ryan Mallett will enter the NFL draft. MEMPHIS—Announced men’s basketball F Ferrakohn Hall transferred from Seton Hall. MISSISSIPPI STATE—Promoted Chris Wilson to defensive coordinator and Angelo Mirando to receivers coach. SMU—Signed athletic director Steve Orsini to a contract extension through May 2015. VIRGINIA TECH—Sophomore RB Darren Evans announced he’s entering the NFL draft. WISCONSIN—Announced DE J.J. Watt will enter the NFL draft.
Baseball Free Agent Signingsyear (4) — Signed Adam Dunn, 1b, Washington, to a $56 million, four-year contract; re-signed A.J. Pierzynski, c, to an $8 million, two-year contract; re-signed Paul Konerko, 1b, to a $37.5 million, threeyear contract; signed Jesse Crain, rhp, Minnesota, to a $13 million, threeyear (3) — Re-signed Erik Bedard, lhp, to a $1 million, one-year contractl; signed Miguel Olivo, c, Toronto, to a $7 million, two-year contract; re-signed Josh Bard, c,. NATIONAL LEAGUE ARIZONA . CHICAGO (2) — Signed Carlos Pena, 1b, Tampa Bay, to a $10 million, one-year contract; signed Kerry Wood, rhp, New York Yankees, to a $1.5; resigned Rod Barajas, c, to a $3.25 million, one-year contract; re-signed Vicente Padilla, rhp, to a $2 million, one-year contract; signed Matt Guerrier, rhp, Minnesota, to a $12 million, threeyear contract. PITTSBURGH (2) — Signed Kevin Correia, rhp, San Diego, to an $8 million, twoyear.
Blue Bears swept From staff reports
Livingstone’s men’s basketball team lost 62-60 at Elizabeth City State in a CIAA opener on Thursday. Livingstone (4-3) rallied from a 10point deficit in the second half to take the lead, but couldn’t hold it. Darius Cox’s runner with 33 seconds left gave the Blue Bears a 60-59 lead, but the Vikings got the winning points at the foul line. Donte Durant led Livingstone with 14 points. Greg Henry had 12, and Nasir Austin scored 11. Trent Bivens led the Vikings (7-2) with 14. LIVINGSTONE (60) — Durant 14, Henry 12, Austin 11, Johnson 7, Cox 6, Redfern 3, Taylor 3, Jackson 2, Adams 2. ELIZABETH CITY (62) — Bivens 14, Spady 13, Tucker 13, Cooke 8, Price 7, Goldsmith 5, White 2. Livingstone 21 Eliz. City State 28
39 34
— 60 — 62
Livingstone women fall Livingstone’s women’s basketball team lost its CIAA opener at Elizabeth City State 79-66 on Thursday. Rashida Elbourne and Brittany Wright scored 13 points each for the Blue Bears (5-3), while Kelcyn Manurs added 11. Kenyatta Gill scored 22 for the Vikings (8-3), and Shaquella Johnson added 20.
Pfeiffer men win
first overtime. Avery Locklear scored 22 points for the Yellow Jackets (9-2). Carolina Hubbard had 14, and Cassidy Chipman scored 10. Ashley Blaire had 16 points to lead the Trojans, and Demeria Robinson scored 15. Erwin’s girls rallied for a 42-30 win against Mooresville on Wednesday. Kelli Fisher led the Eagles (9-2) with a double-double — 17 points and 17 rebounds. Amani Ajayi had 10 points, six rebounds and four steals. Kaleigh Troutman added seven points and 16 rebounds. Erin Haley and Kennedy Lambert had eight rebounds apiece, and Hatley had five assists. Mooresville (2-10) was paced by Mercedes Lowe and Amber Sherrill with eight and seven points, respectively. Erwin’s boys stayed unbeaten with a 66-57 win against the Blue Imps. Samuel Wyrick scored 24 points for the Eagles (11-0) All the Erwin starters scored in double figures with Harrison Bell getting 12 points and Conor Honeycutt, Jack Weisensel and Seth Wyrick adding 10 each. Seth Wyrick scored all of his points in the final quarter as Erwin broke open a close contest. He also had six assists. Bell and Weisensel grabbed 11 and nine rebounds, respectively. Mooresville (7-4) was led by Tommy Bullock’s 15 points. Anthony Sherrill scored 14, and Jordan Vanderburg added 10 points. North Hills’ boys defeated Mooresville Christian 66-12. North Hills was led by Chris Norris’ 12 points while Jay Wood added nine. North (3-2) will play at Salisbury Academy on Monday.
Pfeiffer’s men’s basketball team rode an amazing effort by All-American Chris Woods to an 86-71 win against Conference Carolinas foe Mount Olive on Thursday at Merner Women’s basketball Gym. Bubbles Phifer (Salisbury) scored Woods had 30 points and a schoolrecord 20 rebounds. Davon Gilliard six points for Tallahassee Communiadded 18 points for the Falcons (6-4, ty College in a 66-49 loss to Gulf Coast 4-0 CC). Derek Staton led the Trojans CC on Tuesday. (6-5, 1-2) with 22 points.
Pfeiffer women lose
Pro basketball
Carsos Dixon (South Rowan) Pfeiffer’s women’s basketball scored 26 points for his team in Okiteam (3-7, 2-2) lost 76-69 to Mount nawa on Monday and is averaging Olive on Thursday despite 26 points 14.2 points per game. by Brittany Cox. Jasmine Whitby had 26 for the Tro- Men’s basketball jans (6-4, 3-1). Brevard freshman Darius Moose (Carson) has started every game for Middle school hoops the Tornados and averages 5.1 points Corriher-Lipe’s boys edged Knox and 5.6 rebounds per game. 72-68 on Wednesday. Qwantarius Rhyne scored 24 points to lead the Extreme Perfomance Yellow Jackets. Extreme Performance will be Chandler Corriher (16), Davonta Steele (15) and Burke Fulcher (14) holding its Winter Skills baseball also scored in double figures for the camp this weekend at Extreme Performance’s new business location at Yellow Jackets (6-5). A.J. Hill led the Trojans with 13 1504 Kentucky Street, Salisbury. The camp will be held Saturday points. Riley Myers (12), Malik White (11), Josh Billingslea (11) and Isaiah and Sunday. Athletes can register the Little (10) also scored in double fig- day of the camp. Several local pros will instruct. ures. Corriher-Lipe’s girls beat Knox Call Extreme Performance direc50-47 in double overtime, the first loss tor of baseball operations Chris of the season for the Trojans. Ahearn at 704-633-3200 for informaThe score was tied at 38 at the end tion. Extreme Performance’s open of regulation and was 44-all after the house is set for Jan. 15.
Panthers out of Luck CHARLOTTE 19year. The Panthers are eyeing NFL defensive coordinators as they seek to replace Fox, who was let go after nine seasons. San Diego’s Ron Rivera, Perry Fewell of the New York Giants,.” Harbaugh update MIAMI (AP) —.
SALISBURY POST
FRIDAY, JANUARY 7, 2011 • 3B
PREP/PRO/COLLEGE BASKETBALL
WEST BOYS FROM 1B
tyler buckwell/sALisBURY POst
cole Honeycutt, left, of east Rowan tries to glide past West Rowan’s Jarvis Morgan.
n
tyler buckwell/sALisBURY POst
east Rowan’s Avery Rogers inbounds the ball while being heckled by a host of West Rowan fans.. 2 5 E. Rowan W. Rowan 19 10
18 16
22 14
— —
47 59
Bearcats resume best start in history Associated Press
The college basketball roundup ... CINCINNATI — Yancy Gates scored a season-high 22 points, and 24th-ranked Cincinnati extended the second-best start in school history, beating Xavier 66-46 on Thursday night Cincinnati’s 15-0 start matches the 1998-99 team for second-best in school history. No matter the circumstance, Xavier (8-5) had managed to get the better of its crosstown rival for years. The Musketeers had won three in a row and eight of 11 in the series, which often gets overheated. Xavier’s Terrell “Tu” Holloway got a technical for throwing an elbow Thursday. None of the Musketeers could stop Gates, a 6-foot-9, 265-pound power forward who scored most of his points on outside jumpers. He went 10 of 16 from the field and had 14 rebounds. Xavier’s only consistent scorer was forward Jamel McLean, who had 18 points. Holloway, the Musketeers’ leading scorer at 21.3 points per game, managed only five on 2-of-13 shooting. No. 7 Villanova 83, South Florida 71 TAMPA, Fla. — all nine of the shots they attempted behind the arc. Augustus Gilchrist led the Bulls (6-10, 0-3) with 16 points and 10 rebounds. South Florida has dropped five straight despite showing signs of improvement. No. 23 Washington 87, Oregon 69 SEATTLE — Freshman Terrence Ross scored a season-high 25 points and No. 23 Washington shut down Oregon in the final 12 minutes to improve to 3-0 in Pac-10 play for the first time in six seasons. Ross hit 11 of 18 shots, capping the night with a lob dunk off a pass from Isaiah Thomas. Ross previous high was 18 points in an overtime victory at Southern California. Thomas had 20 points, nine assists and six rebounds for the Huskies (11-3). Joevan Catron led Oregon (7-8, 0-3) with 20 points. Ross hit 11 of 18 shots, capping the night with a lob dunk off a pass from Thomas. Ross previous high came just over a week ago when he scored 18 points in an overtime victory at USC.
Nycieko dixon of West Rowan finishes a layup while east east Rowan’s Olivia sabo and West Rowan’s Allison Parkerbattle it out in a scrum for a loose ball. Rowan’s steffi sides defends.
WEST GIRLS FROM 1B third quarter when Drew grabbed an offensive rebound and drew the fourth foul on West shot-blocker Shay Steele. Steele joined starting post Tabitha Ball, who already had four fouls, on the bench. Drew made one free throw to cut West’s lead to 41-32, but West guard Nycieko Dixon got loose for two quick tran-
Thunder tops Dallas Associated Press
DALLAS — Kevin Durant scored 28 Okla. City 99 p o i n t s , Dallas 95 R u s s e l l.
tyler buckwell/sALisBURY POst
tyler buckwell/sALisBURY POst
sition buckets. Then West’s defense, which got a lift from Allison Parker and Alison Sobataka, clamped down, and the Falcons steadily pulled away. “The gameplan was to drive it at them and get them in foul trouble, and it really worked,” East coach Danielle Porter said. “But it’s like we lost our legs in the second half. We started missing layups and stopped jumping for rebounds. I lost track of how many times West got four and five attempts to score.” West did just about everything right
in the second half. “The first half, we were doing a lot of dribbling up top and didn’t look like much,” Epps said. “But the second half, we gave the ball up, played defense and looked like a pretty good team.” EAST ROWAN (40) — Sabo 13, Goins 9, Drew 8, Honeycutt 5, Fry 3, Poole 1, Sides 1, Lowe, Rummage. WEST ROWAN (70) — Avery 17, Barber 13, Steele 10, Dixon 8, Caldwell 6, Ball 6, Watson 3, Sobataka 3, Dutton 2, Miller 2, Parker. E. Rowan 9 18 W. Rowan 10 25
7 14
6 21
— —
40 70
Duke women win, Heels fall Associated Press
AssOciAted PRess
duke’s Karima christmas, center, attempts a shot against Maryland.
DURHAM — 200607. Georgia Tech 71, UNC 70 ATLANTA — Met.
4B • FRIDAY, JANUARY 7, 2011
Miami (OH) downs MTSU in GoDaddy bowl
Miles focused on game, not Michigan Associated Press
AssociAted Press
Associated Pres
Miami (oH) quarterback Austin Boucher, right, outruns MOBILE, Ala. — Austin Middle tenn.’s dwight smith.
Boucher threw for 289 yards and two touchdowns in his fourth career start and Miami of Ohio Miami (OH) 35 capped a Middle Ten. 21 h i s t o r i c turnaround season with a 35-21 win Thursday night over Middle Tennessee in the GoDaddy.com Bowl. The RedHawks (10-4) are the first team in Football Bowl Subdivision history to win 10 games one season after losing 10. Miami finished a dismal 111
SALISBURY POST
SPORTS DIGEST
them, recovering a fumble and returning an interception 52 yards for a touchdown. Thomas Merriweather rushed for 100 yards and two touchdowns. MTSU’s Dwight Dasher threw four second-half interceptions.
The college football notebook ... IRVING, Texas —. “I’m really here to MILES speak about no other school. I’m really here to speak about LSU,” said Miles, whose 11th-ranked Tigers (10-2) play No. 18 Texas A&M tonight at Cowboys Stadium..” MORE COTTON IRVING, Texas — LSU is going for its sixth 11-win season, and fourth under Miles, Texas A&M, playing in January for the first time since the 2005 Cotton Bowl, has a six-game winning streak since losing three in a row, a stretch that included a loss to Arkansas in Cowboys Stadium. Ryan Tannehill is 5-0 since taking over as Texas A&M's starting quarterback. The last Aggies quarterback to win his first five games was Bucky Richardson, whose streak included the 1988 Cotton Bowl. LSU's next game will also be at Cowboys Stadium. The Tigers open the 2011 season against Oregon. FCS TITLE GAME TONIGHT FRISCO, Texas — A tonight when Devlin leads perennial Delaware against Mitchell and first-time finalist Eastern Washington. Mitchell's college career began at SMU, about 20 miles from the suburban Dallas stadium hosting the game. Devlin transferred from Penn State
Cable’s firing was surprise after Oakland’s 8-8 season Associated Press
The NFL notebook ... ‘. COWBOYS HIRE GARRETT IRVING, Texas — Jason Garrett nailed his audition. He gets to remain coach of the Dallas Cowboys. Garrett was announced as the new head coach at a news conference at Cowboys Stadium on Thursday afternoon.. WADE TO TEXANS HOUSTON — W line-
HOMELESS FroM 1B
AssociAted Press
oakland coach tom cable was all smiles at his last raiders press conference. backer. HARBAUGH UPDATE MIAMI— Two people with knowledge of the situation say Stanford coach Jim Harbaugh is set to meet Miami Dolphins officials in the San Francisco area. Tony Sparano is still the Dolphins' coach, but owner Stephen Ross flew to California to visit Harbaugh on Thursday. A day earlier, Harbaugh met with the San Francisco 49ers about their coaching vacancy. MULARKEY SNUBS DENVER ENGLEWOOD, Colo. — Atlanta Falcons offensive coordinator Mike Mularkey has canceled his interview with the Denver Broncos, who wanted to talk to him
about their head coaching vacancy. BYE, VINCEyear-old owner decided Young no longer is the quarterback for his franchise. Young is 30-17 in his five NFL seasons, but only 13-14 against teams finishing a season at .500 or better.
Grizzlies ban gambling after fight on airplane Associated Press
MEMPHIS, Tenn. — Memphis Grizzlies coach Lionel Hollins banned gambling on team flights after a fight between Tony Allen and O.J. Mayo on board an airplane. Team spokesman Dustin Krugel said the Grizzlies will allow “no more gambling” on flights. Their next road trip begins Friday night after hosting the Utah Jazz. The team released a statement morning confirming that Allen and Mayo had a “brief altercation” on the charter flight back to Memphis on Monday from Los Angeles. The Grizzlies spent the night in California after beating the Lakers 104-85 on Sunday.
CYCLING SYDNEY — Seven-time Tour de France winner Lance Armstrong said he is not affected on a daily basis by an ongoing U.S. federal investigation into drug use
by cyclists. In an interview in the Sydney Morning Herald — his first newspaper interview since July — Armstrong spoke of problems affecting cycling but would not elaborate on the Food and Drug Administration investigation.
HOCKEY BUFFALO, N.Y. — Artemi Panarin scored twice and Russia overcame a threegoal deficit in the third period to stun Canada 5-3 to win gold at the World Junior Hockey Championships.
OLYMPICS LONDON — ESPN, Fox and the other main contenders for U.S. television rights have shown interest in buying a package covering four Olympics rather than the usual two-games deal. The International Olympic Committee had been planning to auction only the lucrative rights to
to Delaware. AUBURN DEFENSE PREPARES SCOTTSDALE, Ariz. — J." LEGRAND UPDATE PISCATAWAY, N.J. — Injured Rutgers football player Eric LeGrand has movement in his shoulders and sensation throughout his body. It marked the first update in LeGrand's condition since last month when the university announced that the defensive tackle had some feeling in his hands. The 20-year-old was hurt on Oct. 16, making a tackle on a kickoff return against Army in a game at New Meadowlands Stadium.
the 2014 Winter Olympics in Sochi, Russia, and the 2016 Summer Games in Rio de Janeiro.
SOCCER SAN FRANCISCO — Landon Donovan has been honored as the U.S. player of the year for a record seventh time by Futbol de Primera.
TENNIS HONG KONG — Venus Williams lost to secondranked. —. Canadiens 2, Penguins 1 MONTREAL — Benoit Pouliot scored on Montreal. Wild 3, Penguins 1 BOSTON (AP) — Wild forward Cal Clutterbuck scored the go-ahead goal in the third period on Thursday night and Minnesota held on to beat Boston 3-1.
voiced.
5B • FRIDAY, JANUARY 7, 2011
SALISBURY POST
CLASSIFIED Autos
Autos
Autos
Autos
Autos
ELLIS AUTO AUCTION 10 miles N. of Salisbury, Hwy 601, Sale Every Wednesday night 6 pm.
More Details = Faster Sales!
Suburu Impreza 2.5i Sedan, 2009. Spark Silver Metallic exterior w/carbon black interior. #T10726A. Stock $16,559.
Chevrolet, 1981, truck. ½ ton, 4 wheel drive. 4 speed. 6 cylinder. Needs engine repair. Call 704279-5765 or 704-2024281
Trucks, SUVs & Vans
Ford F-150 XLT Crew Cab, 2010. Sterling gray metallic exterior w/medium stone/ stone interior. Stock #P7604. $25,359. 1-800542-9758
Trucks, SUVs & Vans
Jeep Wrangler Sahara, 1999, Gold w/Tan cloth interior 4.0 6 cyl. auto trans, am/fm/cd, HARD TOP, aftermarket rims good tires, sound bar, BRUSH GUARD ready for fun or those snowy days! 704-603-4255
BATTERY-R-US
BMW, 2005 325i Midnight Black on tan leather 2.5 V6 auto trans, am, fm, cd, sunroof, dual seat warmers, all power, duel power seats, RUNS & DRIVES NICELY!! 704-603-4255
We are in need of inventory and will pay top dollar for your vehicle. Cash on the spot with title in hand. We can also refinance your current auto loan and lower your payment. Please call 1-800-542-9758
Dodge, 2007, Caliber. 100% Guaranteed Credit Over 150+ Approval! Vehicles in Stock! 1330 W. Jake Alexander Blvd.
Financing Available!
Hyundai, 2006, Sonata GLS/LX. 100% Guaranteed Credit Approval! Over 150+ Vehicles in Stock!
Buick LaCrosse CXS Sedan, 2005. Black onyx exterior w/gray interior. Stock #F11096A. $10,959. 1-800-542-9758
Buick Skylark 1991, automatic, clean, V-6, well equipped, only 71K miles. $2,000. 704-636-4905 Dealer 17302
Ford Focus SE Sedan, Stock #P7597. 2009. Brilliant silver exterior with medium stone interior. $10,559. 1-800-542-9758
Jaguar S-Type, 2005. Black w/black leather interior, 6 sp. auto trans, 4.2L V8 engine, AM/FM/CD Changer, Premium Sound. Call Steve today! 704-6034255
Saturn Aura XR, 2008, Silver with Grey cloth interior 3.6 V6 auto trans, all opts, onstar, power am,fm,cd, rear audio, steering wheel controls, duel power and heated seats, nonsmoker LIKE NEW!!!! 704-603-4255
Saturn ION 2 Sedan, 2006. Stock # F10530A. Cypress Green exterior with tan interior. $6,959 Call Now 1-800-542-9758..
Ford Focus SES Sedan, 2006. Liquid gray clearcoat metallic exterior w/dark flint interior. Stock #F10444A. $8,259. 1-800-542-9758
Ford Focus ZX3 Base 2004. Silver Metallic w/gray interior, est. 33 mpg, automatic transmission. 704-603-4255
Chevrolet Malibu LS Sedan, 2005. White exterior w/neutral interior. Stock #F11109A. $8,459. 1-800-542-9758.
Ford, 2006 Fusion SE. 100% Guaranteed Credit Approval! Over 150+ Vehicles in Stock! 1330 W. Jake Alexander Blvd.
Toyota Corolla CE Sedan, 1997. Cashmere beige metallic exterior w/oak interior. Stock #F10541A2. $6,759. 1-800-542-9758.
Mercedes S320, 1999 Black on Grey leather interior, 3.2, V6, auto trans, LOADED, all power ops, low miles, SUNROOF, chrome rims good tires, extra clean MUST SEE! 704-6034255
Chevrolet Malibu LT Sedan, 2008. Imperial Blue Metallic exterior w/titanium interior. Stock #P7562B. $12,359. 1-800-542-9758
$69.95 Faith Rd. 704-213-1005
Chevrolet, 2005, Colorado 100% Guaranteed Credit Approval! Over 150+ Vehicles in Stock! 1330 W. Jake Alexander Blvd.
Jeep, 2003, Wrangler Sahara. 100% Guaranteed Credit Approval! 150+ Vehicles in Stock!
Scion xA Base Hatchback, 2006. Silver streak mica exterior w/ dark charcoal interior. Stock # F10460A. $11,759. 1-800-542-9758
Toyota, 2005 Camry, LE/XLE/SE. 100% Guaranteed Credit Approval! Over 150+ Vehicles in Stock! 1330 W. Jake Alexander Blvd.
Nissan, 1997 transmission. Low miles. $200. Please Call 704-314-7846
Transportation Dealerships CLONINGER FORD, INC. “Try us before you buy.” 511 Jake Alexander Blvd. 704-633-9321
Chevrolet, 2005, Tahoe. 100% Guaranteed Credit Approval! Over 150+ Vehicles in Stock! 1330 W. Jake Alexander Blvd.
Ford Ranger Extended Cab XLT, 2004. Oxford White with gray cloth. 5 speed auto. trans. w/OD 704-603-4255
Jeep, 2007, Compass Sport. 100% Guaranteed Credit Approval! Over 150+ Vehicles in Stock!
TEAM CHEVROLET, CADILLAC, BUICK, GMC. 704-216-8000
Volvo V70, 2.4 T, 2001. Ash Gold Metallic exterior with tan interior. 5 speed auto trans. w/ winter mode. 704-603-4255
Volvo, 2006 S60 2.5T Onyx black with cream leather interior, sunroof, cd player, all power, alloy wheels, super nice! 704-603-4255
Transportation Financing
900 CCA
Ford F-250 Super Duty Lariat 4 Door Crew Cab, 2006. Dark shadow gray clearcoat exterior w/medium flint interior. #F10422A. Stock $18,959. 1-800-542-9758
Chevrolet 350, complete motor throttle body and transmission. Motor $300, Transmission $200. Call 704-314-7846
HONDA, 2003, ACCORD EX. $500-800 down, will help finance. Credit, No Problem! Private party sale. Call 704-838-1538
BIG TRUCK BATTERIES.
Call Steve today! 704-603-4255
Chevrolet, 2006, Equinox LT. 100% Guaranteed Credit Approval! Over 150+ Vehicles in Stock! 1330 W. Jake Alexander Blvd.
Chevy Suburban 2006 Dark Blue metallic w/tan leather interior, 4 speed auto trans, am, fm, cd premium sound. Third row seating, navigation, sunroof, DVD. 704-603-4255
Dodge, 2004 Dakota. 100% Guaranteed Credit Approval! Over 150+ Vehicles in Stock! 1330 W. Jake Alexander Blvd.
Ford Ranger Extended Cab, 2010. Dark shadow metallic exterior gray w/medium dark flint. Stock #F10496A. $17,559. 1-800-542-9758. Suzuki XL7 Luxury SUV 2007. Stock #F10395A. Majestic silver exterior with gray interior. $15,959 1-800-542-9758
Ford, 2003, Explorer. 100% Guaranteed Credit Approval! Over 150+ Vehicles in Stock! 1330 W. Jake Alexander Blvd.
Ford, 2005, Excursion, Eddie Bauer edition. 70,000 miles. V-10. Automatic. Loaded. DVD player. CD player. Adjustable pedals. Front & rear air. 3rd row seat. Very clean. $14,500. 704-637-7327
Toyota 4Runner SR5 SUV, 2008. Salsa red pearl exterior w/stone interior. Stock #T11212A. $26,359. 1-800-542-9758
Bad Credit? No Credit? No Problem! Tim Marburger Dodge 877-792-9700
Trucks, SUVs & Vans
Ford Expedition Eddie Bauer SUV, 2006. Black clearcoat exterior parchment w/medium interior. Stock #F11093A. $17,759. 1-800-542-9758
Honda Element LX SUV, 2008. Tango Red Pearl exterior w/Titanium/Black interior. Stock #T10724A. $15,159. 1-800-542-9758 Toyota Highlander Hybrid SUV, 2006. Millennium silver metallic exterior w/ash interior. Stock #T11108A. $16,459. 1-800-542-9758
We Do Taxes!! Over 150 vehicles in Stock! Honda Civic EX, 2000. Green on Grey cloth interior 4 cylinder auto trans, pwr options, SUNROOF, am/fm/cd, good tires, GREAT GAS SAVER!!!! 704-603-4255
Nissan Maxima 3.5 SE, 2005. Automatic, moonroof, power options. Excellent condition. Call Steve at 704-603-4255
Chevrolet, 2006, Impala. 100% Guaranteed Credit Approval! Over 150+ Vehicles in Stock! 1330 W. Jake Alexander Blvd. Hyundai Accent GLS Sedan, 2009. Stock # P7572. Nordic white exterior with gray interior. $10,559. 1-800-542-9758
Nissan, 2004, Maxima. 100% Guaranteed Credit Approval! Over 150+ Vehicles in Stock! 1330 W. Jake Alexander Blvd.
Collector Cars
Open Sundays 12pm-5pm Over 150 vehicles in Stock! Autos
Dodge Neon SXT, 2005. Automatic, power package, excellent gas saver. Call Steve at 704-603-4255
CASH FOR YOUR CAR! We want your vehicle! 1999 to 2011 under 150,000 miles. Please call 704-216-2663 for your cash offer.
Dodge, 2005, Magnum SE. 100% Guaranteed Credit Approval! Over 150+ Vehicles in Stock!
Collector Cars
Buick, 2006, Rendezvous. 100% Guaranteed Credit Approval! Over 150+ Vehicles in Stock!
Chevrolet Avalanche 1500 LS Crew Cab, 2007. Gold mist metallic exterior w/dark titanium interior. Stock #T11201A. $22,959. 1-800-542-9758
Ford Explorer Sport Trac XLT SUV, 2007. Red fire clearcoat exterior w/camel interior. Stock #F10543A. $19,959. 1-800-542-9758
Ford Explorer XLT SUV, 2004. Black clearcoat exterior w/midnight gray exterior. Stock #F10521B. $11,459. 1-800-542-9758
Ford Explorer XLT SUV, 2007. Red fire metallic clearcoat exterior w/black/stone interior. Stock# F10127A. $17,459. 1-800-542-9758
Jeep Wrangler Unlimited, 2005. Bright Silver Metallic exterior with black cloth interior. 6-speed, hard top, 29K miles. Won't Last! Call Steve today! 704-603-4255
Open Sundays 12pm-5pm Over 150 vehicles in Stock!
Honda Pilot 2005. Red Pearl with tan leather interior, automatic, 3rd row seating, 4x4, sunroof. 704-603-4255
Toyota RAV4 Base SUV, 2007. Classic silver metallic exterior w/ash interior. Stock #T11153A. $16,259. 1-800-542-9758
Jeep Grand Cherokee Laredo SUV, 2010. Brilliant black crystal pearlcoat exterior w/dark slate gray interior. Stock # F10541A1. $25
Jeep Grand Cherokee Limited, 2004. Bright silver metallic exterior with gray leather interior. Auto, 4x4, heated seats, sunroof. Call 704-603-4255
Want to Buy: Transportation Wanted: Mini Cooper, six speed. Call Chip 704640-5778 Leave message if no answer
There is a NEW group of people EVERY day, looking for a DEAL in the classifieds.
Weekly Special Only $17,995
To place an ad call the Classified Department at 704-797-4220
Buick Rainier CXL Plus SUV, 2004. Olympic white exterior w/light cashmere interior. Stock # T11111C. $11,459. 1-800-542-9758
Toyota 4 Runner, 1997 Limited Forest Green on Tan Leather interior V6 auto trans, am, fm, cd, tape, SUNROOF, alloy rims, good tires, CHEAP TRANSPORTATION!!!! 704-603-4255
Chevrolet Trailblazer LS SUV, 2006. Silverstone metallic exterior w/light gray interior. Stock #T10295A. $11,959. Call now 1-800-542-9758
Ford F-150 XL Extended Cab, 2003. Oxford white clearcoat exterior w/ medium graphite interior. Stock #F10512A 1-800-542-9758
Need customers? We’ve got them. The Salisbury Post ads are read daily in over 74% of the area’s homes!
We Do Taxes!! Over 150 vehicles in Stock!
6B • FRIDAY, JANUARY 7, 2011 Drivers
Employment
Want to attract attention? ★★★★
Get Bigger Type! $10 to start. Earn 40%. Call 704-754-2731 or 704-607-4530
You can drive a truck and have a home life We operate primarily in SE TN, AL, GA, KY and NC and VA. Two years tractor-trailer experience required. Must be DOT qualified and have a Safe Driving Record.
Please Call 1-800-849-5378
Driver
Drivers Regional Van Drivers. 35 - 37 cpm based on experience. BCBS Benefits Package. Home EVERY Week. CDL-A with 1 year experience required. Call 888362-8608, or apply at. Equal Opportunity Employer.
C39714
Drivers
Ads placed by telephone are read back at time of placement. Read your ad carefully the FIRST DAY it appears. Report any errors before the deadline for the next day’s paper (see “Deadlines”). The Salisbury Post assumes no financial responsibility for errors nor for omission of copy. Liability for errors shall not exceed charge for the space occupied by the error, nor for more than one incorrect insertion. For the mutual protection of this newspaper, its advertisers and its readers, the Salisbury Post reserves the right to classify, revise or decline any advertisement.
Employment
Other
Project/Program Director
REEFER, TANKER & FLATBED Drivers Needed! Prime's extensive freight network offers you: Plenty of Miles. Steady Freight. Call Prime Today. 1800-277-0212.
Town of Landis
RN's, LPN's & PRN's needed all shifts. Competitive wages. Please submit resume to NC Veteran's Home, 1601 Brenner Ave., Building 10, Salisbury, NC 28145.
Military
National Guard. 90+ college credits? Serve one weekend a month as a National Guard Officer. 16 career fields, $50,000 student loan repayment, bonus, benefits, tuition assistance, more! robert.bumgardner@us.army.mil Sales
Able to travel. Hiring 10 people to demonstrate household products. Free to travel all states, resort areas. No experience necessary. Paid training / transportation. OVER 18. Start ASAP. 1-866-734-5216. Sales
Independent Contractors Contour Beds offers: No Prospecting, Pre-set, Pre-qualified Appointments, Paid Presentations plus Commission, Earned Signing Bonus, $60k to $90k Potential 1st year. Apply at 1-866475-4911.
Industrial Customer Service
RUSHCO MARKETS IS
NOW HIRING !
CUSTOMER SERVICE CASHIERS Openings in: Mocksville, Salisbury & Kannapolis Locations
WE OFFER:
Requirements: Valid driver's license A Nationwide Criminal Record Background check
To apply, fax resume to: 704-636-7772 or call: 704-633-3211 or 704-633-8233 ext. 20 to schedule an interview
Free cat. Black & white tabby. Totally declawed. Never sick in 15 yrs. Still chases her tail. Long life expectancy. Ideal for adults wanting quieter pet. Loving. Owner going to nursing home. 704-647-9795
The Town of Landis is seeking a highly motivated individual to fill the position of Parks Director. Duties will include, but are not limited to, supervising, coordinating and scheduling department operations. This position will also include managerial and administrative skills and duties, including: formulating the annual Parks & Recreation budget, attending all Board meetings, recommending purchases to the Finance Officer, and seeking Parks & Recreation Grants and funding through Federal, state and private organizations. This individual should be able to plan and develop the Town's Recreation Facilities, and assist private groups in developing park and recreational facilities for private use. This individual will also be responsible for weekly inspections of each park location and other recreational facilities, to ensure that they are properly maintained. A certified criminal history and driving record will be required with all completed application packets. All applicants will also be required to take and pass a drug screening. Benefits include 401 (k), N.C. local government retirement system and medical/dental/vision insurance. Minimum Qualifications: Applicants must have at minimum a Bachelor's Degree in Parks & Recreation from an accredited college/university or extensive experience in the Parks & Recreation field. This individual must possess experience in the development of Parks & Recreation programs and in grant seeking and writing. A valid NCDL is also required. This individual should possess excellent communication skills which will allow them to identify and deal with any problems in a courteous, firm, fair & effective manner.
The Town of Landis prohibits discrimination on the basis of race, color, national origin, sex, religion, or age.
Free cats. Elderly couple looking for a good home for three male neutered cats. Cats approximately 6 years old. 1 black, 1 gray tabby, & 1 gray & white tabby. Please call 704-209-6044
AKC French Bulldog, AKC, Male Adult. Cream color. 4yrs young. Champion Bloodlines all the way back to his 5th Gen! UTD on all shots. $800 cash OBO. Call 704-603-8257.
American Pit Bull Pups
Free Kittens. Litter box trained. One black/white, three gray. Precious. 704-267-9839 l/m
Giving away kittens or puppies?
FIND IT SELL IT RENT IT in the Classifieds
Dogs
Dogs
FREE dog. To good home only. 3 yr. old 1/2 wolf, 1/2 shepherd female. Needs fenced yard or lot. NO CHAIN!!! 704279-8089
Puppies - Free 7 weeks old small mixed breed. Very cute, fat and healthy! 704-209-1943
DOG, free to good home. Small chihuahua three years old all shots. Please call704-657-6062 Free dog. Female German Shepard. 5 years old. Loving & loves to play. Needs room to run. To good home only. Call 704603-8562 Free dog. Male Lab mix. 3 years old. To good home only. Please call 704-431-4654
11 pups ready to go. Prices negotiable. ALL colors, male & female. 1st shots. Call 704-2395924 Faith area.
Free puppy. Sweet female Chocolate Lab puppy. Maybe 9 weeks old. Abandoned in our yard on Sunday. To good home. 704-633-9316
Employment Earn extra holiday cash. $10 to start. 704-2329800 or 704-278-2399
Yard Sale Area 1
Free dog. Mini 19 lb. multicolored Poodle. Neutered. Black racing stripe nose to tail. Handsome & friendly. 12 yo. Exc. health. Loves to run. Owner going to nursing home. 704-647-9795
Cocker Spaniel puppies. Black and white, 1 female, 2 males. Full blooded, no papers. Shots, wormed, tails docked. 8 weeks old. $200. Please Call 704239-3854
Need customers? We’ve got them. The Salisbury Post ads are read daily in over 74% of the area’s homes!
SHIH-TZU PUPPIES Playful, lovable cute! First shots, wormed. DOB 11/20/10 Private home. $200 each. 704 239-5957
704-797-4220 Employment Sales
Yorki-Poos Rockwell, NC. High quality, home raised puppies, registered. Call 704-2249692. Check the website for pricing and information.
HHHHHHHHH Check Out Our December Special! Boarding 20% discount. Rowan Animal Clinic. 704-6363408 for appt.
Supplies and Services Puppies. German Shepherd - Belgian Malions. 2 males. $250 each. Call 704-239-6018
Online for our new interactive
Find all the best sales without the headaches! Plot your route from one sale to another!
Other Pets
Free dog. Sweet female Golden Lab Mix. Owner is moving & cannot keep her. Spayed. Needs loving home. 704-279-6393
Salisbury. 1215 S. Main St. January 8th , 7am-2pm. Antique furniture, queen size bed, some old hand tools, go-cart, kitchen (pots, pans, small appl.)
Puppies - Free part Border Collie puppies, very cute. Black and white, brown, and black puppies. 704-638-0589
Golden Retriever - Free to good home. 2 years old, all shots, very good with children. Needs room to run Please call 704-279-0426
Got puppies or kittens for sale?
Business Equipment & Supplies Filing Cabinet – wooden, lateral filing cabinet, double drawer. Beautiful cherry $300 FIRM. 704 239-6463
Clothes Adult & Children Leather coat. New,
Growing Pains Family Consignments Call (704)638-0870 115 W. Innes Street
Sweet Peas 2127 Statesville Blvd. 50% off all Clothing Now thru Jan. 31st.
Electronics Position Avail. for LPN or RN. Full Time, Apply in person. No phone calls please. Brightmoor Nursing Center, 610 W. Fisher St.
Adopt a Puppy or Kitten for $80 adoption fee. Salisbury Animal Hospital 1500 E. Innes St. 704-637-0227 salisburyanimalhospital.com
Wanted: Life Agents. Potential to Earn $500 a Day. Great Agent Benefits. Commissions Paid Daily. Liberal Underwriting. Leads, Leads, Leads. Life Insurance, License Required. Call 1-888-713-6020. SKILLED LABOR Experienced Diesel Mechanic wanted. Send resume to PO Box 302, Mocksville NC 27028 Weedman - Customer Reps Needed Seeking enthusiastic & outgoing people. No selling involved, full training provided. M-F, 4-9 pm & Sat 10am2pm. Earn $8/hr + bonuses. Begin Immediately. Call today at 704-637-8780
Firewood for Sale: Pick-up/Dump Truck sized loads, delivered. 704-647-4772
Furniture & Appliances Air Conditioners, Washers, Dryers, Ranges, Frig. $65 & up. Used TV & Appliance Center Service after the sale. 704-279-6500
Bedroom set. Mahogany. Thomasville. Headboard, triple dresser with 2 mirrors, nightstand & highboy. 1970s. $450. 704-213-9811
Consignment Application packets are available Monday thru Friday 8AM - 5PM at City Hall located at 312 South Main Street. Applications must be returned no later than 5:00 pm on Friday, January 28th, 2011.
Healthcare
FIREWOOD FOR SALE Split OR Logs. Delivery negotiable. Please call for info: 704-636-5541
Bachelor's Chest with Marble top. Like new. Attractive carvings. Pic available. $300 obo 704 239-64-63
Starting Salary: DOQ
Dogs
Dog – Weimaraner, 1½ year old female, playful, good with kids, she would like to be an inside dog, she is not crate trained. $75. Call 704-361-5363
*All Boocoo Auction Items are subject to prior sale, and can be seen at salisburypost.boocoo.com
Director of Parks
Dog - Free to good home male, dapple, Dachshund all shots & wormed good w/children. 704-657-8527
Free puppies. Cockerspaniel/lab mix. 7 black puppies, 1 blond. 9 weeks old. 704-638-6441
Boocoo Auction Items
Fire wood – Free if you pick it up. Call Shane at 704-636-1054
Asian furniture set, coffee table w/storage, corner cabinet, small side table. $100. Please Call 704-754-3380
WANTED
Dog - full blooded blue healer female, shots up to date, kid friendly. Needs a good home. Call 704 279-0281
WANTED TO BUY Old Colts & Thompson Center Cherokees and Senecas. Please call 704-640-3990
EMPLOYMENT OPPORTUNITY
Salespeople. Sales experience necessary. Top pay & benefits. Start the new year right! Call Greg, 704-792-9700
Cats
Antiques & Collectibles
312 South Main Street Post Office Box 8165 Landis, North Carolina 28088 (704)857-2411 Office (704)855-3350 Fax
Sales
Dogs
Fuel & Wood
Youth Advocate/ Program Assistant
Other
*Excellent Starting Pay *Insurance Benefits *Paid Vacation
C39879
Employment
Healthcare
Driver. CDL-A. Start Fresh at Western Express! Lots of Miles, Brand New Equipment. Great Pay, Excellent Bonuses! Flatbed Division CDLA, TWIC Card and Good Driving Record. 1-866-863-4117. Drivers
PROOF YOUR AD
SALISBURY POST
CLASSIFIED
Davie-Clemmons Yard Sales YARD SALE AREAS
conditioner for Air.
Firewood - Seasoned hardwood. Pick up load $60 & 1 ton load $120 Will Deliver 704-798-5058
Goes great with morning coffee. Dryer - $75.00 Please Call 704-857-1854 for more information Dryer - Barely used White Frigidaire Dryer. Small scratch/dent on top. $200 OBO. China Grove 704-855-2396 Recliner, $100; chest of drawers $95 & matching nightstand, $60, All like new. Computer desk $20. very nice. 704-636-2738 Sofa- Reclining Good condition $25. Please Call 704-202-6075 LM Table with lamp and magazine rack, $25; heavy bookcase with drawer $35 firm. 704-239-0920 or 704239-0920 Television. 52” high definition. Large speakers for surround sound effect. Barely used. $500 obo. 704-857-9687 or 704-202-0831 Washer & Dryer set, MayTag Performa. $325. Please call for more info. 704-762-0345 Washer & dryer, GE. Very good condition. $175. Call 980-234-7526 or 704-657-8397 Washer & dryer, Kenmore Elite, 6 yrs old. King size capacity, heavy duty, quiet pack,, white. Works great $200. 704-212-2195 Wolfgang Puck oven. Broil, bake, rotisserie. Stainless steel, all acc. & book. $50. Call 857 6274
Games and Toys Barbie Dolls - Chest of Early Barbie dolls with furniture and clothes. $50. 704-633-3937
Lawn and Garden Holshouser Cycle Shop Lawn mower repairs and trimmer sharpening. Pick up & delivery. (704)637-2856
Machine & Tools Air Compressor 20 gal. 5.5 Hp. Single Cylinder, Custom airbrushed. $125 Call 704-857-2945. New Norwood Sawmills. LumberMate-Pro handles logs 34" diameter, mills boards 28" wide. Automated quick-cyclesawing increases efficiency up to 40%! om/300N. 1-800-6617746, ext. 300N.
Medical Equipment Electric Lift Chair $300 Please Call 704-633-1150
Misc For Sale
Call to subscribe
Salisbury Post 704-797-4213
Acetylene Oxygen Welder, both tank scutting & brazing torches with cart. $450. 704-938-4948
SALISBURY POST Homes for Sale
Homes for Sale
Misc For Sale
Misc For Sale
Instruction
Air conditioner for room w/remote by Haier $60. If interested, please call 704-857-2945
Light Fixtures - 8 ft. Fluorescent Light Fixtures w/ Tubes $10/ ea. For More Information call 704-857-1854
Attend College Online from Home! Medical, Business, Paralegal, Accounting, Criminal Justice. Job placement Computer assistance. available. Financial aid if qualified. Call 888-8996918.
Rockwell
Become a CNA Today! Fast & affordable instruction by local nurses. 704-2134514.
3 BR, 2 BA in Hunters Pointe. Above ground pool, garage, huge area that could easily be finished upstairs. R51150A. $179,900. B&R Realty 704-633-2394.
METAL: Angle, Channel, Pipe, Sheet & Plate Shear Fabrication & Welding FAB DESIGNS 2231 Old Wilkesboro Rd Open Mon-Fri 7-3:30 704-636-2349 Queen size comforter. Complete set. Nonsmoking, pet free home. $50. 704-278-2829 SpaMassage Foot Massager with comfort fabric. New in Box $10. Call 704-245-8843
Bingham Smith Lumber Co. !!!NOW AVAILABLE!!! Metal Roofing Many colors. Custom lengths, trim, accessories, & trusses. Call 980-234-8093 Patrick Smith
BINGHAM-SMITH LUMBER CO. Save money on lumber. Treated and Untreated. Round Fence Post in all sizes. Save extra when buying full units. Call Patrick at 980-234-8093. tree and Christmas decorations for sale. Too much to list. You pick up. $75. For more info call 704-638-5633, no calls after 7pm, or leave a message.
Treadmill $25. Exercise Bench $25. Restaurant supplies, plates, bowls, trays, silverware $150. Home Entertainment Ctr., light color, 3 sections, w/lights $30. Call 704857-1854 TV tables, 2 @ $35 each. Good condtion. Antique baby doll, $50. Picnic tables, $40. 704-638-8965
Christmas Tree 7 ½ foot pre-lit 900+ lites $35. Please Call 336-406-3696 Comforter – King size comforter, quilt, shams – blue & yellow. $50. King size padded foam mattress cover, $25; memory foam topper $50. 704-279-6393 Computer desk, $20. 3 backpacks, $5 each. Please call 704-640-4373 after 5pm. Dolls, beautiful. (Not antiques) (5 avail). Each at least 20” tall. $100 each. Call 704-633-7425 Essick evaporative humidifier $40. Please call 704-279-8874 after 6pm for more information Essick evaporative humidifier $40. Please call 704-279-8874 after 6pm for more information
Binoculars by Vivitar w/case .7 X 50.(297 Yds. $15. ft.@1000 Please call 704-857-2945 China Grove
Want to Buy Merchandise
CASH PAID for junk cars. $200 & up. Please call Tim at 980234-6649 for more info. Timber wanted - Pine or hardwood. 5 acres or more select or clear cut. Shaver Wood Products, Inc. Call 704-278-9291. Wanted to Buy Old Tools: hand saws, hand planes, miter boxes, etc. Please Call 704-754-0311 Watches – and scrap gold jewelry. 704-636-9277 or cell 704-239-9298
Business Opportunities!
Found Dog. Border Collie mix, on High Rock Rd, January 4. Call to identify. 704-639-9358 Found dog. German Shepherd, neutered male, January 4, Rowan Regional Hospital area. Call to identify. 704-636-2827 Found dog. Medium size, female, brownish color, with collar, found Jan 1 on Concordia Ch Rd. Call to identify. 704900-3335 Found dogs. Brown & white, small females probably about a year old on Parks Rd off 70 Jan. 2. Call to identify. 704232-0266 or 704-8573701 Found Puppy. About 2 months old, mixed breed at Davie County Health Dept Monday, Jan. 3. Call to identify. 336-3457449 small beige, Found
Salisbury Rockwell
REDUCED
Awesome Location
J.Y. Monk Real Estate School-Get licensed fast, Charlotte/Concord courses. $399 tuition fee. Free Brochure. 800-849-0932
Free Stuff
With our
Homes for Sale
Salisbury
Motivated Seller
Very nice 2 BR 2.5 BA condo overlooking golf course and pool! Great views, freshly decorated, screened in porch at rear. T51378. $103,900 Monica Poole B&R Realty 704-245-4628
3 BR, 2 BA. Well cared for, kitchen with granite, eat at bar, dining area, large living room, mature trees, garden spot, 2 car garage plus storage bldgs. $149,500. Monica Poole 704.245.4628 B&R Realty
Forest Creek. 3 BedNew room, 1.5 bath. home priced at only $98,900. R48764 B&R Realty 704.633.2394 Salisbury
Over 2 Acres
Rent With Option!
Great Location 2 BR, 1 BA, hardwood floors, detached carport, handicap ramp. $99,900 R47208 B&R Realty 704.633.2394
Hide While You Seek! Our ‘blind boxes’ protect your privacy.
3BR, 2BA. Wonderful location, new hardwoods in master BR and living room. Lovely kitchen with new stainless appliances. Deck, private back yard. R51492 $124,900 Monica Poole B&R Realty 704-245-4628
Brand new & ready for you, this home offers 3BR, 2BA, hardwoods, ceramic, stainless appliances, deck. R51547. $99,900. Call Monica today! 704.245.4628 B&R Realty
Motivated Seller
Classifeds 704-797-4220
North of China Grove, 225 Lois Lane. 3BR/2BA, Double garage and deck on a quiet dead end street. Country setting. No water bills. No city tax. Possible owner financing. Will work with slow credit. $975/mo + dep. Please call 704-857-8406
Apartments Condos/Townhomes Houses for Rent/Sale Lake Property Land Office & Commercial Industrial/Warehouse Resort & Vacation Homes Rooms Storage
SURE
N
Concord, 1.5 story, level lot, nice subdivision. Thousands below tax value. Tons of extras, crown molding, work island in kitchen, office upstairs, bonus room. 3 BR, 2.5 Baths. $244,750. Dream Weaver Properties of NC LLC 704-906-7207
Open spac hen has parquet ceramic sinks in ba & kitchen. Large bedrooms w/walk-in closets. Dish and cable available. Dishwasher, refrigerator & stove. $79,900. 704-857-9495 or 704-223-1136
New Home
China Grove, 2 new homes under construction ... buy now and pick your own colors. Priced at only $114,900 and comes with a stove and dishwasher. B&R Realty 704-633-2394
3 BR, 2.5 BA, wonderful home on over 2 acres, horses allowed, partially fenced back yard, storage building. $164,900 R51465 B&R Realty 704.633.2394
Salisbury
Alexander Place
Over 2 Acres
Salisbury
Rowan Memorial Park in the Veteran Field of Honor Section, two spaces. $1,000 ea. 336-284-2656
1409 South Martin Luther King Jr Ave., 2 BR, 1 BA, fixer upper. Owner financing or cash discount. $750 Down $411/month. 1-803-403-9555
Salisbury
New Home
Salisbury
Monument & Cemetery Lots
Homes for Sale
Homes for Sale
Salisbury
Convenient Location
S rem New F #50515 Inc. 1755 28023
OPEN
28 Salisbury. Forest Creek. 3 Bedroom, 1.5 bath. New home priced at only $98,900. R48764 B&R Realty 704.633.2394
Sporting Goods
All Coin Collections Silver, gold & copper. Will buy foreign & scrap gold. 704-636-8123
Lumber All New!
Found Cat. In Archdale. All White, Green Eyes. Please call to identify. 704-564-6528
Salisbury - Newly remodeled 3 BR, 2 BA on corner lot in large Meadowbrook. New plumbing, water heater, roof & stainless steel appliances, heat pump, new kitchen w/granite tops & more. $3500 down + $599/mo. on approved credit. 704-239-1292
Misc For Sale Wood Burning Stove, Old Daisy, 50 years old, antique but usable. $50 obo. 704-278-0498
Fuel tank. 75 Gallon Fuel Tank/Tool Box $250.00. For more information, please call 704-857-1854
Lasonic Digital Tonal Converter for older TV $30. New, never used. 704-857-2328
Found cat. Black and white, tuxedo. Air Park area in Gold Hill. Around Christmas. Please call 704-279-0265 to identify.
Homes for Sale
Salisbury
A Must See
PUBLIC NOTICE
AA Antiques. Buying anything old, scrap gold & silver. Will help with your estate or yard sale. 704-433-1951.
Lamps (2) 27" w/shades cream w/pink poppies ginger jar w/carved wood base $50. 704-637-6886
Lost & Found
Homes for Sale
Applications for the Principal Combined Fund Organization to administer the 2011-12 Combined Federal Campaign are now being accepted. Any organization wishing to apply must send their application to the Local Federal Coordinating Committee Chair, PO Box 5065, Salisbury, NC 28144-0088 by Thursday, January 27th, 2011.
Free puppies. Mixed Great Pyrenees. Excellent guard dogs. Very gentle & lovable pet. Mother registered & onsite. 704-279-5876
Homedics Bubble Bliss Foot Spa with heat. New in Box $15.00 Please call 704-245-8843
FRIDAY, JANUARY 7, 2011 • 7B
CLASSIFIED
UL HOME
wood floors, open / airy floor porch off mas-
Forest Abbey. 3BR, 2½BA with upgrades, formal dining & breakfast. Cul-de-sac lot, basement with storage. Gorgeous! $248,900. (980) 521-7816
OLDE SALISBURY
Salisbury, New Home 3 BR. 2 BA. REAL HARDWOODS, Gorgeous kitchen, stainless appliances, vaulted ceiling in great room! Pretty front
F R t K D C $89,500. Monica Poole 704-245-4628 B&R Realty Fulton Heights
Send us a photo and description we'll advertise it in the paper for 15 days, and online for 30 days for only
30*!
$
Call today about our Private Party Special!
704-797-4220 *some restrictions apply
Air Hockey Table For Sale. Full Size $40. Call 704-633-9069 for more information. Lost Dog - Chocolate Lab named Jake. Old Beatty Ford Road/ Lowerstone Church Area. Call 704-209-1363. Refrigerator, Whirlpool. Side by Side. White. Model ED5PHEXMQ. $450 obo. 704-762-0345
Reduced
CLASSIFIEDS salisburypost.com 3 BR, 2 BA, Attached carport, Rocking Chair front porch, nice yard. R50846 $119,900 Monica Poole 704.245.4628 B&R Realty
More Local Real Estate Listings.
8B • FRIDAY, JANUARY 7, 2011 Want to sell quickly? Try a border around your ad for $5!
Homes for Sale
SALISBURY POST
CLASSIFIED
Homes for Sale
Homes for Sale
Bank Foreclosures & Distress Sales. These homes need work! For a FREE list:
Homes for Sale
Genesis Realty 704-933-5000 genesisrealtyco.com Foreclosure Experts
Homes for Sale
Homes for Sale
Land for Sale
Land for Sale
25 Acres Beautiful Land for Sale by Owner
FOR SALE BY OWNER 36.6 ACRES AND HOME
Lake Property
Salisbury. 2 or 3 bedroom Townhomes. For information, call Summit Developers, Inc. 704-797-0200
West Rowan – Country Club living in the country. Builder's custom brick home has 4 BR, 3 ½ BA w/main floor master suite. 3300 sqft. + partially finished bonus room. Lots of ceramic and granite. 2 fireplaces with gas logs. 6.5 very private wooded acres. Priced at $399,000. Reduced to sell! $389,000. Call for appt. 704-431-3267
1 Hr to/from Charlotte, NC Cleveland & near:
High Rock waterfront, beautiful, gently sloping, wooded in Waters Edge subdivision. Approx. 275' deep, 100' waterline. Excellent HOA. For Sale By Owner. $248,000. Appraisal available. Call 704-609-5650
Kannapolis. 608 J Avenue, 3BR/2BA. Totally remodeled, stainless steel appliances & granite. Rent to own! Owner will help obtain financing. $79,900. Call Scott for information. Lifetime opportunity! 704-880-0764
FRIDAY, JANUARY 7, 2011
Happy 70th Birthday to the best dad in the world! I love you Tyler "Coot" C.
Happy Birthday Granddaddy "Coot" Today you're 70, but who's counting..lol! You rock. I love you! Sarah
Happy 40th Birthday Aunt Tina. Thanks for all you do for me and my son. Love Cyndi, Tristan
Happy Birthday to Granddaddy "Coot" We love you, Kyle & Kelsey
Happy 41th Birthday Tina. Hope you have a great day. Love always, your daughters, Mercedes, Cori, Autumn
Happy Birthday to you and wish you all of God's blessings. Love you always, Your mom (Francine)
Happy Birthday Selena, a big 19 in da building. Hope you have fun and enjoy. From Kabrina
EXIT 76 WEST OFF HWY 85!
Tyler "Coot" C., Big 70 but who's counting! Wishing you many more! Love you! Hugs & Kisses Sophia
THE HONEYBAKED HAM CO. & CAFE 413 E. Innes St., Salisbury of Salisbury 704-633-1110 • Fax 704-633-1510 HAM CLASSIC SANDWICH
4.99
Enjoy your day dad! Now in the words of Brown, let's have a "CELEBRATE" .. Lol… Happy 70th!
W/CHIPS & DRINK
$
Here's a very special heart hug for Tina W. on your 40th birthday. Love you, Christopher LOL Happy 23rd Birthday to Freddie B. We love you and miss you! Natasha and Ra'jon
Auctions
Carport and Garages
Carolina's Auction Rod Poole, NCAL#2446 Salisbury (704)633-7369
Auction Thursday 12pm 429 N. Lee St. Salisbury Antiques, Collectibles, Used Furniture 704-213-4101
Lippard Garage Doors Installations, repairs, electric openers. 704636-7603 / 704-798-7603
On-Site Estate Auction Sale: Sat., Jan. 8, 10am Preview: Jan. 7, 1-5pm Location: 244 Greensboro St. Ext., Lexington, NC, 27292
Auction held under heated tents rain, snow or shine! Highlights include local furniture custom made by members of the Craver family, a 1995 Cadillac 53k miles, shop wood working equipment, hardwood lumber, yard tools and mowers, generator, guns, sterling silver, estate jewelry, antiques, Plus Much More! View website for complete sale listing and photos today!
Cleaning Services We can provide you with an affordable customized home cleaning service. Have your home cleaned the way you like it! Insured, refs available. Call Kim Taft! 704-433-2502
Terms: No Reserves. All sales subject to the terms & conditions of sale. Cash, check, Visa, MC, AX, and Discover. 13% buyer's premium. 3% discount for cash/check. No state sales tax. NCFL#7452
“Clean as a Whistle”
Leland Little Auction & Estate Sales, Ltd.
WOW! Clean Again! New Year's Special Lowest Prices in Town, Senior Citizens Discount, Residential/Commercial References available upon request. For more info. call 704-762-1402
620 Cornerstone Ct., Hillsborough NC 919. 644. 1243 Heritage Auction Co. Glenn M.Hester NC#4453 Salisbury (704)636-9277
Cleaning Services
Job Seeker meeting at 112 E. Main St., Rockwell. 6:30pm Mons. Rachel Corl, Auctioneer. 704-279-3596
Rowan Auction Co. Professional Auction Services: Salis., NC 704-633-0809 Kip Jennings NCAL 6340.
Automotive Services Genesis Auto Detailing & Headlight Restoration. Complete service. Pick up/ delivery avail. 704-279-2600
NC AUTO INSPECTION $15 U U
plus tax $6.25
By appt. only Call 704-857-1854.
H
4.99
H
H
H
704-633-9295 FREE ESTIMATES Licensed, bonded and insured. Since 1985.
“Allbrite Carpet Cleaning” Eric Fincher. Reasonable rate. 20+ years experience. 704-720-0897
Carport and Garages
Perry's Overhead Doors Sales, Service & Installation, Residential / Commercial. Wesley Perry 704-279-7325
S47834
Every Night Kids Under 12 eat for 99¢ with 2 paying Adults Thurs-Fri
HAMBURGER STEAK PLATE $5.99
We want to be your flower shop!
CHICKEN & DUMPLINGS
Salisbury Flower Shop
5.99
$
1628 West Innes St. Salisbury, NC • 704-633-5310
HOURS: Mon, Tues, Thurs, Fri, Sat: 11AM-8PM Wednesday 11AM-3PM • Closed on Sundays S48510
S40137
Home Improvement
Junk Removal
Miscellaneous Services
Painting and Decorating
Roofing and Guttering
Brisson - HandyMan Home Repair, Carpentry, Plumbing, Electrical, etc. Insured. 704-798-8199
$ $ $ $ $ $ $ $ $ $ We Buy Any Type of Scrap Metal At the Best Prices...
BSMR Sewing
Bowen Painting Interior and Exterior Painting 704-630-6976.
SEAMLESS GUTTER Licensed Contractor C.M. Walton Construction, 704-202-8181
Browning ConstructionStructural repair, flooring installations, additions, decks, garages. 704-637-1578 LGC
Guaranteed! F
CASH FOR JUNK CARS And batteries. Call 704-279-7480 or 704-798-2930 WILL BUY OLD CARS With keys, title or proof of ownership, $200 and up. (Salisbury area only) R.C.'s Garage & Salvage 704-636-8130 704-267-4163
Kitchens, Baths, Sunrooms, Remodel, Additions, Wood & Composite Decks, Garages, Vinyl Rails, Windows, Siding. & Roofing. ~ 704-633-5033 ~
Grading & Hauling
Home Improvement
Drywall Services OLYMPIC DRYWALL
Piedmont AC & Heating Electrical Services Lowest prices in town!! 704-213-4022
New Homes Additions & Repairs Small Commercial
Household sewing machines, new and older models and parts.
704-797-6840 704-797-6839
Moving and Storage TH Jones Mini-Max Storage 116 Balfour Street Granite Quarry Please 704-279-3808
Painting and Decorating
Lawn Maint. & Landscaping
Complete crawlspace work, Wood floor leveling, jacks installed, rotten wood replaced due to water or termites, brick/block/tile work, foundations, etc. 704-933-3494
Earl's Lawn Care
Cathy's Painting Service Interior & exterior, new & repaints. 704-279-5335
• 25 years exp. • Int./Ext. painting • Pressure washing • Staining • References • Insured 704-239-7553
Tree Service Graham's Tree Service Free estimates, reasonable rates. Licensed, Insured, Bonded. 704-633-9304
Bost Pools – Call me about your swimming pool. Installation, service, liner & replacement. (704) 637-1617 MOORE'S Tree TrimmingTopping & Removing. Use Bucket Truck, 704-209-6254 Licensed, Insured & Bonded TREE WORKS by Jonathan Keener. Insured – Free estimates! Please call 704-636-0954.
See stars
Removal 3Gutter Cleaning
~ 704-633-5033 ~
Pools and Supplies
Want to get results? ####
3Mowing 3Yard Cleanup 3Trimming Bushes 3Leaf
Guttering, leaf guard, metal & shingle roofs. Ask about tax credits.
Stoner Painting Contractor
ALL home repairs. 704857-2282. Please call! I need the work. Roofing, siding, decks, windows.
Lyerly's ATV & Mower Repair Free estimates. All types of repairs Pickup/delivery avail. 704-642-2787
The Floor Doctor
BowenPainting@yahoo.com
Roofing and Guttering
Lawn Equipment Repair Services
The more you tell, the surer you’ll sell.
3Core Aeration 3Fertilizing
FREE Estimates
704-636-3415 704-640-3842
Heating and Air Conditioning
Machine Repair
We will come to you! F David, 704-314-7846
Anthony's Scrap Metal Service. Top prices paid for any type of metal or batteries. Free haul away. 704-433-1951
Professional Services Unlimited
Carpet and Flooring
2 Hot Dogs, Fries & Drink ..............$4.49
Hours: Mon-Fri 10-7; Sat 10-6; Sun 11-2
Birthday? ...
5550 Hwy 601 • Salisbury, NC 28147 • 704-647-9807
A message from the Salisbury Post and the FTC.
Beaver Grading Quality work, reasonable rates. Free Estimates 704-6364592 H
1/2 HAM CLASSIC SANDWICH & BOWL OF HAM & BEAN SOUP
MawMaws Kozy Kitchen
SATURDAY 11-4 ....BUY 1 FOOTLONG GET 1 FREE
413 E. Innes Street • 704-633-1110
18 WORDS MAX. Number of free greetings per person may be limited, combined or excluded, contingent on space available.
Fencing
We Build Garages, = 24x24 $12,500. All sizes built! ~ 704-633-5033 ~
The late Jacqueline C. Leonard
THE HONEYBAKED HAM CO. & CAFE of Salisbury
In Person: 131 W. Innes Street Online: (under Website Forms, bottom right column)
Auctions
Hours: Mon-Fri: 10-7; Sat 10-6; Sun 11-2
$
Must present ad. Not valid w/any other offer. Exp. 2/12/11
FOR FREE BIRTHDAY GREETINGS Please Fax, hand deliver or fill out form online
10 people or more Not valid with any other coupon.
CarlaAnnes.com
Happy Birthday to my father-in-law Tyler C. celebrating 70 years of life. Love you, Donnell
OFF Party Trays
704-754-6519 Baked Fresh To Order!
10.00
To advertise in this directory call
704-797-4220
GAYLOR'S LAWNCARE For ALL your lawn care needs! *FREE ESTIMATES* 704-639-9925/ 704-640-0542 Outdoors By Overcash Mowing, shrub trimming & leaf blowing. 704-630-0120
Lawn Maint. & Landscaping
Quality Haircut
$
Home Improvement
4.99 DEBBIE’S HAIR DESIGNS for new customers only
•
A HANDYMAN & MOORE Kitchen & Bath remodeling Quality Home Improvements Carpentry, Plumbing, Electric Clark Moore 704-213-4471
Home Improvement
Manufactured Home Services
Around the House Repairs Carpentry. Electrical. Plumbing. H & H Construction 704-633-2219
HMC Handyman Services. Any job around the house. Please call 704-239-4883
Mobile Home Supplies~ City Consignment Company New & Used Furniture. Please Call 704636-2004
men • women • children 1008 S. Main Street • Salisbury, N.C. Call for an appointment
S47812
S48851
$
Hours of daily personal attention and doggie fun at our safe 20 acre facility. Professional homestyle boarding, training, and play days with a certified handler/trainer who loves dogs as much as you do.
• Birthday & Holiday Gift Baskets • Party Trays • Fresh Breads
C47539
Happy 70th Birthday to the GREATEST Dad in the world, Tyler Roosevelt "Cooter Boy" C.! Love you Daddy! Benet
We are so there!
S39136
Happy Birthday to my granddad Tyler C. Celebrate BIG! Whitney & Cadence
having a
S45263
Happy Birthday to our dear friend Jane T. From your Red Vest sisters. Much love, Cindy, Sharon, Reneau
S44972
Lordy Tina turned 40 today, we still love you since you're over the hill now. Love friends & family
704/630-9970 or 704/433-0595
SALISBURY POST Land for Sale ********************** Front St. 3.37 acres, almost completed 50' x100' bldg. $44K. 704-636-1477 10 minutes from Catawba. 10-80 acres. 336-998-9626 daytime / 336-998-5376 evenings Beautiful year round creek, 3.06 acres. Buy now, build later, $47,900 owner fin. 704-563-8216
Lots for Sale N. Rowan-Nice, wooded subdivision lot. $15,300. 51225. Varina Bunts B&R Realty 704.640.5200
Olde Fields Subdivision. ½ acre to over 2 acre lots available starting at B&R Realty $36,000. 704.633.2394 Southwestern Rowan Co.
Barnhardt Meadows. Quality home sites in setting, country restricted, pool and pool House complete. Use your builder or let us build for you. Lots start at $24,900. B&R Realty 704-633-2394 Western Rowan County
Real Estate Commercial
Convenience store business for sale with large game room/mini bar. Includes all stock, system, ice security coolers, etc. maker, $20,000. Will consider trade for mobile home & land. 704-857-0625
Manufactured Home Sales Area 3 or 4 bedroom, 2 baths, $500 down under $700 per month. 704-225-8850 Salisbury
OWNER FINANCING! NO MONEY DOWN!
3BR/2BA, 2.75 acres, one mile from High Rock Lake, one year old Samsung appliances, tons of upgrades, Pergo floors, 1400+ sq feet, Oakwood manufactured. Asking $125,000. 704-202-2228 or 704-224-1286
Real Estate Services Allen Tate Realtors Daniel Almazan, Broker 704-202-0091 Arey RealtyREAL Service in Real Estate 704-633-5334 B & R REALTY 704-633-2394
Century 21 Towne & Country 474 Jake Alexander Blvd. (704)637-7721 Forest Glen Realty Darlene Blount, Broker 704-633-8867 KEY REAL ESTATE, INC. 1755 U.S. HWY 29. South China Grove, NC 28023 704-857-0539 Rebecca Jones Realty 610 E. Liberty St, China Grove 704-857-SELL
Rowan Realty, Professional, Accountable, Personable . 704-633-1071 William R. Kennedy Realty 428 E. Fisher Street 704-638-0673
$$$$ Want to make more of this? Check out the Classifieds in todays Salisbury Post for a lead on a new career!
East Schools. 3BR. Refrigerator and stove. Central air and heat. Please call 704-638-0108.
Hidden Creek, Large 2 BR, 2 BA end unit, all appl. pool + W/D, $795/mo + $400 dep. Ref. 1 yr. lease, no smoking, no pets. 704-640-8542
Old Concord Rd., 3 BR, 1 BA, has refrigerator, stove & big yard. No pets. $595/rent + $595/dep. Call Rowan Properties 704-633-0446
Franklin St. 2 BR, 1 BA. Newly refurbished inside. Rent $495, dep. $400. Call Rowan Properties 704-633-0446
Wiltshire Village Condo for Rent, $700. 2nd floor. Want a 2BR, 2BA in a quiet setting? Call Bryce, Wallace Realty 704-202-1319
Rockwell, near Rockwell Park. 2BR, 1½BA. Brick home w/garage, deck. Very nice neighborhood. All appl. $650/mo. + dep. 704-6365992 or 704-245-8123
Salisbury
Rowan County. 2 & 3 BR homes. All electric. Free water & sewer. $450$675/mo. 704-633-6035
Wanted: Real Estate
Salis., 3BR/1BA Duplex. Elec., appls, hookups. By Headstart. $500 & ½ MO FREE! No pets. 704-636-3307
*Cash in 7 days or less *Facing or In Foreclosure *Properties in any condition *No property too small/large
Prince Charles Renovated Condos, Large Floor Plans, 1250-4300 sq.ft. Safe inside entrances. Walking distance to Downtown Salisbury. Special Financing Terms. Call: 704-202-6676
Salisbury 2BR. $525 and up. GOODMAN RENTALS 704-633-4802
Apartments 1 & 2BR. Nice, well maintained, responsible landlord. $415-$435. Salisbury, in town. 704-642-1955 1 BR, 1 BA in Granite Quarry. $375/mo. + $375 dep. No Pets. W/D hookups. 704-202-5594
1BR/1BA duplex fully furnished. TV, BR suite, LR furniture, refrig., washer / dryer, Sect. 8 approved. Heat, air, electricity & water incl'd. $750/mo + $500 dep. 704-636-1850 brick duplex with carport, convenient to hospita. $450 per month. 704-637-1020
2BR, 1BA Duplex Central heat/air, appliances, laundry room, yardwork incl. Fenced backyard, storage building. $600/mo. plus $600 deposit 704-633-2219
Airport Rd. area. 118-A Overbrook Rd. ½ rent for December. 2 story apt. $535/mo. Very nice. Daytime 704-637-0775
BEST VALUE Quiet & Convenient, 2 bedroom town house, 1½ baths. All Electric, Central heat/air, no pets, pool. $550/mo. Includes water & basic cable.
West Side Manor Robert Cobb Rentals 2345 Statesville Blvd. Near Salisbury Mall
704-633-1234 maintained, 2 BR Duplex. Central heat/air, all electric. Section 8 welcome. 704-202-5790
Colony Garden Apartments 2BR and 1-1/2 BA Town Homes $575/mo. College Students Welcome! Near Salisbury VA Hospital 704-762-0795 Houses for Rent Apartments
Office Building with 3 office suites; small office in office complex avail.; 5,000 sq.ft. warehouse w/loading docks & small office. Call Bradshaw Real Estate 704-633-9011 No. 60923
OFFICE SPACE
Prime Location, 1800+ sq.ft. (will consider subdividing) 5 private offices, built in reception desk. Large open space with dividers, 2 bathrooms and breakroom. Ample parking 464 Jake Alexander Blvd. 704 223 2803
Office Space
Salisbury. Free Rent, Free Water, New All Elec. Heat/air, on bus route. $495. 704-239-0691 Spencer. 2BR/1½ BA, appls w/ W/D hook up, security lights, no pets, Sect. 8 OK. 704-279-3990 STONWYCK VILLIAGE IN GRANITE QUARRY Nice 2BR, energy efficient apt., stove, refrigerator, dishwasher, water & sewer furnished, central heat/ac, vaulted ceiling, washer/dryer connection. $495 to $550 /Mo, $400 deposit. 1 year lease, no pets. 704-279-3808 WELCOME HOME TO DEER PARK APTS. We have immediate openings for 1 & 2 BR apts. Call or come by and ask about our move-in specials. 704-278-4340 for info. For immediate info call 1-828-442-7116 Concord. Move in ready, completely furnished downtown condo. $500 dep. + $550/mo. 704-782-1881
Don't Pay Rent! 3BR, 2BA home at Heights. Crescent Call 704-239-3690 for info. E. Rowan, 3BR/2BA, deck, all electric, no pets. $750/mo + $750 dep. Sect. 8 OK. Credit check. 704-293-0168. E. Spencer - 2 BR, 1 BA, access. wheelchair Faith/Carson district. 3BR / 2BA, no smoking, no pets. $650/mo + dep + refs. 704-279-8428 Fulton St. 3 BR, 1 ½ BA. Refrigerator, stove furnished. Rent $725, Dep., $700. Call Rowan Properties 704-633-0446
We have office suites available in the Executive Center. First Month Free with No Deposit! With all utilities from $150 and up. Lots of amenities. Call Karen Rufty at B & R Realty 704-202-6041
Salisbury 4BR/2BA, brick ranch, basement, 2,000 SF, garage, nice area. $1,195/mo. 704-630-0695
Salisbury. 12,000 sq ft corner building at Jake Alexander and Industrial Blvd. Ideal for retail office space, church, etc. Heat and air. Please call 704279-8377 with inquiries.
Salisbury City, Near Rowan Regional Medical Center. 4BR /2½BA, 2 car garage, fenced-in yard, many ugrades. $1,400 per month, $1,000 deposit, one year minimum. Credit check & references required. 704-232-0823 Salisbury
Great Convenient Location!
303-B W. Council St. Impressive entry foyer w/mahoghany staircase. Downstairs: L/R, country kit. w/FP. Laundry room, ½BA. Upstairs: 2BR, jacuzzi BA. Uniquely historic, but modern. 704-691-4459
Salisbury N. Fulton St., 2BR/1BA Duplex, limit 3, no pets, $525/month + deposit. 704-855-2100 Hurley School area. 3BR, 2BA. Carport, fenced yard. Storage building. Newly remodeled. $800/mo. + deposit. Call 704-636-8058 Kannapolis -604 Carolyn Ave, 2 BR, 1 BA Duplex, $475/mo.; 1704 Moose Rd, 3 BR, 1 BA, $675/mo. KREA 704-933-2231
Lake Front East area. Completely remodeled 1BR. Perfect for one or two people. Trash & lawn service. $360/mo. + deposit. 704-640-2667
Salisbury-2 BR, 1 BA, brick, off Jake Alex., Remodeled, central heat/ air, $550/mo. 704-640-5750
East Rowan. 2BR. trash and lawn service included. No pets. $450 month. 704-433-1255
Salisbury. 3 & 2 Bedroom Houses. $500-$1,000. Also, Duplex Apartments. 704636-6100 or 704-633-8263
Ellis Park. 3BR/2BA. Appls., water, sewer, incl'd. $525/mo. + $525 deposit. Pet OK. 704-279-7463
Salisbury/Spencer 2, 4 & 5 BR $450-$850/mo. 704202-3644 or leave message. No calls after 7pm
Faith 2BR/2BA, private lot, appliances included, $490/mo + dep. No pets. 704-279-3518
Salisbury/Spencer area 2-6 BR houses. Cent. heat & AC. $550- $850/ month. Jim 704-202-9697
Condos and Townhomes
Salisbury. 2BR, 2BA spacious 1st floor condo. Appliances, fireplace, covered porch. Pool, tennis court. $750/mo. + deposit. Rent to own possible. 704-209-1805 Lv. msg.
3 BR, 2 BA, West Schools. Quiet, private location in nice subdivision. 3 miles to mall. Central heat/air, appliances, dishwasher, wired storage building, concrete drive. $800 plus deposit. 704-279-0476
2 to 5 BR. HUD Section 8. Nice homes, nice st areas. Call us 1 . 704-630-0695
Salisbury, city. 2BR, 1BA. Stove, refrigerator. New carpet. $500/mo., $500 dep. 704-633-4081
Colonial Village Apts.
Eaman Park Apts. 2BR, 1BA. Near Salisbury High. $375/mo. Newly renovated. No pets. 704-798-3896
Numerous Commercial and office rentals to suit your needs. Ranging from 500 to 5,000 sq. ft. Call Victor Wallace at Wallace Realty, 704-636-2021
NOTICE TO CREDITORS Having qualified as Executor for the Estate of Roxie D. Overcash, 1116 Circle Dr., China Grove, NC 28023-5634.. Floyd Delano Overcash, Executor of the estate of Roxie D. Overcash, File #10E1056, 1116 Circle Dr., China Grove, NC 28023-5634 No. 60922 NOTICE TO CREDITORS Having qualified as Administrator CTA of the Estate of Lilliesteen Moore Harris, 1504 West Horah Street, Salisbury, NC 28144, 3rd day of January, 2011. John T. Hudson, ACTA, for the estate of Lilliesteen Moore Harris, deceased, File 10E32, 122 N. Lee Street, Salisbury, NC 28144 Attorney at Law, John T. Hudson, Doran, Shelby, Pethel & Hudson, 122 N. Lee St., Salisbury, NC 28144
No. 60924
Spencer. 3BRs & 2BAs. Remodeled. Great area! Owner financing available. 704-202-2696
Office and Commercial Rental
1st Month Free Rent! Salisbury, Kent Executive Park office suites, $100 & up. Utilities paid. Conference room, internet access, break room, ample parking. 704-202-5879
Faith. 2BR, 1BA. Water, trash, lawn maint. incl. No pets. Ref. $425. 704-2794282 or 704-202-3876 Hurley School Rd. 2 BR, 2 BA. Nice yard, subdivision. Central air/ heat. $460/mo. + dep. 704-640-5750 Landis. 3BR, 2 full BA. Laminate hardwood, fireplace, Jacuzzi tub. Incl. water, sewer & trash. $575 + dep. 704-202-3790 Rockwell. 2BR, 2BA. Appl., water, sewer, trash service incl. $500/mo. + dep. Pets OK. 704-279-7463 Salis 3990 Statesville Blvd., Lot 12, 3BR/2BA, $439/mo. + dep. FOR SALE OR RENT! 704-640-3222
China Grove. 1200 sq ft. $800/mo + deposit. Call 704-855-2100
Quiet Setting “A Good Place to Live” 1, 2, & 3 Bedrooms Affordable & Spacious Water Included 704-636-8385
Office and Commercial Rental
Salisbury Salisbury
Call 24 hours, 7 days ** 704-239-2033 ** $$$$$$
Salisbury.
Great House!
Houses for Rent
Salis., 2 BR, 1 BA $550; 3 BR, 1.5 BA $800, E. Spen. 2 BR, 1 BA $425 Carolina-Piedmont Properties 704-248-2520
AAA+ Apartments $425-$950/mo. Chambers Realty 704-637-1020 Singlewide, 3BR/2BA, on ¾ acre, wooded lot, newly renovated, all appliances, well water 704-633-8533 after 5pm
Condos and Townhomes
Apartments
Downtown Salis, 2300 sf office space, remodeled, off street pking. 633-7300
1, 2, & 3 BR Huge Apartments, very nice. $375 & up. 704-754-1480 Knox Farm Subdivision. Beautiful lots available now starting at $19,900. B&R Realty 704.633.2394
FRIDAY, JANUARY 7, 2011 • 9B
CLASSIFIED
Lake front house on High Rock Lake. 2 BR, 1 BA. Avail. Feb. 1st. Rent from Oct. to Mar. $600/ mo. Rent from Apr. to Sept. $700/mo. Contact Dwayne at 704-213-3667 Off Airport Rd. 3BR, 1½BA brick house. Hrd flrs. 1 acre lot. $575/mo. $300 sec. deposit. 704-326-5073
Furnished Key Man Office Suites - $250-350. Jake & 150. Util & internet incl. 704-721-6831 Granite Quarry - Start the New Year Right! Only two units left! Move in by 1/31/11 and pay no rent until 4/1/11. Comm. Metal Bldg. perfect for hobbyist or contractor. Call for details 704-232-3333
West 13th St., in well established, nice neighborhood, totally furnished, internet, microwave, range, refrigerator, washer & dryer, all utitilies included. Single person only. No pets. $110/wk. + small deposit. 336-927-1738
NOTICE OF SALE In accordance with North Carolina General Statue Chapter 44A and in order to satisfy lien assertion for unpaid rent, the following units will be sold at public auction on January 7, 2011 at 10:00 a.m. to the highest bidder. The sale will be conducted by P.S. Orangeco, Inc. and/or Shurgard TRS, Inc. at the Public Storage Location facilities identified below. Public Storage, 1730 W. Jake Alexander Blvd., Salisbury, NC 28147 Rabackoff, Justin Boxes/Bags/Totes D017 Woodruff, William Boxes/ Bags/Totes; Electronics/Computers D022 G027 Sloan, Jr., Vernon Books/Files/Cabinets; Boxes/Bags/Totes; Furniture G036 Smith, Alisha Bedding/Clothing; Boxes/Bags/Totes; Furniture Sherman, Sweetie Boxes/Bags/Totes; Electronics/Computers I014 Parker, Rachel Boxes/Bags/Totes; Furniture; Tools K012 K013 Harding, Kimberly Furniture; Toys K050 Linkins, Lisa Boxes/Bags/Totes; Furniture R030 Sexton, Ruth Boxes/Bags/Totes; Furniture No. 60921 NOTICE OF PUBLIC HEARING SUP 01-10 ADO 01-10 TUESDAY, JANUARY 18,-10 Orica USA Inc. is requesting a special use permit to allow a 1,344 sq. ft. office expansion to an existing non-conforming use located at 2075 High Rock Rd., Gold Hill further identified as Rowan County Tax Parcel 538 027. ADO 01-10 The Rowan County Planning and Development Department requests consideration of multiple amendments to the Rowan County Road Name, Road Sign and Address Display Ordinance. Please contact the Rowan County Planning Department, located at 402 North Main Street, Salisbury, NC (704) 216-8588, to request a copy of the above referenced applications. This is the 5th day of January 2011 Carolyn Athey, Clerk to the Board of Commissioners This notice to run January 7, 2011 and January 14, 2011 No. 60919 AMENDED NOTICE OF FORECLOSURE SALE, North Carolina, Rowan County - 10 SP 853 In the matter of the foreclosure of the Deed of Trust of Paula G. Miller and Barry W. Miller, Grantor(s) To: TRSTE, Inc., Trustee, and Wachovia Bank, National Association, Beneficiary, See Substitution of Trustee as recorded in Deed Book 1167, Page 203, Rowan County Registry, appointing Richard J. Kania as Substitute Trustee. Under and by virtue of the power and authority contained in that certain deed of trust executed and delivered by the above-named Grantors to Wachovia Bank, National Association, dated January 16, 2004 filed for record on January 16, 2004, securing indebtedness in the original principal amount of $82,215.00 as recorded in Deed of Trust Book 997, Page 935, 530 Miller Road, China Grove, NC 28023, and as more fully described as follows: BEING all of that parcel on the western side of Miller Road, said parcel described in a deed to Barry W. Miller, said deed dated August 14, 2006 and recorded in Book 1073, Page 131, Rowan County Registry. Reference to said deed is hereby made for a more description. PIN: 11402501 Address: 530 Miller Road, China Grove, NC 28023.: Barry W. Miller An order for possession of the property may be issued pursuant to G.S. 4585 1/7, 01/14/2011 No. 60920 NOTICE OF FORECLOSURE SALE, North Carolina, Rowan County 10 SP 1037 In the matter of the foreclosure of the Deed of Trust of Hugh Mason Stowe, Grantor (s) To: TRSTE, Inc., Trustee, and Wachovia Bank, National Association, Beneficiary, See Substitution of Trustee as recorded in Deed Book 1169, Page 273, Rowan County Registry, appointing Richard J. Kania as Substitute Trustee. Under and by virtue of the power and authority contained in that certain deed of trust executed and delivered by the above-named Grantors to Wachovia Bank, National Association, dated April 19, 2006 filed for record on May 5, 2006, securing indebtedness in the original principal amount of $52,062.00 as recorded in Deed of Trust Book 1064, Page 898, 811 Carolyn Avenue, Kannapolis, NC 28083, and as more fully described as follows: Tract 1 : Lying and being in China Grove Township, Rowan County, North Carolina, and being Lot No. 8 of Block A of the ADA Sloop Honeycutt property. This lot is not shown on the recorded map of the said ADA Sloop Honeycutt property but it lies just north of and adjoins Lot No. 7 of Block A of said property, this latter lot being shown on the recorded map of the ADA Sloop Honeycutt property. This is the same property as described in deed book 259, page 237, in the Rowan County Registry. Tract 2: being Lot No.1 in Block "4", as shown on the map of "Jackson Park Addition", a deed of said property being on file in the office of register of deeds in book 337, page 216 at the Rowan County Registry. Said two tracts being all that property described in a deed to Hugh Mason Stowe, dated 6-29-2003, and recorded in Book 980, Page 112.: Denise G. Stowe, Denise G. Stowe, Administrator of the Estate of Hugh Mason Stowe An order for possession of the property may be issued pursuant to G.S. 4586 1/7, 01/14/2011
10B • FRIDAY, JANUARY 7, 2011, JANUARY 7, 2011 • 11B
TV/HOROSCOPE
FRIDAY EVENING JANUARY 7, 2011 A
6:30
7:00
7:30
A - Time Warner/Salisbury/Metrolina
8:00
4
M WXLV N WJZY
8
P WMYV W WMYT Z WUNG
12 5
Wheel of Fortune (N) Å WBTV News Prime Time (N) Extra (N) (In Stereo) Å Inside Edition (N) Å
Jeopardy! (N) Å Who Wants to Be a Millionaire (N) Å TMZ (N) (In Stereo) Å
Entertainment Tonight (N) (In Stereo) Å Inside Edition Entertainment (N) Å Tonight (N) (In Stereo) Å How I Met Your How I Met Your Mother Å Mother Å
Medium “Only Half Lucky” (N) (In Stereo) Å Medium “Only Half Lucky” (N) (In Stereo) Å
CSI: NY “To What End?” A bakery owner is shot. (N) Å CSI: NY “To What End?” A bakery owner is shot. (N) (In Stereo) Å
Blue Bloods “Little Fish” A highend escort is murdered. Blue Bloods “Little Fish” A highend escort is murdered. (N) (In Stereo) Å College Football AT&T Cotton Bowl -- LSU vs. Texas A&M. From Arlington, Texas. (In Stereo Live) Å
News 2 at 11 (N) Å WBTV 3 News at 11 PM (N)
Late Show W/ Letterman (:35) Football Friday Night
Supernanny “George Family” Jo Primetime: What Would You Do? 20/20 (N) (In Stereo) Å helps a couple with five daughters. (In Stereo) Å (N) (In Stereo) Å Minute to Win It (In Stereo) Å Dateline NBC (In Stereo) Å
WSOC 9 News Tonight (N) Å
Seinfeld Kramer gets into meat slicing. (:35) Nightline (N) Å
(:15) WXII 12 Sports Report
College Football AT&T Cotton Bowl -- LSU vs. Texas A&M. From Arlington, Texas. (In Stereo Live) Å
(:35) The Tonight Show With Jay Leno Fox News at 10 (N)
Å
Jeopardy! (N) Å
Wheel of Minute to Win It (In Stereo) Å Dateline NBC (In Stereo) Å Fortune Stereo) Å “America’s Game” PBS NewsHour (N) (In Stereo) Å McLaughlin MotorWeek Carolina Barnstorming (In Stereo) Å “Lincoln MKX” Group (N) Business Review Supernanny Jo helps a couple Who Wants/ Are You ABC World Primetime: What Would You Do? with five daughters. (N) Å Millionaire Smarter? News (In Stereo) Å Family Guy (In Two and a Half Two and a Half Smallville “Supergirl” The Green Supernatural Dean is abducted Stereo) Å Men Men Arrow is threatened. from a crop circle. Å The Simpsons Two/Half Men Two/Half Men Monk (In Stereo) Å Monk (In Stereo) Å Family Feud (In Law & Order: Special Victims Monk “Mr. Monk and the Missing Monk “Mr. Monk and the Captain’s Stereo) Å Unit “Annihilated” Terrorists threat- Granny” A law student offers to Wife” A union dispute goes awry. en victim’s fiance. Å help Monk. Å (In Stereo) Å (:00) PBS Nightly North Carolina Washington North Carolina North Carolina Exploring North Carolina Å NewsHour Business Now (In Stereo) Week (N) (In Weekend (In People “Rev. (N) Å Report (N) Å Å Stereo) Å Stereo) Å George Reed”
NewsChannel (:35) The Tonight Show 36 News at With Jay Leno 11:00 (N) Legend of Pancho Barnes and The Mysterious Human Heart End-stage heart failure. the Happy Bottom (:35) Nightline 20/20 (N) (In Stereo) Å Entourage (N) Å “Dominated” WJZY News at (:35) Seinfeld New Adv./Old (:35) The Office 10 (N) “The Slicer” Christine Å The Office The Office House-Payne Meet, Browns Tyler Perry’s Tyler Perry’s My Wife and George Lopez House of Payne House of Payne Kids (In Stereo) (In Stereo) Å Å
Å
Å
Around the World in 80 Trades “Africa” Camels; two tons of Zambian coffee. Å
Need to Know (N) (In Stereo) Å
CABLE CHANNELS A&E
Criminal 36 (:00) Minds
Criminal Minds “Catching Out” Criminal Minds Abduction of a boy Criminal Minds Dr. Reid investi- Criminal Minds “Masterpiece” Criminal Minds A serial killer lures Serial killer jumps trains. Å in Las Vegas. Å gates an old murder. Å Solving a murder in reverse. women into danger. Å (5:30) Movie: ››› “High Plains Drifter” (1973) Movie: ››› “Open Range” (2003) Robert Duvall, Kevin Costner, Annette Bening. Cattle herdsmen unite Movie: ››› “Open Range” Clint Eastwood, Verna Bloom. to battle a ruthless rancher and his henchmen in 1882. Å (2003) Robert Duvall. Hero Phoenix Dangerously Devoted Å Fatal Attractions Å Confessions: Animal Hoarding Confessions: Animal Hoarding Confessions: Animal Hoarding (:00) 106 & Park: BET’s Top 10 Live Å Movie: › “The Wash” (2001) Dr. Dre. Å Movie: ››› “New Jack City” (1991) Wesley Snipes. Housewives Real Housewives/Beverly Movie: ›››‡ “The Green Mile” (1999) Tom Hanks, David Morse, Michael Clarke Duncan. Green Ml Mad Money The Kudlow Report (N) The Facebook Obsession CNBC: Illegal Gambling Inside the Mind of Google Mad Money Situation Rm Anderson Cooper 360 Å John King, USA (N) Parker Spitzer (N) Larry King Live Å (:00) Man vs. Gold Rush: Alaska When the Gold Rush: Alaska The greenhorn Gold Rush: Alaska Tensions build Gold Rush: Alaska Trying to run Gold Rush: Alaska The greenhorn Wild “Alaska” going gets tough. Å miners are at risk. Å among the families. Å dirt through a wash plant. miners are at risk. Å Shake it Up! Shake it Up! Shake It Up! The Suite Life Wizards of Fish Hooks (N) Good Luck Good Luck Shake it Up! Shake it Up! Shake it Up! “Kick it Up” “Party It Up” “Hook It Up” on Deck (N) Waverly Place Charlie Charlie “Age It Up” “Kick it Up” “Party It Up” Bridalplasty E! News (N) Sex and-City Sex and-City Kardashian The Soup Fashion Police Chelsea Lately E! News (:00) SportsCenter (Live) Å NBA NBA Basketball Houston Rockets at Orlando Magic. From Amway Arena in Orlando, Fla. NBA Basketball New York Knicks at Phoenix Suns. From US Airways Center in Phoenix. Countdown Å (Live) Football Live College Football NCAA Division I, Final -- Delaware vs. Eastern Washington. From Frisco, Texas. Boxing (Live) Å Still Standing America’s Funniest Home Videos America’s Funniest Home Videos America’s Funniest Home Videos America’s Funniest Home Videos The 700 Club Å Å Weddings. Å Crazy cats. Å Funny signs. Å Sports shorts. Å Pro Football In My Words NHL Hockey Carolina Hurricanes at Florida Panthers. (Live) Postgame Final Score ACC Final Score Movie: ››› “Ghost Town” (2008) Ricky Gervais, Téa Leoni, Greg Two and a Half Two and a Half Two and a Half Movie: ››› “Ghost Town” (2008) Ricky Gervais, Téa Leoni, Greg Men Men Men Kinnear. Premiere. Kinnear. Special Report FOX Report W/ Shepard Smith The O’Reilly Factor (N) Å Hannity (N) Greta Van Susteren The O’Reilly Factor (:00) PGA Tour Golf Hyundai Tournament of Champions, Second Round. (Live) Golf Central PGA Tour Golf Who’s Boss? Who’s Boss? Who’s Boss? Little House on the Prairie Golden Girls Movie: “Ice Dreams” (2010) Jessica Cauffiel, Brady Smith. Å Golden Girls Designed-Sell Hunters Int’l House Hunters Property Virgin Property Virgin Hunters Int’l Hunters Int’l Hunters Int’l Hunters Int’l Hunters Int’l Hunters Int’l (:00) Hell: The Devil’s Domain Å Modern Marvels Hot and spicy The Templar Code The Knights Templar military order becomes a medi- The History of Sex Medieval items; Tabasco sauce. Å eval world power, then suffers a sudden downfall. Å courtship; the early Church. Highway Hvn. Our House “Friends” Å The Waltons “The Beguiled” Inspir. Today Life Today Joyce Meyer ACLJ-Week Degree Life Fellowship Reba “No Boys Reba (In Stereo) Reba (In Stereo) How I Met Your How I Met Your New Adv./Old How I Met Your How I Met Your Reba “Regarding Reba “The Great Reba “Thanksgiving” Upstairs” Race” Henry” Mother Å Å Mother Mother Christine Mother (:00) Movie: “Best Friends” (2005) Megan Movie: “Viewers’ Choice” Å Movie: “Viewers’ Choice” Å Gallagher, Claudette Mink. Å The Ed Show Hardball With Chris Matthews Countdown With K. Olbermann The Rachel Maddow Show The Last Word Countdown With K. Olbermann Monster Fish Border Wars “No End in Sight” Dog Whisperer (N) Unlikely Animal Friends 2 (N) Unlikely Animal Friends Dog Whisperer George Lopez George Lopez Glenn Martin, The Nanny (In The Nanny (In iCarly (In Stereo) iCarly (In Stereo) iCarly (In Stereo) Big Time Rush Victorious (In Everybody Å Å Å Å Å Å Stereo) Å Hates Chris DDS Å Stereo) Å Stereo) Å Law Order: CI Law & Order: Criminal Intent Law & Order: Criminal Intent Law & Order: Criminal Intent Law & Order: Criminal Intent Law & Order: Criminal Intent Ways to Die Ways to Die Ways to Die Movie: ››› “Grindhouse Presents: Death Proof” Movie: “Grindhouse Presents: Planet Terror” (2007) Eastern Golf Million Dollar Challenge Million Dollar Challenge Million Dollar Challenge 3 Wide Life Raceline (N) Unique Auto. Brawl Call (5:30) Movie: ››› “28 Days Later” (2002) Cillian WWE Friday Night SmackDown! (N) (In Stereo) Å Merlin (Season Premiere) Merlin Stargate SG-1 “Off the Grid” The Murphy, Noah Huntley. Å and Arthur recover. Å team plans an offensive. The King of Seinfeld (In Seinfeld “The Movie: ›› “The Wedding Planner” (2001) Jennifer Lopez, Matthew McConaughey, (:25) The Office (10:55) Glory Daze “Shamrock You Queens Å Stereo) Å Bris” Å Bridgette Wilson-Sampras. Å Like a Hurricane” Å (:15) Movie: ››› “Cat Ballou” (1965) Jane Fonda, Movie: ››› “The Fastest Gun Alive” (1956) Glenn Ford. A gunsling- Movie: ›››‡ “State Fair” (1945) Jeanne Crain, Dana Andrews, Dick Lee Marvin. Å er’s son avoids his father’s legacy. Å Haymes. Å Say Yes Say Yes Say Yes Say Yes Say Yes Say Yes Say Yes Say Yes Four Weddings (N) Å Say Yes Bones Corpse at the bottom of a Movie: ›››‡ “Forrest Gump” (1994) Tom Hanks, Robin Wright, Gary Sinise. Å (:00) Law & (:45) Movie: ››› “The Terminal” (2004) Tom Order (In Stereo) gorge. (In Stereo) Å Hanks. Premiere. Å Police Video Cops Å Most Shocking Cops Å Most Shocking Las Vegas Jail Las Vegas Jail Forensic Files Forensic Files Roseanne Roseanne EverybodyEverybodyEverybody(:18) All in the (6:53) Sanford & (:26) Sanford & Sanford & Son Sanford & Son Everybody“Bingo” Å “Santa Claus” Raymond Raymond Son Å Raymond Family Son Å Raymond Å House Wilson’s newly revealed (:00) House Movie: ››› “Inside Man” (2006) Denzel Washington, Clive Owen, Jodie Foster. Å Movie: ›››‡ “No Country for Old Men” (2007) relationship. (In Stereo) Å “Frozen” Tommy Lee Jones. Å W. Williams Meet, Browns Meet, Browns Dr. Phil (In Stereo) Å The Oprah Winfrey Show Eyewitness Entertainment The Insider Inside Edition Dharma & Greg New Adv./Old New Adv./Old New Adv./Old New Adv./Old How I Met Your How I Met Your WGN News at Nine (N) (In Stereo) Scrubs (In Scrubs J.D. is Mother Mother Christine Christine Å Å Christine Christine Stereo) Å pushed aside.
PREMIUM CHANNELS HBO
Movie: ››› “Solaris” (2002) George Clooney. 24/7 Penguins/Capitals: Road to Movie: ››‡ “Edge of Darkness” (2010) Mel Gibson, Ray Winstone, Ricky Gervais: Out of England 2 15 (:15) (In Stereo) Å the NHL Winter Classic Danny Huston. (In Stereo) Å - The Stand-Up Special
HBO2
Movie: ››‡ “The Book of Eli” (2010) Denzel Washington, Gary Boxing’s Best of 2010 (In Stereo) Boxing’s Best of 2010 (In Stereo) Movie: ›‡ “The Unborn” (2009) Oldman, Mila Kunis. (In Stereo) Å (In Stereo) Å Å Å (5:15) “Liberty Movie: ››› “The American President” (1995) Michael Douglas, Movie: ›› “The Uninvited” (2009) Elizabeth Banks, Movie: ››‡ “Pride and Glory” (2008) Edward 304 Stands Still” Annette Bening, Martin Sheen. (In Stereo) Å Arielle Kebbel. (In Stereo) Å Norton. (In Stereo) Å (:45) Movie: ›› “National Security” (2003) Martin (:15) Movie: ›‡ “The Tuxedo” (2002) Jackie Chan, Jennifer Love Movie: ››‡ “The Wolfman” (2010) Benicio Del (:45) Life on 320 Lawrence. (In Stereo) Å Hewitt, Jason Isaacs. (In Stereo) Å Toro. (In Stereo) Å Top Å (:15) Movie: ›››‡ “Inglourious Basterds” (2009) Brad Pitt, Mélanie Laurent, Christoph Waltz. iTV. (In Strikeforce Challenger Series (:00) Movie: ›››‡ “The Hurt Locker” (2008) 340 Jeremy Renner. iTV. (In Stereo) Stereo)micro. United FeatUre Syndicate
United FeatUre Syndicate
Today’s celebrity birthdays Singer Kenny Loggins is 63. Singer-songwriter Marshall Chapman is 62. Actor David Caruso is 55. Country singer David Lee Murphy is 52. Bassist Kathy Valentine of The Go-Go’s is 52. Actress Hallie Todd (“Lizzie McGuire”) is 49. Actor Nicolas Cage is 47. Singer John Ondrasik of Five for Fighting is 46. Actor-rapper Doug E. Doug is 41. Actor Kevin Rahm is 40. Country singer John Rich of Big and Rich is 37. Actor Dustin Diamond is 34. Actor Liam Aiken (“Lemony Snicket”) is 21.
my’s two heart tricks, played a trump to his ace, ruffed his last heart on the board, noting West’s queen, cashed the club king, and played a club to his queen. Clearly West had begun with 2-3-5-3 distribution and was a candidate for a Morton’s Fork. Declarer led his spade nine, leaving West with no riposte. If West had played his 10, a second round of spades would have endplayed him to open up diamonds. And when West won with his ace and returned the spade 10, South took his queen, played a club to dummy’s 10, and discarded two diamonds on the king-jack of spades.
BY PHILLIP ALDER United Feature Syndicate
To end the week, let’s look at a couple of deals that made the short lists for the International Bridge Press Association awards and caught my eye but not that of the jury. If you were South, how would you plan the play in five clubs after West leads a low heart? North’s one-heart response showed four or more spades; his double was for takeout; and his three-diamond cue-bid asked partner to bid three no-trump with a diamond stopper. Then North did well not to pass, because three no-trump would have been hopeless after a diamond lead. The declarer was Yury Khiuppenen, playing for Russia in the 2009 Bermuda Bowl in Brazil. He was confident that West had the
diamond ace. And if East had the spade ace, the contract was doomed. Should declarer play a spade to his nine, hoping East had the 10 and establishing three spade tricks? Maybe — but that could wait. Khiuppenen took dum-
COMPLETE AUTO SERVICE
R128700
Dear Dr. Gott: I am a 58yearDR. PETER headedness, diarrhea, GOTT dizziness, temporary blurred vision, low potassium and loss of appetite. Severe allergic reactions can produce hives, difficulty breathing, low urine output, muscle pain or cramps and more. Accupril is an angiotensinconverting
You might take it upon yourself to establish far more important objectives than usual in future months. Whether or not you’ll be able to do all of them will depend upon your knowledge, skills and the time you have allotted. ‘em. plans. Know where to look for romance and you’ll find it. The Astro-Graph Matchmaker instantly reveals which signs are romantically perfect for you. Mail $3 to Astro-Graph, P.O. Box 167, Wickliffe, OH 44092-0167.
He gets the lead and loses a trick
SHOWPLACE OF KANNAPOLIS CANNON VILLAGE
704-932-5111 111 West First Street Kannapolis, NC 28081
Tires & exide
Batteries Granite Auto Parts & Service
209-6331
704/
Hwy. 52 Granite Quarry
38
Eye twitch requires investigation
67
SHOW
12
MAX
R
HBO3
Movie: 302 (4:30) “Rob Roy”
Friday, Jan. 7
OPEN AT 1:45PM MON–THURS
THE CHRONICLES OF NARNIA: VOYAGE DAWN TREADER (PG) Fri. 4:45, 7:00 Sat-Sun. 2:30, 4:45, 7:00 Mon.-Thurs. 7:00
R129065
Before 6:00 PM $3.00 For All Persons-All Ages After 6:00 PM $4.00 For Adults, $3.00 for 2-12 and 55+
ADMISSION
12B • FRIDAY, JANUARY 7, 2011
SALISBURY POST
W E AT H E R
No Games ★★★ No Gimmicks ★★★ GOOD PEOPLE TO DEAL WITH ★★★ Save Up To $13,000
SHOP 24 HRS @ larrykingchevy.com
From all of us at
0
%
Family Owned & Operated KANNAPOLIS
Financing Available
2011 HHR LS
New 2011 CRUZE LS
New 2011 MALIBU
Stk#5772
Stk#5756
Stk#5723
Sale Price $
15,581
16,590
Sale Price $
NEW 2011 COLORADO EXT CAB NEW 2011 CAMARO 1LT Stk#5750
1LT,AUTO,POWER PKG. STOCK #5707
Sale Price $
Sale Price $
18,598
Sale Price $
25,490
18,896
New 2011 SILVERADO Reg Cab WT
New 2011 SILVERADO EXT. CAB
New 2011 SILVERADO Crew Cab LT
New 2011 TRAVERSE LS
NEW 2010 TAHOE 4WD LT
Stk#5720
Stk#5686
Stk#5706
Stk#5710
Stk#5629 • DEMO SUGG PRICE 52,580
16,555
Sale Price $
Sale Price
$
25,237
Sale Price $
22,986
Sale Price $
25,990
Demo Sale Price $
44,397 Total Savings
$
97 Buick LeSabre 07 Ford Focus SE local trade in very clean and low miles!!!
AC, Very Clean, Stk#5210A
$
4,450
08 Hyundai Sonata 03 Jeep Grand GLS Cherokee Laredo One owner local trade in clean vehicle history leather,
$
06 Honda Civic EX one owner, very clean, only 36k
12,990
09 Chevrolet Impala
17,450
13,990
09 Buick Lucerne CXL
2010 Equinox LT
12,995
GM factory certified, low miles and lots of options stk P1409
Low miles and lots of optopns! Stk. 5527A
$
$
$
$
18,995
$
20,995
10,450 09 Chevrolet HHR LT
Auto, Low Miles, Very Clean
$
12,990 09 Jeep Grand Cherokee 4WD, one owner, low miles,
$
10,990 07 Chevy Trailblazer LT GM Factory certfied $15,490
GM factory certified, low miles
$
clean vehicle history. Stk#P1450
$16,995 13,990 04 Chevrolet 07 GMC Sierra 2500 07 Cadillac Durmax Crew Cab Escalade AWD Corvette Conv HD Running Boards, Power Pkg and Much one owner showroom condition a
GM certified, low miles lots of options
$
04 Ford Ranger Super Cab XLT
Auto, AC, Low Miles and More!! Stk#P1440
$
GM Factory Certified, GM Factory Certified 2.9% Fin For 60 Very Clean, Local Trade In, #5725a Mo Stk P1438
12,990 08 Hyundai Sonata 2005 Yukon XL FE V6 GLS 4wd leather,bose system,on star,clean vehicle history
9,995 08 Saturn Vue
8,990
$
very clean, low miles stock #5640b
$
$
Sporty One Owner Auto With Lots Of Options. Stk P1462
$
Very Clean And Well Equipped! Stk 5210A
sunroof and more
7,495 08 Dodge Charger
09 Chrysler Sebring LX
2005 Ford Fusion SEL
8,183
29,995
$
$
29,990
23,450
22” chrome wheels, NAV, rear entertainment & more
More! Stk 5778
nd only 5,000 miles!!!
$
33,995
704-933-1104 800-467-1104 I-85 Exit 58 - 1 Mile • 1520 South Cannon Blvd. • KANNAPOLIS
SHOP 24 HRS @
KANNAPOLIS
All prices are plus tax, tag, title and DOC fee. All prices are after all rebates and incentives that are applicable including GM Loyalty Bonus Cash.
5-Day 5-D ay Forecast for for Salisbury Salisbury
National Cities
Today
Tonight
Saturday
Sunday
Monday
Tuesday
High 45°
Low 22°
43°/ 18°
38°/ 25°
34°/ 25°
34°/ 20°
Chance of snow showers
Partly cloudy
Mostly sunny
Chance of snow
Chance of snow
R128784
Your Source for: • Vegetable Plants • Perennials
Greenhouse Supplies! Plant Pharmacy!
This winter view our 30,000 sq. ft. indoor nursery in any kind of weather!
4070 Woodleaf Rd., Salisbury 704-636-7208
Kn K Knoxville le 36/25
Boone 29/ 29/18
Frank Franklin n 38 3 38/25 5
Hi Hickory kkory 41/22
A Asheville s ville v lle 3 36 36/22
Sp Spartanburg nb 47/2 47/25
Kit Kittyy Haw H Hawk w wk 47 47/31 7//31 7 1
Ral Raleigh al 4 43/27
Charlotte ha t e 45/23
Co C Col Columbia bia 50/ 50/29
... ... .. Sunrise-.............................. Sunset tonight Moonrise today................... Moonset today....................
Darlin D Darli Darlington 49/29 /2 /29
A Augusta u ug 5 52 52/ 52/29 2/ 9 2/29
7:32 a.m. 5:24 p.m. 9:21 a.m. 8:50 p.m.
Jan 12 Jan 19 Jan 26 Feb 2 First F Full Last New
Aiken ken en 50/ 50 50/29 /2 2
A Al Allendale llen e ll 5 54/31 /31 31 Savannah na ah 56/34 4
Moreh Mo M Morehead o ehea oreh orehea hea ad C ad Ci Cit City ittyy ity 4 9 47/29
Forecasts and graphics provided by Weather Underground @2011
Myrtle yr le yrtl eB Be Bea Beach ea each 4 49 49/32 9//32 9/3 9 /3 Ch Charleston rle les es 5 52 52/36 H Hilton n He Head e 5 52/ 52/38 2///38 8 Shown is today’s weather. Temperatures are today’s highs and tonight’s lows.
LAKE LEVELS Lake
Today Hi Lo W 41 19 pc 54 36 pc 63 49 pc 69 51 pc 17 -2 fl 67 47 s 33 21 sn 33 11 cd 34 24 sn 64 43 pc 24 12 37 22 sn
Tomorrow Hi Lo W 28 17 pc 56 36 pc 61 46 pc 74 52 pc 10 -11 pc 59 48 pc 32 22 pc 20 8 cd 32 20 pc 59 42 pc 36 18 sn 34 20 pc
Today Hi Lo W 62 46 s 51 44 r 17 10 pc 51 46 pc 86 73 pc 26 8 s 42 32 pc
Tomorrow Hi Lo W 57 42 r 50 35 r 32 19 sn 51 35 r 86 73 pc 35 13 pc 50 35 s
Pollen Index Salisburry y Today: Saturday: Sunday: -
High.................................................... 46° Low..................................................... 33° Last year's high.................................. 41° Last year's low.................................... 18° ....................................18° Normal high........................................ 51° Normal low......................................... 32° Record high........................... 73° in 1950 Record low............................... 5° in 1924 ...............................5° Humidity at noon............................... 49% ...............................49%
Air Quality Ind Index ex Charlotte e Yesterday.... 54 ........ .... moderate .......... particulates Today..... 28 ...... good N. C. Dept. of Environment and Natural Resources 0-50 good, 51-100 moderate, 101-150 unhealthy for sensitive grps., 151-200 unhealthy, 201-300 verryy unhealthy, 301-500 haazzardous
24 hours through 8 p.m. yest......... 18.52" 0.42" Month to date................................... ...................................0.42" Normal year to date......................... 0.73" Year to date..................................... ...................... .. .. 0.42" 2 -10s
Se ea at Seattle S ttllle e e atttl 50/37 5 50 0 0///3 37
-0s 0s
Southport outh uth 4 49/32
Above/Below Observed Full Pool
High Rock Lake............. 647.88.......... -7.12 ..........-7.12 ..........-1.53 Badin Lake.................. 540.47.......... -1.53 Tuckertown Lake............ 595.3........... -0.7 Tillery Lake.................. 278.1.......... -0.90 Blewett Falls.................177.8 ................. 177.8.......... -1.20 Lake Norman................ 97.40........... -2.6
City Jerusalem London Moscow Paris Rio Seoul Tokyo
Almanac
Precipitation Cape Ha C Hatteras atter atte attera tte ter era ra ass a 47 4 47/3 47/32 7/3 7/ /32 3
W Wilmington to 49/31
Atlanta 49/29
SUN AND MOON
Go Goldsboro bo b 45/29
L Lumberton b be 47 47/27 7
G Greenville n e 45/27 27
City Kansas City Las Vegas Los Angeles Miami Minneapolis New Orleans New York Omaha Philadelphia Phoenix Salt Lake City Washington, DC
Tomorrow Hi Lo W 46 32 r 33 8 pc 59 50 pc 46 35 pc 91 64 pc 15 -2 sn 41 32 s
Data from Salisbury through ough 6 p.m. yest. Temperature
Danville D l 43/20 Greensboro o Durham D h m 40/25 43/27 27 7
Salisbury Salisb S alisb sb b y bury 45/22 22
Tomorrow Hi Lo W 44 24 pc 36 20 pc 32 20 fl 33 7 sn 32 24 fl 23 14 pc 22 18 fl 55 40 cd 46 21 pc 25 15 fl 7 -5 pc 24 14 fl
Today Hi Lo W 42 37 r 32 17 s 64 48 pc 41 35 pc 86 73 pc 30 8 pc 39 26 pc
City Amsterdam Beijing Beirut Berlin Buenos Aires Calgary Dublin
Regional Regio g onal W Weather eather Winston Win Wins Salem a 40/ 5 40/25
Today Hi Lo W 51 29 pc 37 21 sn 35 20 sn 36 7 sn 34 25 sn 22 11 sn 21 18 fl 66 35 pc 47 21 pc 22 17 fl -2 -14 fl 25 13 fl
10s
B Billings iilllllin in ng g gss
n nn n ne e ea a ap p po Minneapolis M iin oliiss
36/7 3 7 6 6///7
17/-2 1 7 17 7///---2 2
20s
San Sa an n Francisco Francisco Fr rancisco an nccis isc sco
30s
54 54 54/43 4//4 /4 43 3
H
L
3 33 3 3/21 //21 2 21 1 33/21
D e etroit trroit oit it Detroit Denver D e en n nver vver e err
50s
4 47 47/21 7 7///2 2 21 1
60s 70s
Ne New ew wY York Yo o orrrkk
22/11 2 22 2 2///11 /1 1 11 1
40s
80s
L
Chicago C h hiiiccca a ag g go o
2 22/17 22 2//1 17
Los L os A os Angeles An n ng g ge elle e ess
Kansas K Ka a ansas n nsssas as City as Cit ity
63/49 6 49 9 3//4 4
44/20 44/20 4//20 20 20
L
Cold Front
3 37 7///2 7 22 37/22 2 2
5 51 51/29 1//2 1/ 29
63 6 63/38 3//3 3/ 3 38 8 a am m mii Miami M iia
100s
69/51 5 1 69//5 51
Staationary 110s Front Showers T-storms -sttorms
W a asssh hin ing ng gttton o on n Washington
A Atlanta tlla an an nttta a Ell P E Paso aso
90s Warm Front
H Houston o ou u usssttton o on n
Rain n Flurries rries
Snow Ice
7 70 0/4 0/ /4 46 6 70/46
WEATHER UNDERGROUND’S NATIONAL WEATHER
Kari Kiefer Wunderground Meteorologist
C47623
Toll Free
The Pacific Northwest remains wet and snowy, while snow also persists across the the Northeast on Friday. A low pressure system over the Great Lakes will continue moving eastward and into the Northeastern US. Throughout the day, this system will push a cold front southeastward over the Ohio River Valley and toward the East Coast. Expect more snow across the northern Appalachian Mountains with accumulation ranging from 2 to 4 inches. Heavier snowfall is likely along the western and northwestern areas of the Appalachians, as upslope flow will aid in the development of snowfall. More lake effect snow will develop over the eastern shores of the Great Lakes as strong flow from the west persists. Cold air from Canada will pour in behind this system. Expect cold conditions to persist in the Northern Plains and Upper Midwest with highs ranging in the teens and overnight lows dipping to the negative teens. Strong winds with gusts up to 25 mph are also expected, thus, wind chills overnight will dip into the negative 30s. The Midwest and Ohio River Valley will remain slightly warmer with highs in the 20s and 30s. Out West, a low pressure system dips in from British Columbia and pushes a front over the Pacific Northwest. This system brings more rain to Washington and Portland, with snow in the Cascades and Northern Rockies. High pressure will remain over California and the Southwest, allowing for more cool and sunny weather. In the South, high pressure dominates the Southeastern US and allows for cool and dry conditions. Highs in the 50s and 60s will prevail with overnight lows in the 30s. A cold front moving through the Southern Plains will create another chilly day for Texas and Oklahoma.
Get the Whole Picture at wunderground.com wunderground.com—The —The Best Known Secret in Weather™ | https://issuu.com/salisburypost/docs/01072011-sls-a01 | CC-MAIN-2017-17 | refinedweb | 39,710 | 75.2 |
Hello, I just created a MongoDB database following this tutorial: and everything works fine when I’m accessing a database from the mongo shell but I can’t connect to the database using node.js
This is my code:
import mongoose from 'mongoose'; mongoose.connect('mongodb://user:pass@droplet_ip:27017/my_database', (err, res) => { if(err) { console.log(err); } else { console.log('connected'); } })
And this is the error:
{ MongoError: failed to connect to server [droplet_ip:27017] on first connect [MongoError: connection 0 to droplet_ip:27017 timed out] at Pool.<anonymous> (/node_modules/mongodb-core/lib/topologies/server.js:336:35) at emitOne (events.js:96:13) at Pool.emit (events.js:189:7) at Connection.<anonymous> (/node_modules/mongodb-core/lib/connection/pool.js:280:12) at Object.onceWrapper (events.js:291:19) at emitTwo (events.js:106:13) at Connection.emit (events.js:192:7) at Socket.<anonymous> (/node_modules/mongodb-core/lib/connection/connection.js:197:10) at Object.onceWrapper (events.js:291:19) at emitNone (events.js:86:13) at Socket.emit (events.js:186:7) at Socket._onTimeout (net.js:342:8) at ontimeout (timers.js:365:14) at tryOnTimeout (timers.js:237:5) at Timer.listOnTimeout (timers.js:207:5) name: 'MongoError', message: 'failed to connect to server [droplet_ip:27017] on first connect [MongoError: connection 0 to droplet_ip:27017 timed that your mongodb is running. Check
docker lsresult, you should see both your app and mongo at
upstatus. if your mongo is missing or down, that is the problem
If you followed Part Three: Configuring Remote Access (Optional) of the “Install and Secure Mongodb” article, make sure you’ve didn’t accidentally firewall off the droplet running the express app from connecting to the mongodb droplet.
Are you able to connect to monodb from the mongo shell ON the droplet that is running the express app?
message: ‘failed to connect to server [droplet_ip:27017] on first connect [MongoError: connection 0 to droplet_ip:27017 timed out]’ }
Maint take away from the error message is it “Timed Out”, so I’m thinking its unable to connect, or something is blocking it from connecting.
Does the express app droplet have any outgoing firewall rules?
Please replace droplet_ip with ip first. | https://www.digitalocean.com/community/questions/how-to-connect-node-js-to-a-mongodb-droplet | CC-MAIN-2022-40 | refinedweb | 368 | 52.36 |
(9)
Mahesh Chand(7)
Rajesh VS(7)
G Gnana Arun Ganesh(5)
Dipal Choksi(4)
Pramod Singh(3)
John O Donnell(3)
Levent Camlibel(3)
Manisha Mehta(3)
Jason Zadroga(2)
Hari Shankar(2)
andrew.phillips (2)
Shivani (2)
Amisha Mehta(2)
Prasad (2)
Sanjay 0(2)
Tushar Ameta(2)
Ashish Jaiman(2)
Jigar Desai(2)
Giuseppe Russo(2)
Abhijeet Warker(1)
Hari Sankar(1)
sayginteh (1)
Sudhakar Jalli(1)
C Vinod Kumar(1)
manish Mehta(1)
Caonabo Ruiz(1)
Ashish Banerjee(1)
Vivek Gupta(1)
K Niranjan Kumar(1)
Kunal Cheda(1)
Fons Sonnemans(1)
Paul Abraham(1)
Junaid Majeed(1)
Prasad H(1)
Dipal Choksi(1)
Filip Bulovic(1)
sami_danish (1)
Luke Venediger(1)
David Talbot(1)
Leonid Molochniy(1)
Markus Kalina(1)
R. Seenivasaragavan Ramadurai(1)
Kunle Loto(1)
chandrakant upadhyay(1)
S.R.Ramadurai, K.Sreenivasan(1)
Ricardo Federico(1)
Mark Johnson(1)
Shripad Kulkarni(1)
Doug Bell(1)
Paul Trott(1)
Tin Lam(1)
Simon Harris(1)
Srimani Venkataraman.
ColorDialog in C#
Dec 21, 2000.
A ColorDialog control is used to select a color from available colors and also define custom colors. This article demonstrates how to use a ColorDialog in Windows Forms and C#.
Calling a COM Component From C# (Late Binding)
Jan 08, 2001.
This code sample shows how to call a COM component in .NET framework using C#..?.
Compilation and Runtime Execution of a C-Sharp Program
Apr 10, 2001.
C-Sharp (C#) is a strongly typed object-oriented programming language designed to give optimum composition of simplicity, expressiveness and performance..
Defining Custom Entry Points
Apr 30, 2001.
In this article i am going to demonstrate how we can manipulate the IL code to change the behaviour of how the .NET programme executes.
Using .NET Framework Multithreading and GDI+ to Enrich the user experience
May 04, 2001.
This tutorial shows you how to create, send, and received messages using MSMQ from the .NET base class library (System.Messaging) and C#.
.
Events and Delegates
Jul 26, 2001.
Events in C# are based on delegates, the Originator defining one or more callback functions as delegates and the listening object then implements then..
Compute Feature of DataTable
Aug 01, 2001.
The following code is for implementing least known feature of DataTable Compute() method.
Text Reader and Text Writer in C#
Aug 03, 2001.
A detailed tutorial and C# types such as Value and Reference types with sample examples.
NumberBox ASP.NET Control
Aug 08, 2001.
The NumberBox control is an ASP.NET control, which lets the user only input numerical values..
Super String in C#
Aug 20, 2001.
Today I realized that I miss those Visual Basic/Visual C++ type operators. You know the ones: Left, Mid, Right...
Mapping Objects to Relational Databases
Nov 01, 2001.
The application generates C# Class files for each table in a relational database. I have used Mysql and ODBC.NET for this project. The application only supports MySQL right now.
Implementing Stacks in C#
Nov 06, 2001.
With the help of C# we can also implement ADT (Abstract Data Types) with little effort. An example of ADT is a simple stack of integers. 2
Nov 12, 2001.
This is the second part of the series of articles about the network programming with C#.
Nov 16, 2001.
Email notifier with Microsoft Agent is a TCP/IP application that notifies the user if there is email in the user's email server..
Creating a User Control: .NET Toggle Control
Nov 16, 2001.
This is a C# User Control which re-creates the toggle used by XML, HTML, etc. files in the .NET Developer Studio. Just compile the control and drag it onto a form from the Windows Form Toolbox..
Operator Overloading in C#
Dec 03, 2001.
All unary and binary operators have pre-defined implementations, that are automatically available in any expressions. In addition to this pre-defined implementations, user defined implementations can also be introduced in C#..
Working With Data Types
Jan 02, 2002.
Explains data types in C# and how to work with them.
Adapter Pattern in C#
Jan 03, 2002.
The Gang Of Four (GoF) defined the Adaptor pattern as follows in their most famous book "Design Patterns" Gamma et al. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces."
Playing with DataGrid Control
Jan 08, 2002.
The article gives a user the overview to show the importance and versatility of the DATAGRID control.
Interrogating Systems with WMI
Jan 18, 2002.
WMI allows you to retrieve information such as hardware types, software installed and much much more..
Implementing IEnumerator and IEnumerable Interfaces using Inner Class in C#
Feb 28, 2002.
.NET framework provides IEnumerable and IEnumerator interfaces to implement collection like behavior to user defined classes.
SOAP Message with Binary Attachments
Feb 28, 2002.
Recently Microsoft announced new format called DIME: Sending Binary Data with Your SOAP Messages.
Sorting Object Using IComparer and IComparable Interfaces
Mar 01, 2002.
The System.Collections namespace contains interfaces and classes that define various....
Boxing and Performance of Collections
Mar 14, 2002.
In this article, I will compare some performance issues of values and references types during boxing and unboxing operations.).
.NET Remoting: The Interface Approach
Mar 26, 2002.
In this article, we will create a remote object, and access this object using the Interface. The object returns rows from a database table.
Simple NSLookUp Implementation in C#
Apr 01, 2002.
This is code implementation for simple nslookup. As you can see from the code listing, I've used classes defined in the System.Net namespace.
BattleShips Games
Apr 02, 2002.
This application presents a grid of 100 squares to the user. The user has thirty five attempts to find to find the computers fleet. The computer randomly positions five ships of varying sizes around the board.
Multithreading Part 2: Understanding the System.Threading.Thread Class
Apr 08, 2002.
In this article we will study the .NET threading API, how to create threads in C#, start and stop them, define their priorities and states.
Reflecting Data in .NET Classes - Part IV: From Database Table
Apr 08, 2002.
In this article, we will be looking at how to "reflect" data from the most common data source - Database tables..
Mastermind Game with Drag and Drop Functionality
May 15, 2002.
There as nice article some time ago on this site for creating mastermind game by Mike Gold. I am rewriting complete game from scratch to implement Drag and Drop feature and presentable User interface.
Assembly Browser: Browsing a .NET Assembly
May 17, 2002.
This program lets you browse an assembly and lists the methods and the parameter name and parameter type for each assembly.#.
Form Authentication for Mobile Applications
May 28, 2002.
In this example we will authenticate mobile web users for our application using Forms Authentication.. | http://www.c-sharpcorner.com/tags/User-Defined-Table-Types | CC-MAIN-2016-36 | refinedweb | 1,135 | 60.01 |
The challenge
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a “Double Cola” drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, drinks it and gets to the end of the queue as two Leonards, and so on.
For example, Penny drinks the third can of cola and the queue will look like this:
Rajesh, Howard, Sheldon, Sheldon, Leonard, Leonard, Penny, Penny
Write a program that will return the name of the person who will drink the
n-th cola.
Input:
The input data consist of an array which contains at least 1 name, and single integer
n which may go as high as the biggest number your language of choice supports (if there’s such limit, of course).
Output / Examples:
Return the single line — the name of the person who drinks the n-th can of cola. The cans are numbered starting from 1.
let names = &[Name::Sheldon, Name::Leonard, Name::Penny, Name::Rajesh, Name::Howard]; assert_eq!(who_is_next(names, 1), Name::Sheldon); assert_eq!(who_is_next(names, 6), Name::Sheldon); assert_eq!(who_is_next(names, 52), Name::Penny); assert_eq!(who_is_next(names, 7230702951), Name::Leonard);
Courtesy of CodeForces:
Test cases
import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class ListTests { @Test public void test1() { String[] names = new String[] { "Sheldon", "Leonard", "Penny", "Rajesh", "Howard" }; int n = 1; assertEquals("Sheldon", new Line().WhoIsNext(names, n)); } @Test public void test2() { String[] names = new String[] { "Sheldon", "Leonard", "Penny", "Rajesh", "Howard" }; int n = 6; assertEquals("Sheldon", new Line().WhoIsNext(names, n)); } }
The solution using Java
public class Line { public static String WhoIsNext(String[] names, int n) { n = n - 1; int len = names.length; while(n >= len) { int div = n-len; n = (int)Math.floor(div/2); } return names[n]; } } | https://ao.gl/solving-the-double-cola-challenge-using-java/ | CC-MAIN-2020-40 | refinedweb | 328 | 73.88 |
Arrays in C++ Programming
Array is a collection of data of same types stored in sequential memory location. It is a linear data structure, where data is stored sequentially one after the other. The elements in an array is accessed using an index. For example, In an array of n elements, the first element has index zero and the last element has index (n-1). Elements with consecutive index (i.e. i and i+1) are stored in consecutive memory location in the system.
Array can be divided into following types:
One Dimensional Array
An array in which data are arranged linearly in only one dimension is called one dimensional array. It is commonly known as 1-D array
Syntax and Declaration of One Dimensional Array
datatype array_name[size];
Here, array_name is an array of type datatype and the number of elements in array_name is equal to size.
For example,
int x[10]; // declares an integer array with 10 elements float arr[5]; // declares an float array with 5 elements char n[50]; // declares an character array with 50 elements
Arrangement of One Dimensional Array
Example of One Dimensional Array
C++ program to ask 10 numbers from user and display the sum.
#include <iostream> #include <conio.h> using namespace std; int main() { int arr[10],sum=0,i; cout<<"Enter 10 numbers"<<endl; for(i=0;i<10;i++) { cin>>arr[i]; sum = sum+arr[i]; } cout<<"Sum = "<<sum; getch(); return 0; }
Here, a one dimensional array arr of size 10 is declared. Ten numbers are entered by user which is stored in the array arr. Then the sum of these numbers is calculated using a for loop. Finally the sum is displayed outside the loop.
Output
Enter 10 numbers 13 52 4 -41 32 11 19 7 2 25 Sum = 124
Multi-Dimensional Array
An array in which data are arranged in the form of array of arrays is called multi-dimensional array. An array can have as much dimensions as required. However, two dimensional and three dimensional array are commonly used.
Syntax
Two dimensional array is where the data is stored in a list containing 1-D a[10][10]; // declares an integer array with 100 elements float f[5][10]; // declares an float array with 50 elements char n[5][50]; // declares an character array with 250 elements
Arrangement of Two Dimensional Array
Example of Two Dimensional Array
C++ program to enter elements of a matrix and display them.
#include <iostream> #include <conio.h> using namespace std; int main() { int arr[10][10],row,col,i,j; cout<<"Enter size of row and column: "; cin>>row>>col; cout<<"Enter elements of matrices(row wise)"<<endl; for(i=0;i<row;i++) for(j=0;j<col;j++) cin>>arr[i][j]; cout<<"Displaying matrix"<<endl; for(i=0;i<row;i++) { for(j=0;j<col;j++) cout<<arr[i][j]<<" "; cout<<endl; } getch(); return 0; }
In this program, a two dimensional array is used to store the content of a matrix. The size of row and column is entered by user. Nested for loop is used to ask the content of elements of matrix and display them. The number of elements in the array (matrix) is equal to the product of size of row and column.
Output
Enter size of row and column: 2 3 Enter elements of matrices(row wise) 12 31 51 19 13 24 Displaying matrix 12 31 51 19 13 24
Example of Three Dimensional Array
C++ program to show the concept of three dimensional array.
#include <iostream> #include <conio.h> using namespace std; int main() { int arr[10][10][10],d1,d2,d3,i,j,k; cout<<"Enter size of three dimensions: "; cin>>d1>>d2>>d3; cout<<"Enter elements of array"<<endl; for(i=0;i<d1;i++) for(j=0;j<d2;j++) for(k=0;k<d3;k++) { cout<<"a["<<i<<"]["<<j<<"]["<<k<<"] = "; cin>>arr[i][j][k]; } cout<<"Displaying elements of array"<<endl; for(i=0;i<d1;i++) for(j=0;j<d2;j++) for(k=0;k<d3;k++) cout<<"a["<<i<<"]["<<j<<"]["<<k<<"] = "<<arr[i][j][k]<<endl; getch(); return 0; }
This example show how data.
Output
Enter size of three dimensions: 3 2 2 Enter Displaying
Accessing elements of array
Elements of an array can be accessed by using array name and index of element to be accessed.
For example, consider a one dimensional array
int a[5];
Third element of this array can be accessed as a[2].
Note: First element of array has index 0 and so on.
Elements of multi dimensional array can be accessed similarly as one dimensional array.
For example, consider a two dimensional array
float x[5][10];
Now, element of second row and fifth column can be accessed as x[1][4].
Array of Objects
As we know, array is a collection of similar data types. Since class is also an user-defined data type, we can create the array of variables of class type which is called array of objects. These objects are stored sequentially in the memory. The memory occupied by each object is equal to the sum of memory occupied by its data members.
Syntax And Declaration of Array of Objects
classname objectname[size];
Similarly, the public members of these objects can be accessed as follows:
objectname[index].function_name([arguments]); objectname[index].data_name = value;
The private members can be accessed through member functions.
Example of Array of Objects
C++ program to get and print array of objects.
#include <iostream> #include <conio.h> using namespace std; class student { char name[100]; int roll,age; public: void input() { cout<<"Name : "; cin>>name; cout<<"Roll : "; cin>>roll; cout<<"Age : "; cin>>age; } void output() { cout<<"Name : "<<name<<endl; cout<<"Roll : "<<roll<<endl; cout<<"Age : "<<age<<endl; } }; int main() { student s[3]; int i; cout<<"Enter student's info"<<endl; for(i=0;i<3;i++) { cout<<"Student "<<i+1<<endl; s[i].input(); } cout<<endl<<"Displaying student's info"<<endl; for(i=0;i<3;i++) { cout<<"Student "<<i+1<<endl; s[i].output(); } getch(); return 0; }
A class student is created in this program. It consists of name,age and roll as data members and input() and output() as member functions. An array of objects of class student is created in main() function. For each object in the array, input() function is called to enter data and output() function is called to display data. These functions are called inside a for loop.
Output
Enter student's info Student 1 Name : Jack Roll : 11 Age : 23 Student 2 Name : David Roll : 23 Age : 21 Student 3 Name : Jim Roll : 24 Age : 22 Displaying student's info Student 1 Name : Jack Roll : 11 Age : 23 Student 2 Name : David Roll : 23 Age : 21 Student 3 Name : Jim Roll : 24 Age : 22 | https://www.programtopia.net/cplusplus/docs/arrays | CC-MAIN-2019-30 | refinedweb | 1,142 | 51.18 |
With Felgo you can create powerful standalone apps and games for multiple platforms. It is however also possible to integrate Felgo content into existing apps. You can load complete QML files with all Felgo features in Android and iOS apps. This guide explains the necessary steps to integrate QML with existing applications.
Integrating Felgo and QML in existing native apps has many beneficial use cases:
You can find examples of integrating Felgo and QML with existing apps on our Github page:
First set up your project to enable loading QML content from a native Android application.
Add the
vplay-android dependency in your
build.gradle file:
dependencies { implementation 'net.vplay:vplay-android:2.18.1' }
Also add the Felgo Maven repository at the
repositories block:
repositories { maven { url '' } }
Integrating QML content in your Android application requires a custom Activity base class. Extend any Activity where you would like to show QML content from
VPlayAndroidActivity:
public class MyQmlActivity extends VPlayAndroidActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // more Activity setup } }
Any other Activities that do not show QML content do not require a special base class.
You can load QML files from anywhere. All you need is the text content of the QML file. This lets you even load QML files from the web at runtime.
The most common use case is loading QML files from your project assets. To do so, place your
.qml files under your projects
assets directory (usually
<project-dir>/src/main/assets). You can also use subfolders inside
assets and reference files relatively from within QML.
You can load any QML content using the class
VPlayAndroidFragment. You can add an instance of the Fragment in code or in a layout XML file.
You can add
VPlayAndroidFragment to any layout
.xml file:
<fragment android:
This loads the file
qml/Main.qml from your project assets.
To programmatically add a
VPlayAndroidFragment to an
Activity, you can use
FragmentManager:
void loadQml() { try { getFragmentManager().beginTransaction() .replace(R.id.fragment_container, new VPlayAndroidFragment() .setQmlSource(getApplicationContext(), "qml/Main.qml"), null) .addToBackStack(null) .commit(); } catch (IOException ex) { // QML file not found Log.w("MainActivity", "Could not load QML file", ex); } }
Here
R.id.fragment_container is the ID of an existing view to place the new Fragment into. This loads the file
qml/Main.qml from your project assets. You can also load content from other places.
Use the method
VPlayAndroidFragment.setQmlSource(Context context, URI source) to load QML from a local file. The
source URI should start with
file://. In this case, relative resource
lookup within QML starts at the
source file's directory.
Use the method
VPlayAndroidFragment.setQmlContent(String qmlContent, String qmlBaseUrl) to load QML content directly from a source string. The paramater
qmlBaseUrl represents a virtual base URL for
a relative resource lookup. As an example, you can set it to
"assets:/qml/subdir/Main.qml" to start the lookup within QML at the
"qml/subdir" directory inside assets.
First set up your project to enable loading QML content from a native iOS application.
You can add the Felgo dependency to an existing Xcode project using CocoaPods. If you have not yet used CocoaPods, you can install it with Homebrew from terminal:
$ brew install cocoapods
If your project does not yet use CocoaPods, you can add it via terminal. Execute the following command in your Xcode project root:
$ pod init
This creates a file named
Podfile in the same directory.
Add the
VPlayIOS dependency in your
Podfile:
target 'MyIOSApp' do # more dependencies pod 'VPlayIOS', :git => '' end
Afterwards, update CocoaPods dependencies:
$ pod install
This generates a file called
<project-name>.xcworkspace. To use CocoaPods, open this file in Xcode instead of the
<project-name>.xcodeproj.
Start the Felgo runtime before QML content can be used. You can do this, for example, in your
AppDelegate's
didFinishLaunchingWithOptions method. When your app terminates, you can quit the Felgo
Runtime again:
#import "VPlayIOS.h" @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // other code ... [[VPlayIOS sharedInstance] start]; return YES; } - (void)applicationWillTerminate:(UIApplication *)application { // other code ... [[VPlayIOS sharedInstance] quit]; } @end
VPlayIOSView. You can add an instance of the view in code or in an interface builder file.
You can add
VPlayIOSView using the Xcode Interface Builder. Add an empty View to your interface and set the custom class to
VPlayIOSView:
To access the view from source code, add an
IBOutlet property to your
ViewController implementation:
#import "VPlayIOSView.h" @interface ViewController @property (weak, nonatomic) IBOutlet VPlayIOSView *vplayView; @end
You can then add a referencing outlet by right-clicking the view in Interface Builder:
You can also add
VPlayIOSView to another view in code. Example from within a
ViewController implementation:
#import "VPlayIOSView.h" @interface ViewController() @property (strong, nonatomic) VPlayIOSView *vplayView; @end @implementation ViewController // more methods... - (void)addQMLView { self.vplayView = [VPlayIOSView new]; self.vplayView.frame = self.view.bounds; [self.view addSubview:self.vplayView]; } @end
To load QML content, assign a URI to the property
VPlayView.qmlSource. You can use any URI, for example to a web resource, a local file or a project resource.
This example loads
Main.qml from your project resources:
- (void)loadQML { self.vplayView.qmlSource = [[NSBundle mainBundle] URLForResource:@"Main" withExtension:@"qml"]; }
You can also load QML directly from an
NSData or
NSString object. For this, assign to the property
VPlayView.qmlContent:
- (void)loadQML { // obtain QML content from anywhere... NSString *content = @"import Felgo 3.0; App { AppText { text: 'Direct QML content' } }"; self.vplayView.qmlContent = [content dataUsingEncoding:NSUTF8StringEncoding]; }
Voted #1 for: | https://felgo.com/doc/felgo-native-integration/ | CC-MAIN-2019-47 | refinedweb | 909 | 50.63 |
Attendees: Michael Bouschen, Matthew Adams, Michelle Caisse, Martin
Zaun, Craig Russell
On Jan 5, 2006, at 4:52 PM, Michelle Caisse wrote:
Agenda:
1. Test status (Michael) 4 of 28 configurations fail: the usual
suspects 564 tests (not including detach tests) 4 failures, 5 errors
datastore id 5 failures 5 errors. Real progress.
2. Query tests (Michael) Moved and changed query "Having" tests; now
pass. Still some JPOX query issues but most have been resolved.
Hooray. AI: Michael: need to add a public static final field in a
public class to test fully qualified class name static field in query.
3. Fieldtypes test status (Michelle) The only issue remaining is
BigDecimal[ ] where it seems there are two different issues: one with
storing the values in a separate table and the other with storing the
arrays as a serialized BLOB. AI: Craig and Andy
4. Suggestion to split alltests.conf into separate configuration
files (Craig and others) Andy earlier proposed splitting out
alltests.conf into several configurations in order to better tell
where the problems are. AI: Michael propose a split into a dozen
configurations by subdirectory of tck20/test/java/org/apache/jdo/tck/
*. As soon as schema8 is stable, it will be integrated into the
default schema. AI: Matthew add version columns to schema and remove
schema8.
5. Other issues (any and all)
The JIRA issues associated with detachment need to be cleaned up;
they mixed the life cycle and behavior of detached and persistent-
nontransactional-dirty objects. AI: Matthew and Craig to fix up.
Action Items from weeks past:
.
! | http://mail-archives.apache.org/mod_mbox/db-jdo-dev/200601.mbox/%3CE28A7569-D9D0-4368-B7DE-839A817260E0@Sun.COM%3E | CC-MAIN-2014-41 | refinedweb | 261 | 64 |
Here's a 2.5.50 version of kmalloc_percpu originally submitted by Dipankar.
This one incorporates Rusty's suggestions to rearrange code and sync
up with its static counterpart. This version needs exposure of malloc_sizes
in order to move the interfaces to percpu.c from slab.c (kmalloc_percpu and
kfree_percpu donot have anything to do with the slab allocator itself).
First of the two patches is to expose the malloc_sizes and the second
one is the actual allocator. I'll follow this up with patchsets to enable
networking mibs use kmalloc_percpu. We'll have to use kmalloc_percpu
for mibs since DEFINE_PER_CPU won't work with modules (and ipv6 stuff
can be compiled in as modules)
Following is the 1 of 2 patches.
D: Name: slabchange-2.5.50-1.patch
D: Description: Exposes malloc_sizes for kmalloc_percpu
D: Author: Ravikiran Thirumalai
include/linux/slab.h | 13 +++++++++++++
mm/slab.c | 9 +--------
2 files changed, 14 insertions(+), 8 deletions(-)
diff -ruN linux-2.5.50/include/linux/slab.h kmalloc_percpu-2.5.50/include/linux/slab.h
--- linux-2.5.50/include/linux/slab.h Thu Nov 28 04:06:23 2002
extern kmem_cache_t *sigact_cachep;
extern kmem_cache_t *bio_cachep;
+/*
+ * Size description struct for general caches.
+ * This had to be exposed for kmalloc_percpu.
+ */
+
+struct cache_sizes {
+ size_t cs_size;
+ kmem_cache_t *cs_cachep;
+ kmem_cache_t *cs_dmacachep;
+};
+
+extern struct cache_sizes malloc_sizes[];
+
#endif /* __KERNEL__ */
#endif /* _LINUX_SLAB_H */
diff -ruN linux-2.5.50/mm/slab.c kmalloc_percpu-2.5.50/mm/slab.c
--- linux-2.5.50/mm/slab.c Thu Nov 28 04:06:17 2002
#define SET_PAGE_SLAB(pg,x) ((pg)->list.prev = (struct list_head *)(x))
#define GET_PAGE_SLAB(pg) ((struct slab *)(pg)->list.prev)
-/* Size description struct for general caches. */
-struct cache_sizes {
- size_t cs_size;
- kmem_cache_t *cs_cachep;
- kmem_cache_t *cs_dmacachep;
-};
-
/* These are the default caches for kmalloc. Custom caches can have other sizes. */
-static struct cache_sizes malloc_sizes[] = {
+struct cache_sizes malloc_sizes[] = {
#if PAGE_SIZE == 4096
{ 32, NULL, NULL},
#endif
-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
More majordomo info at
Please read the FAQ at | http://www.verycomputer.com/180_19bf6834190b196c_1.htm | CC-MAIN-2022-05 | refinedweb | 334 | 50.84 |
💣 The problem
Have you ever found yourself needing to change an external type from another library, or just needing specific fields to become optional?
Or maybe you just wanted to update a type, but deeply?
Or even just simply concat to tuples together into one?
A week ago, this was not possible... Until today.
🤔 But how?
What if I told you that most of the pain of TypeScript could be put away forever?
So that you can focus on what matters now, not working around TS' limitations??
These are just a few examples for the most common type manipulations.
🍩 So what is it?
I am proud to annouce ts-toolbelt. A 100% tested type library that makes coding with TypeScript even safer. But not only, it will also make your software more robust and more flexible.
It uses the type system itself for TypeScript to compute more complex types. In other words, its API exposes types that trade CPU & RAM for higher type safety.
ts-toolbelt completes TypeScript with a collection of more than 150 tested types. It's goal is to improve type correctness while adding a whole new set of features to TS.
🥅 Goals
- This package aims to be the home of all utility types
- Keep reasonable performance, so it will not bloat TS
- Computed types are always readable, like if you typed it
- Software that's more type-safe, flexible & more robust
- Bring a whole new set of extra features to TypeScript
- Types can be combined together to create even more types!
🏁 Getting Started
Prerequisites
npm install typescript@^3.5.0 --save
Installation
npm install ts-toolbelt --save
Hello World
import {Object} from 'ts-toolbelt' // Merge two `object` together type merge = Object.Merge<{name: string}, {age?: number}>
The project is huge but very well documented with a website (and a search bar). So if you're ready to be type-safe, here's my repository.
This is my first open-source project, your comments are more than welcome 😉
Discussion (3)
Found this library and this post after finding your post about your curry implementation on FreeCodeCamp.
Wanted to congratulate you for this very fine work and your written content.
Thanks!
Hi Pierre, like Enrico i've been following you since your awesome typing Ramda article on Free Code Camp.
I hope you're doing well! | https://dev.to/pirixgh/higher-type-safety-for-typescript-4703 | CC-MAIN-2022-33 | refinedweb | 388 | 73.37 |
Shapes could be defined by an inequality, for example simple shapes could be defined as follows:
Sphereboolean isInside(float x, float y, float z) {return (r*r < x*x+y*y+z*z);}
CubeBoolean isInside(float x, float y, float z) {return ((x<left) & (x>right) & (y<top) & (y>bottom) & (z<front) & (z>back));}
Other shapesOther shapes could be made by combining these simple shapes using Boolean operations, for example a Boolean 'or' will create a new shape with an outline covering both shapes. A Boolean 'and' will create a shape with an outline which is the intersection of both shapes. An 'not and' would allow a 'bite' to be taken out of an object in the shape of the other object.
Movement
You could offset or move the object with the following type of method: (see Using this to model physics)Boolean isInside(float x, float y, float z) {return shapeToBeMoved.isInside(x+xOffset, y+yOffset, z+zOffset);}
Uses of this method
Parameterisation | http://euclideanspace.com/threed/solidmodel/solidgeometry/equations/index.htm | CC-MAIN-2017-17 | refinedweb | 164 | 50.91 |
Scaled Agile Framework (SAFe) can look quite complicated and intimating at first glance. However the essence of SAFe is pretty simple:
Around 6 months ago I got trained in Scaled Agile Framework (SAFe) and became certified as a SAFe Program Consultant (SPC) for SAFe 4.0. Before doing the training, I had a somewhat negative opinion of SAFe, as well as other scaling frameworks, e.g. LeSS, DAD etc. I can now say that my former opinion was based on very little understanding of what SAFe is and how it works, and was without a doubt an uneducated opinion. I admit to being somewhat ashamed for having the views I held then. Anyway, since the training, I have coached almost full-time in an organisation practicing SAFe, and have done a fair amount of thinking, training and speaking on SAFe. The following is what I believe to be the essence of SAFe. (Disclosure: my training and certification is in SAFe 4.0. SAFe 4.5 was released relatively recently. I have not yet caught up with 4.5, though I believe my thoughts remain valid and accurate.)
Fractal feedback loops: SAFe has 2 main Plan-Do-Check-Act feedback loops. At the team level, Scrum (or Kanban), and at the program, or team-of-teams level, the
Program Increment. A Program Increment (PI) is analagous to a sprint in Scrum, that is a timebox wherein a group of people plan, execute, reflect and adjust together. The differences between a PI and a sprint are that a PI involved more people, is longer lived (typically 4-5 sprints), and has ceremonies designed for the level of scale. Note that although a plan is made at PI Planning, this plan is not set in stone. It is revisited frequently during execution of the PI, much the same way a Sprint plan is revisited every day at a Daily Stand-Up or Daily Scrum (HT to Kevin Shine for reminding me about this point).
Fractal work filtering and prioritisation: Kanban is used at various levels (portfolio, value stream and program levels in SAFe 4) to filter and prioritise the work that the people in the teams do. This is to ensure as far as possible that we don’t waste time and effort working on the wrong things. This is similar to how work gets filtered and prioritised in Scrum. The feedback loops mentioned above provide a limit to the length of time the teams work on anything before getting feedback from stakeholders.
Priority alignment at scale: An
Agile Release Train is a way of making sure that everybody, across the organisation, required for work to happen has the same single list of priorities. That is, all the necessary people are dedicated solely to this set of priorities. This is analagous to cross-functional teams in Scrum. When everyone has the same priority, we have much less coordination overheard and much less waiting for each other compared to being dependent on people with other priorities.
SAFe does have a lot of roles and moving parts, there is no doubt. However I believe that the three things mentioned above form the core and essence of the framework. I certainly believe that most organisations, certainly those I’ve worked in, would benefit from all three of these structures and practices.
Kent Beck is fond of saying:
Work on the most important thing until either its done or its no longer the most important thing
If you look closely at the three things above, you might find that they’re simply ways of doing just this, when there are a large number of people working together on the same thing.]]>
TL;DR People spend a lot of time arguing whether things are ‘Agile’ or not. ‘Agile’ has become the tail wagging the dog and asking that question misses the point. The question we should be asking is “Does X help us (or our client) achieve the outcomes they desire?”
I recently spoke at a community meetup on the topic Agile Release Trains: Agile, or not so much?. The talk had 2 parts, the first explaining what Agile Release Trains are; the second part discussing whether the question But is it Agile? is a useful question to ask. In my previous post (What is ‘Agile’), I discussed my current interpretation of the Manifesto for Agile Software Development and what I believe ‘Agile’ means.
I no longer believe that there is much value in discussing whether something, e.g. Agile Release Trains, is Agile or not. The term ‘Agile’ has become a misnomer, a red herring. It has become the tail wagging the dog. In his Agile Africa 2015 Keynote, Kent Beck used the analogy of dogs and small children looking at the pointed finger, instead of what the finger is pointing at, to describe Agile. Alistair Cockburn, another Manifesto signatory has launched his own ‘new branding’: Heart of Agile. I assume this was because he was frustrated by what Agile had become.
Agile has become a goal in its own right, and has moved away from its origins as a guideline for a way of operating. Instead of asking “does this help me (or my client) achieve the outcomes we seek?”, we’re so caught up in debating what agile is or isn’t, and spend a lot of time in No True Scotsmen arguments.
Who cares if its agile? Are we moving in the direction of continuous improvement or not? Do we even know what continuous improvement means for us in our context? What would imrovement look like? How would we measure it? Would we know it if it bit us in the backside? The next time you hear, or say, “That’s Not Agile!”, stop. Ask yourself what’s really being said and why.
For what it’s worth, my opinion is that any operating model that follows the 4 value statements described in the Manifesto is, by definition, agile.]]>
TL;DR Agile is a way of operating wherein the decisions we make are guided primarily by 4 trade-off statements expressed as value statements in the Agile Manifesto. Following this guidance is believed to lead to improved ways of developing software.
Recently I have again started to question what is meant by ‘Agile’ (I make no distinction between ‘Agile’ and ‘agile’). I have asked this question at a few conferences, Lean Coffees etc. This is my current interpretation of ‘Agile’, as informed by the Manifesto for Agile Software Development, specifically the first statement and the four value statements: statements provide guidelines for trade-off decisions we should be making. If you’re in a situation where you can choose between working on either
working software or
comprehensive documentation, rather choose
working software, especially if you don’t yet have
working software.
If you’re in a situation where you have a plan but have discovered that the plan no longer makes sense, you can choose between either
following the plan (even though you now know it no longer makes sense to do so), or
responding to the change, the guidance from the Manifesto is to rather
respond to the change. (I personally prefer
adapt to learning over
responding to change but that’s another story.)
The same thinking applies to the other two value statements: should you have to choose either
contract negotiation or
customer collaboration, rather choose the latter. If you need to choose between
processes and tools and
individuals and interactions, again rather choose the latter.
The original authors and signatories of the Manifesto believed, based on their collective experience, that if you follow these decision making guidelines, you will become
better at developing software. I certainly don’t disagree with them.
TL.
TL:
In this article I will deal with only ‘Simple Pricing’ and ‘Three-for-Two Promotion’. I will deal first with ‘Simple Pricing’ completely, and then start with ‘Three-for-Two Promotion’.
Simple Pricing
Expected outcomes for combinations of state and inputs:
Three-for-Two Promotion
Expected outcomes for combinations of state and inputs:
There are several interesting things about the specifications above to which I’d like to draw particular attention:.]]>
TL;DR: Lessons learned from hosting and facilitating Lean Coffees at public meetups, within companies and at conferences.
I have been hosting and facilitating Lean Coffee for a number of years now, for the Lean Coffee JHB Meetup, at companies where I’ve worked, and at several conferences I’ve attended. Along the way I’ve learned a few things about hosting and facilitating. Quite frequently people ask me for advice on starting a Lean Coffee. These are the lessons I’ve learned.
Lean Coffee
Lean Coffee is a lightweight structure for an informal gathering where the participants decide the agenda at the start of the gathering in a just-in-time way. The aim is to have many shallow discussions about a broad range of topics instead of deeply discussing only one or two topics. All you need for a Lean Coffee is somewhere to gather (hopefully with either good coffee or beer), someone to invite people, and someone to facilitate (after a while the gatherings become self-facilitating).
The discussion around each topic is time-boxed, so that we don’t spend too much time on a single topic. Lean Coffee was originally developed to discuss Agile/Lean coaching, but you can discuss anything. You as a host decide if there are boundaries to the topics which can be discussed.
Hosting
Its very easy to host a Lean Coffee, all you need to is:
Facilitating
Facilitating means you’re holding the space and managing the flow of the event. You can think of it like directing the traffic at the gathering. Facilitating typically includes the following:
Flow
The flow of Lean Coffee is:
Sticky Note Tips
There are a few things to remember which improve the usage and utility of sticky notes. They seem simple, but they’re easy to forget. I’ve made all of these mistakes at one time or another.
Group Size
Group size is probably the factor that affects the hosting and facilitating of Lean Coffee the most.
Internal Lean Coffee
For internal (private company-specific) Lean Coffee, its a good idea to announce at the beginning that everything said in the event is private and confidential and shouldn’t leave the room. This is to make a safe space so that people can open up more.
At one company we tried a few invitation mechanisms:
And, eventually,
At this same company, people saw it as a something for people involved in software development only, and thus didn’t arrive. It turned out the name ‘Lean Coffee’ was the main reason behind this. I changed the name to ‘Coffee & Conversation’, and in my emails explicitly mentioned that it was for everyone. This increased attendance and diversity.
For internal Lean Coffee, try get your company or department to sponsor some refreshments. Coffee, donuts, sandwiches etc. This is a relatively cheap but effective crowd puller.
Try book a meeting/board room that is very visible and has a lot of foot traffic so that people see you as they walk past. Generate interest and curiosity.
One thing you should be aware of is that the presence of managers (or people to whom other people report) will have an effect on how safe people feel and therefore what they’ll be prepared to talk about. I’ve also seen the presence of senior managers change the conversation into questions that should be part of ordinary operations (this is fine if its the aim of you Lean Coffee but it wasn’t the aim of this one).
Resources
* Lean Coffee
* A nice slideshow I found explaining Lean Coffee
* Gerry Kirk’s One Page Intro which I’ve used a lot in the past. I usually have one or two laminated print-outs of this sitting on tables when I facilitate.
* Another great article on Lean Coffee
* Jo’burg Lean Coffee Meetup Group: My ‘home’ Lean Coffee, and where I first learned about it.
* Modus Cooperandi’s Lean Coffee material Modus Cooperandi is Jim Benson’s company. Jim Benson created Lean Coffee.
Please offer your Lean Coffee thoughts, tricks, tips, hacks and resources in the comments!]]>
TL.]]>
TL!]]>
TL;DR: The specification I write are based on domain-level Ubiquitous Language-based specifications of system behaviour. These spec tests describe the functional behaviour of the system, as it would be specified by a Product Owner (PO), and as it would be experienced by the user; i.e. user-level functional specifications.
I get asked frequently how I do Test-Driven Development (TDD), especially with example code. In my previous post I discussed reasons why I do TDD. In this post I’ll discuss how I do TDD.
First-off, in my opinion, there is no difference between TDD, Behaviour-Driven Development (BDD) and Acceptance-Test-Driven Development (ATDD). The fundamental concept is identical: write a failing test, then write the implementation that makes that test pass. The only difference is that these terms are used to describe the ‘amount’ of the system being specified. Typically, with BDD, at a user level, with ATDD, at a user acceptance level (like BDD), and TDD for much finer-grained components or parts of the system. I see very little value in these distinctions: they’re all just TDD to me. (I do find it valuable to discuss the ROI of TDD specifications at different levels, as well as their cost and feedback speed. I’m currently working on a post discussing these ideas.) Like many practices and techniques, I see TDD as fractal. We can get the biggest ROI for a spec test that covers as much as possible.
The test that covers the most of the system is a user-level functional test. That is, a test written at the level of a user’s interaction with the system – i.e. outside of the system – which describes the functional behaviour of the system. The ‘user-level’ part is important, since this level is by definition outside of the system, and covers the entirety of the system being specified.
Its time for an example. The first example I’ll use is specifying Conway’s Game of Life (GoL).
These images represent an (incomplete) specification of GoL, and can be used to specify and validate any implementation of Conway’s Game of Life, from the user’s (i.e. a functional) point of view. These specifications make complete sense to a PO specifying GoL – in fact, this is often how GoL is presented.
These images translate to the following code:
[Test] public void Test_Barge() { var initialGrid = new char[,] { {'.', '.', '.', '.', '.', '.'}, {'.', '.', '*', '.', '.', '.'}, {'.', '*', '.', '*', '.', '.'}, {'.', '.', '*', '.', '*', '.'}, {'.', '.', '.', '*', '.', '.'}, {'.', '.', '.', '.', '.', '.'}, }; Game.PrintGrid(initialGrid); var game = CreateGame(initialGrid); game.Tick(); char[,] generation = game.Grid; Assert.That(generation, Is.EqualTo(initialGrid)); } [Test] public void Test_Blinker() {)); } [Test] public void Test_Glider() {)); }
All I’ve done to make the visual specification above executable is transcode it into a programming language – C# in this case. Note that the tests do not influence or mandate anything of the implementation, besides the data structures used for input and output.
I’d like to introduce another example, this one a little more complicated and real-world. I’m currently developing a book discovery and lending app, called Lend2Me, the source code for which is available on Github. The app is built using Event Sourcing (and thus Domain-Driven Design and Command-Query Responsibility Segregation). The only tests in this codebase are user-level functional tests. Because I’m using DDD, the spec tests are written in the Ubiquitous Language of the domain, and actually describe the domain, and not a system implementation. Since user interaction with the system is in the form of Command-Result and Query-Result pairs, these are what are used to specify the system. Spec tests for a Command generally take the following form:
GIVEN: a sequence of previously handled Commands WHEN: a particular Command is issued THEN: a particular result is returned
In addition to this basic functionality, I also want to capture the domain events I expect to be persisted (to the event store), which is still a domain-level concern, and of interest to the PO. Including event persistence, the tests, in general, look like:
GIVEN: a sequence of previously handled Commands WHEN: a particular Command is issued THEN: a particular result is returned And: a particular sequence of events is persisted
A concrete example from Lend2Me:
User Story: AddBookToLibrary – As a User I want to Add Books to my Library so that my Connections can see what Books I own.
Scenario: AddingPreviouslyRemovedBookToLibraryShouldSucceed
GIVEN: Joshua is a Registered User AND Joshua has Added and Removed Oliver Twist from his Library WHEN: Joshua Adds Oliver to his Library THEN: Oliver Twist is Added to Joshua's Library
This spec test is written at the domain level, in the Ubiquitous Language. The code for this test is:
[Test] public void AddingPreviouslyRemovedBookToLibraryShouldSucceed() { RegisterUser joshuaRegisters = new RegisterUser(processId, user1Id, 1, "Joshua Lewis", "Email address"); AddBookToLibrary joshuaAddsOliverTwistToLibrary = new AddBookToLibrary(processId, user1Id, user1Id, title, author, isbnnumber); RemoveBookFromLibrary joshuaRemovesOliverTwistFromLibrary = new RemoveBookFromLibrary(processId, user1Id, user1Id, title, author, isbnnumber); UserRegistered joshuaRegistered = new UserRegistered(processId, user1Id, 1, joshuaRegisters.UserName, joshuaRegisters.PrimaryEmail); BookAddedToLibrary oliverTwistAddedToJoshuasLibrary = new BookAddedToLibrary(processId, user1Id, title, author, isbnnumber); BookRemovedFromLibrary oliverTwistRemovedFromJoshuaLibrary = new BookRemovedFromLibrary(processId, user1Id, title, author, isbnnumber); Given(joshuaRegisters, joshuaAddsOliverTwistToLibrary, joshuaRemovesOliverTwistFromLibrary); When(joshuaAddsOliverTwistToLibrary); Then(succeed); AndEventsSavedForAggregate(user1Id, joshuaRegistered, oliverTwistAddedToJoshuasLibrary, oliverTwistRemovedFromJoshuaLibrary, oliverTwistAddedToJoshuasLibrary); }
The definitions of the Commands in this code (e.g.
RegisterUser) would be specified as part of the domain:
public class RegisterUser : AuthenticatedCommand { public long AuthUserId { get; set; } public string UserName { get; set; } public string PrimaryEmail { get; set; } public RegisterUser(Guid processId, Guid newUserId, long authUserId, string userName, string primaryEmail) : base(processId, newUserId, newUserId) { AuthUserId = authUserId; UserName = userName; PrimaryEmail = primaryEmail; } }
Again, the executable test is just a transcoding of the Ubiquitous Language spec test, into C#. Note how closely the code follows the Ubiquitous Language used in the natural language specification. Again, the test does not make any assumptions about the implementation of the system. It would be very easy, for example, to change the test so that instead of calling
CommandHandlers and
QueryHandlers directly, HTTP requests are issued.
It could be argued that the design of this system makes it very easy to write user-level functional spec tets. However these patterns can be used to specify any system any system, since it is possible to automatically interact with any system through the same interface a user uses. Similarly, it is possible to automatically assert any state in any boundary-interfacing system, e.g. databases, 3rd party webservices, message busses etc. It may not be easy or cheap or robust, but it is possible. For example, a spec test could be:
GIVEN: Pre-conditions WHEN: This HTTP request is issued to the system THEN: Return this response AND: This HTTP request was made to this endpoint AND: This data is in the database AND: This message was put onto this message bus
This is how I do TDD: the spec tests are user-level functional tests. If its difficult, expensive or brittle to use the same interface the user uses, e.g. GUIs, then test as close to the system boundary, i.e. as close to the user, as you can.
For interest’s sake, all the tests in the Lend2Me codebase hit a live PostgreSQL database, and an embedded eventstore client. There is no mocking anywhere. All interactions and assertions are outside the system.]]>
People give many reasons for why they do Test-Driven Development (TDD). The benefits I get from TDD, and thus my reasons for practicing it, are given below, in order of most important to least important. The order is based on whether the benefit is available without test-first, and the ease with which the benefit is gained without a test-first approach.
The first step in building the correct thing is knowing what the correct thing is (or what it does). I find it very difficult to be confident that I’m building the correct thing without TDD. If we can specify the expectations of our system so unambiguously that a computer can understand and execute that specification, there’s no room for ambiguity or misinterpretation of what we expect from the system. TDD tests are executable specifications. This is pretty much impossible without test-first.
I also believe Specification by Example, which is necessary for TDD, is a great way to get ‘Product Owners’ to think about that they want (without having to first build software).
The problem with most other forms of documentation is there is no guarantee that it is current. Its easy to change the code without changing the natural-language documentation, including comments. There’s no way to force the documentation to be current. However, with TDD tests, as long as the tests are passing, and assuming the tests are good and valid, the tests act as perfectly up-to-date documentation for and of the code, (from an intent and expectation point of view, not necessarily from an implementation PoV). The documenation is thus considered ‘living’. This is possible with a test-after approach but is harder than with test-first.
TDD done properly, i.e. true Red-Green-Refactor, forces me to focus on one area of work at a time, and not to worry about the future. The future may be as soon as the next test scenario or case, but I don’t worry about that. The system gets built one failing test at a time. I don’t care about the other tests, I’ll get there in good time. This is possible without test-first, but harder and nigh-impossible for me.
This is the usual primary benefit touted for TDD. My understanding of this thinking is thus: in general, well-designed systems are decoupled. Decoupling means its possible to introduce a seam for testing components in isolation. Therefore, in general, well-designed systems are testable. Since TDD forces me to design components that are testable, inherently I’m forced to design decoupled components, which are in general considered a ‘better design’. This is low down on my list because this is relatively easy to do without a test-first approach, and even without tests at all. I’m pretty confident I can build what I (and I think others) consider to be well-designed systems without going test-first.
Another popular selling point for TDD is that the tests provide a suite of automated regression tests. This is absolutely true. However I consider this a very pleasant by-product of doing TDD. A full suite of automated regression tests is very possible with a test-after approach. Another concern I have with this selling point is that TDD is not about testing, and touting regression tests as a benefit muddies this point.
Why do you do TDD? Do you disagree with my reasons or my order? Let me know in the comments!]]> | http://feeds.feedburner.com/joshilewis | CC-MAIN-2019-13 | refinedweb | 3,840 | 52.7 |
19 August 2011 10:46 [Source: ICIS news]
(updates closing share prices, closing indices, other details)
?xml:namespace>
By Nurluqman Suratman
A plunge in a
The result marked the weakest reading since early 2009, according to the Commonwealth Bank of
A fall in
A dip in European markets on Thursday fanned further concerns over the economic health of the region.
Banks led the fall after a report that US regulators are stepping up scrutiny of the local operations for
Worries over demand dragged crude oil prices lower, with West Texas Intermediate (WTI) light sweet crude for September delivery down by $2.15/bbl to $80.23 at 17:08 hours Singapore time (09:08 GMT).
“Global crude oil prices fell on disappointment there was no concrete plan to address the euro debt crisis,” said Commonwealth Bank of
In the Asian chemicals markets, propylene spot discussions were put on the backburner on Friday following the falls in oil prices.
“Following the crude price drop, sentiment is quite unstable,” said a Japanese propylene trader.
Earlier this week, deals were heard done at $1,580-1,600/tonne (€1,106-1,120/tonne) CFR (cost & freight) NE (northeast) Asia for September arrival, but no firm discussions were heard on Friday morning.
On Friday, prices for butadiene rubber (BR) fell by CNY800/tonne ($125/tonne) to CNY32,500-34,500/tonne EXWH (ex-warehouse).
Chinese domestic styrene butadiene rubber (SBR) prices, meanwhile, fell by CNY500/tonne to CNY31500-33100/tonne EXWH.
Weak demand, bearish market sentiment and fears of a global slowdown have prompted traders to offload their material at reduced prices, exerting more downward pressure on prices.
The import prices of non-oil grade 1502 SBR fell by $100/tonne to $4,300-4,400/tonne CIF (cost, freight & insurance)
In
The Nikkei stock average was hit by concerns about a 6.8-magnitude earthquake that hit the northeast region of the country at 14:36 hours Japan time (05:36 GMT).
In South Korea, LG Chem slumped by 14.69% and SK Innovation fell by 13.33%, with the Korea Composite Stock Price Index ending 6.22% lower at 1,744.88 points.
In Malaysia, PETRONAS Chemicals Group slipped by 2.58%, with the benchmark Kuala Lumpur Composite Index down by 1.29%, or 19.32 points, to 1,483.98 points at the close.
In
“The recent violent equity market sell-off has brought unpleasant memories of 2008 back to investors' minds,” said UBS Wealth Management Research’s note.
“Following the many risk events financial markets had to absorb over the past months, the concern in focus now is a more fundamental one: global growth,” the note said.
“With uncertainty being the last thing equity investors want to deal with, and with no quick fix in sight for the global growth concerns, we expect market volatility to remain high,” it added.
Additional reporting by Peh Soo Hwee, Helen Yan, Sunny Pan and Miki Jiang | http://www.icis.com/Articles/2011/08/19/9486437/asian-chemical-shares-slump-on-us-recession-fears.html | CC-MAIN-2014-42 | refinedweb | 493 | 62.48 |
In this article, we will describe various libraries offered by Python to allow us to download files. We have gathered all of the information and details that can help you to download a file using Python.
Here are some different ways to download a file in Python easily.
Download File with Wget Function
In the wget function, we do not need to perform this extra step while using the wget function. The wget function offers a function named "download," which accepts two parameters:
- 1st parameter: URL to the downloadable resource file
- 2nd parameter: Path to the local file system where the downloaded file is to be stored.
Example:
import wget myurl = input("Enter url: ") wget.download(myurl , 'D:\python')
Output:
Enter url: 100% [..............................................................................] 11231 / 11231
Download File with urllib Package
This package facilitates the python developers to incorporate the file downloading feature in their website, cross-platform applications, etc.
urllib.request() is the method that needs two parameters in order to download the file.
- 1st parameter: URL to the downloadable resource file
- 2nd parameter: Path to the local file system where the downloaded file is to be stored.
Before running the sample code, you must ensure to install urllib package into your system by executing the following command:
pip install urllib
This Package will soon get deprecated in the later versions of Python. So, better to use the urllib3 Package after upgrading the python version from 2.0 to 3.5 and above.
python -m pip install urllib3
Example:
import urllib.request myUrl = input("Enter url:") #Linux urllib.request.urlretrieve(myUrl, '/User/Downloads/xyz.jpg') #Windows #urllib.request.urlretrieve(myUrl,"D:\\python\\xyz.jpg")
In the 1st line of the above code, we imported the required module. Then we created a variable that holds the string representing the URL of the downloadable file resource. This variable points to the online resource.
In the last line of the code, we called the method by passing two parameters, i.e., the URL pointing to the online resource. The second represents the path where the downloadable resource is to be stored.
After running the above code snippet, we can access the downloaded file in the local system's document folder with a file named "car.jpg".
We can provide any name to the downloaded resources through the code. We have to make sure that the path to the folder should be accessed with the least privilege (without any special permission required from the administrator of the local system).
Ensure that urlretrieve is considered the 1st version of the Python-defined module of the legacy code. So, there might be a chance that this module may not be present at the later version of python releases.
If we are using the Python2 version, then it is advised to use this snippet to implement the desired functionality as it can be found as one of the simplest ways to download the file from online resources.
Download File with Proxy Module
Some developers may need some files which are restricted to download using networks belonging to certain regions. To facilitate the users, developers incorporate the proxy service in their websites to allow the users to download such files.
Example:
from urllib2 import Request >>>setNewProxy = urllib.request.ProxyHandler({'http': '123.12.21.98'}) >>> connProxy= urllib.request.build_opener(setNewProxy) >>> urllib.request.urlretrieve('')
In the above code, we have created the proxy object named setNewProxy, bypassing the virtual IP address of your device.
We established the connection to the proxy server using build_opener(), bypassing the proxy object in it. In the final step, we retrieve the resource using the urlretrieve() method of the request class.
Download File with urllib2 Package
This is the alternate way to download the file from an online resource. This method requires only one parameter to fetch the document. This Package is deprecated in Python3 and the above versions. In order to use the urllib2 version, it is already included in the urllib3 version. So it is advised to shift your project to the Python3 version and above to avoid getting incompatible issues.
python -m pip install urllib3
The urllib2 package contains a urlopen() method that accepts the URL to the downloadable online resource. This method returns the object which points to that required resource.
Example:
import urllib2 Myurl = input("Enter url :") fileFetchededata = urllib2.urlopen(myurl) dataforwrite = fileFetchededata.read() with open('/your/local/path/xyz.jpg', 'wb') as myfile: myfile.write(dataforwrite)
Firstly, in the above code, we imported the urllib2 package, which offers the urlopen method to fetch the file data object from an online resource. urlopen accepts one parameter, i.e., URL, in the form of a string.
The fileFetchededata()is the variable that holds the fetched file's data in the form of an object. We need to copy the data from this object and add it to our local system's desired file.
After storing the fetched file in the data object, we used the open() method to write the data from the object to our file named myfile. This method again accepts two parameters:
- Local system path where the downloaded file is going to store.
- Mode of storing the file. Here "wb" shows the open() method has the necessary permission to write the data from the object to that into myfile variable.
We can look into the downloaded file created by navigating into the directory mentioned in the python script.
This Package is now added in the request() method in Python3. So, we can not use this method in the Python2 version.
So, before starting the project, we need to make sure the versions we are going to use, and based on that, we can select the desired packages to be used; otherwise, there may be a chance of version incompatibility.
Download File with Request Function
This method is specially built for the Python3 version and includes all the features present in the methods of urllib2.
This Package downloads the file in binary format. We can use the open() method in the previous code example to fetch the human-readable data from this binary code format. The open() method copies the data from the binary formatted file into the desired file.
Like the above scenarios, this code also creates the file in the python script's path.
Example:
import requests myurl = input("Enter url :") req = requests.get(myurl ) with open('/your/local/path/myCar.jpg', 'wb') as myfile: myfile.write(req.content) # Accessing HTTP meta-data print(req.encoding) print(req.headers['content-type']) print(req.status_code)
In various applications, developers build cross-platform API, multi-page websites. In such scenarios, it may be required to access some file information such as meta-data. The request method offers few constants (a few of them mentioned in the above code).
This meta-data can generate the request and pass it to another HTTP request to perform other development-related activities. (This is just an example).
The request function provides a wide range of features to the python developers that easily do web-scraping-related activities.
The request package's main advantage is that it is backward compatible and can be used in Python2.7 also. So, in general, developers can use this package in a lot more projects without facing any version-related problems.
Download File with Subprocess Module
Subprocess module is a module in python to run system commands from python code. In Linux, we have some commands to download files from URL, Two most popular commands are :
wget and curl
Example:
import subprocess subprocess.run(' curl --output abc.jpg ' ) subprocess.run(' wget ' )
Here using subprocess, we are running commands in the system, and we can run any system command from this module curl, and wget are Linux commands to download files from URL.
Handling Large File Downloads
Request package offers many more functions and flags to make developers enable the download of large files easier for the users.
There is a flag named "stream," which can be set to true. This will tell the request.get() method to download only the header of the file and store it as an object. While this happens, the connection with the URL remains open.
A built-in iterator is made to iterate through the file object to fetch the data in a large number of small chunks and store it in the desired documents.
Example:
req = requests.get(myurl, Stream=True) with open("myfilename.pdf",'wb') as myPypdf: for current_chunk in req.iter_content(chunk_size=1024) if current_chunk : myPypdf.write(ch)
We can see from the above code and we also have the privilege to set the chunk size as per our wish. The iter_content is the built-in iterator that iterates throughout the data abject and writes it in the specified document in our local system.
Advantage of Request Package Over other Methods
There are few scenarios, and we observe that while downloading few files, as we click on the download button, we get redirected to some other website. So, these redirections sometimes become complicated to handle.
Request methods offer additional functionalities to the developers to do the same easily.
Example:
import requests myurl = 'insert url' myresponse = requests.get(myurl , allow_redirects=True) with open('filename.pdf') as myPypdf: myPypdf.write(myresponse .content)
To handle the redirections, we need to put the allow_redirects variable value equal to true.
Download File with Asyncio Module
There may be a situation where a developer may need to download multiple files by making the download process periodically. Multiple files can be downloaded asynchronously using the asyncio module.
Asyncio module works by keeping an eye on the system events. Whenever there is an event, asyncio starts downloading the file as soon as it receives the interrupt from the system.
We need to install the aiohttp module to implement the feature successfully. We can install the respective module using the following command in cmd:
pip install aiohttp pip install asyncio
Example:
import asyncio from contextlib import closing import aiohttp async def FileDownload(session: aiohttp.ClientSession, url: str): async with session.get(url) as response: assert response.status == 200 # For large files we can use response.content.read(chunk_size) instead. return url, await response.read() @asyncio.coroutine def DownloadMultipleFiles(session: aiohttp.ClientSession): myUrls = ( ', '', '' ) myDownloads = [FileDownload(session, url) for url in myUrls] print('Results') for download_future in asyncio.as_completed(myDownloads): result = yield from myDownloads print('finished:', result) return myUrls def main(): with closing(asyncio.get_event_loop()) as obj1: with aiohttp.ClientSession() as period: myresult = obj1.run_until_complete(DownloadMultipleFiles(period)) print('Download finished:', myresult) main()
Conclusion
We saw that urllib and urllib2 packages would get deprecated from python three versions and above. To use the same functionality, we can use the requests module of python three and install urllib3 in our system.
For avoiding version incompatibility, it is advised to use the urllib3 or requests module to perform the above-required operation.
request package handles large file downloads in their way. It also made the developers handle the redirections within the websites easily.
In our opinion, the wget function is very easy to use because we do not need to explicitly copy the data from the binary-fetched file into a locally created blank file. So, this reduces our work.
Finally, we can prefer to use request methods as it offers a wide range of in-built features. The wget package is becoming much handier with the latest python release. Also, developers now prefer to work with file downloading-related activities using the wget and the request package. | https://www.stechies.com/download-file-python/ | CC-MAIN-2021-25 | refinedweb | 1,914 | 57.06 |
Scanrand Dissected: A New Breed of Network Scanner
Abstract
An attacker is only as good as the tools he can effectively use. Suffice to say, most do not have the know-how or skill to create their own advanced tools in order to leverage the available information of a network they plan on penetrating. This is where tools such as nmap and now Paketto Keiretsu, come into play.
The goal of this paper is to describe and demonstrate how the Paketto Keiretsu suite of tools, particularly scanrand, can be used to gather information on large networks in a shorter period of time than currently available tools.
Introduction
Created by Dan "Effugas" Kaminsky of Doxpara Research, Paketto Keiretsu is a suite of five tools that each perform a specialized task for obtaining or inserting data on a network.
- Scanrand Fast network scanner.
- Paratrace 'Parasitic' traceroute program.
- Minewt Software router.
- Lc Layer 2 data insertion tool.
- Phentrophy 3-D point plotter.
This paper will mainly concentrate on scanrand since this is the particular tool in Paketto Keiretsu that has emphasis on network information gathering.
Obtaining and Installing Paketto Keiretsu
The suite of tools can be obtained from:
Paketto Keiretsu relies on the libnet library for sending packets, and libpcap for receiving packets. These libraries deal directly with the datalink layer, bypassing the kernel network stack. In additional to these two libraries, scanrand relies on libtomcrypt for encryption algorithms. All these libraries are included and statically linked to the Paketto distribution but are referenced here for completeness. The number in parenthesis below is the version Paketto Keiretsu 1.0 - 1.10 uses.
- Libtomcrypt:
- Libnet:
- Libpcap:
Once you have obtained and extracted the paketto-1.10.tar.gz file, the typical
$ ./configure $ make # make install
will compile and install the suite.
Scanrand
Overview.
TCP - a stateful transport protocol
The TCP/IP stack of each operating system is responsible for keeping track of many variables for each 'connection' to or from the local machine. One of these variables is the state that a particular TCP connection is in.
A typical connection starts off with a client sending a TCP SYN packet to a server or remote machine. When the SYN is sent from the client, the operating system sets the state for this connection to SYN_SENT. When in a SYN_SENT state, the client operating system is expecting a SYN/ACK in return. Note, the client operating system and program are waiting on a reply. If the server does not respond within a particular time, the client will retransmit it's SYN since it assumes the packet did not make it to the server. If the server is listening on the port the client sent to, the server receives the SYN and replies with a SYN/ACK. The server then enters SYN_RECD state. If the client were a scanner, it would more than likely have what it wanted: A response from the server that indicated something was listening on the port it sent its SYN to.
Now that it has the information it wants, it doesn't care to talk to the server anymore. However, since TCP is a reliable protocol, if the server does not get a response from the scanner saying it received its SYN/ACK, the server will retransmit. To keep this from happening, the scanner sends a RST packet which tells the TCP connection to terminate regardless of state. You can imagine the quantity of SYN/ACK retransmits a scanner would get if it scanned thousands of machines and did not RST the connections. Another problem the scanner has to worry about is authentication. How does it know the SYN/ACK it received came from the machine it sent the SYN to? Sure the IP address is from the same machine, but what's to say it's not spoofed from a person that notices the scanning and wants to corrupt the gathered data?
TCP relies on sequence numbers to ensure the machine it is talking to is indeed the machine it originally contacted. The initial sequence numbers are 32-bit randomly generated integers that are exchanged in the initial TCP connection by both machines involved in the connection. Refer to figure 1-1.
Figure 1-1. J is the initial sequence number the client sends to the server in a SYN. The server gets the SYN and responds with a SYN/ACK which contains K, it's own initial sequence number, and an ACK which contains the clients sequence number(J) +1 which tells the client it got its SYN packet. The client then sends an ACK with the servers initial sequence number(K) + 1 to tell the server it received its SYN/ACK. After these three packets, the connection is considered to be in the ESTABLISHED state, and data transfer can occur.[5]
A basic network scanner sends a SYN packet to the remote server. It then stores the connection variables1, or waits for a reply. When it gets the reply, it makes sure the ACK sequence number is 1 plus the initial sequence number it sent in the SYN. If this is the case, it is a valid response (assuming it came from the IP address it sent the SYN to). The assumption is that an attacker that wanted to insert data into your TCP stream could not synchronize sequence numbers with you because of the randomness. This is actually possible, but often very difficult depending on how random the algorithm for selecting initial sequence numbers and the type of firewall the host is behind.
Scanning scanrand style
As mentioned earlier, scanrand takes a little different approach than the typical network scanner. It implements more of a, 'fire and forget' ideology for scanning mixed with a little math.
On startup, scanrand breaks itself up into two processes. One processes is responsible for doing nothing but sending out SYN packets using libnet. The other process is responsible for receiving the responses the remote computers send back using libpcap. One important thing to note here is that these processes work independently. There is no consulting with the other process on, "Did you send this packet out?" or, "Is this a valid packet?" Scanrand stores no list of IP addresses it is expecting a response from and the sending process does not wait for a response at all. It fires off a SYN, and then moves on to the next computer leaving the receiving process to sort out the flood of responses to come.
So how does the receiving process do this? It doesn't know what the initial sequence number of any of the packets sent are. It only knows it got a response packet. (A SYN/ACK, or a ICMP error message). It could be from anyone. It could be a SYN/ACK from your email client checking your email every five minutes. It could be Windows sending the names of the DVDs you just played to their gigantic database without your knowledge.
The key is what the sending process of scanrand sends out as initial sequence numbers which are not exactly randomly generated. Scanrand takes the source address and port, along with the destination address and port, concatenates them along with key, and runs them through a SHA-1 truncated to 32-bits one-way hash algorithm which becomes the initial sequence number for the outgoing packet. Scanrand calls these 'Inverse SYN cookies.' The reason we use a one-way hash function is because the likely hood of collision is low. This means that given different input data to the hash function, the probability of the hash function generating the same result is very very low.
hash(input1) = output1
hash(input2), hash(input3) ... hash(inputn) != output1
Table 1-1: One-way hash algorithm [4]
In table 1-1, input1 is the source, source port, destination, and destination port along with a key. Therefore, if we get a response, we subtract 1 from the ACK sequence number in the reply packet (since this should be one greater than the initial sequence number we sent ) and hash it. If that hash matches the hash of the source, source port, destination, and destination port (which we also pulled from the reply packet) along with our key, then this is a valid response to our scan.
Using this method, scanrand doesn't have to wait for hosts to respond before moving on to the next host. It can fire off as many SYN packets as the machine or bandwidth can handle. It also doesn't need to keep track of any sequence numbers of any kind. It just fires and forgets.
Traditional scanning across hosts is generally serialized where as the scanrand method is scanning multiple hosts at a time. The traditional scanner will connect to host A, wait for the response, and then move to host B. The problem with this method is that the scanner has to wait for the host to respond. Depending on how long the scanner is set to wait, scanning large networks could be timely. Often there is not always a machine listening or the machine cannot be reached and the timeout for a response will be the maximum. This leads to long scanning times when scanning large networks. Scanrand's method of scanning maximizes scanning time and minimizes waiting time.
Traditional scanning with nmap
The Network Mapper (nmap) is a feature-rich scanning tool which has come to be a very valuable, and well-known in the security industry. It is available from and can be run under Windows or Unix-based operating systems.
I have been a big fan of nmap for a while. Many a bad guy I have scanned with this feature-rich tool. I figured nmap could parallelize scanning across hosts, keep track of connections and see when a valid response was received. Not exactly the way scanrand does it, but it would give a similar effect if it can do that. Pouring over the nmap man page, I found some features, listed in table 1-2, that could possibly give scanrand a run for its money. We will see.
Table 1-2: Interesting nmap options.
The closest option I see for the effect we are looking for (parallel scanning across hosts) is the -M option. The manual page says this is only used in TCP connect() scans, which is not exactly what we want to use, but if we want to do parallel scanning, we'll have to settle.
We'll put these options to good use to see what nmap can do to represent the traditional scanners in scanning large networks when put up against the new kid on the block, scanrand.
The Showdown... nmap
We'll time and scan around a 16,000 host network with both tools to see how each performs under scanning large networks. Though I don't control a network with thousands upon thousands of hosts, I do have an internal network made up of a mere four computers. Figure 1-2 outlines my network which the scanning will occur on. I will be scanning from 192.168.64.2 as it is the machine with the most power.
The fact that thousands of hosts don't exist on my network does not keep me from scanning thousands of 'hosts'. With a little iptables magic, we can simulate thousands of websites running on the 192.168.0.0/18 network if we wish. We accomplish this by adding a rule to the firewall simliar to the one below for each website we wish to simulate where (host) is the IP we want to act as a webserver.
# iptables -A PREROUTING -s 192.168.64.2 -d (host) -j DNAT --to 192.168.74.2
This rule will NAT all traffic from the scanning machine to the webserver in the DMZ [3]. This gives us the effect that any 192.168.0.0/18 addresses could be running a webserver. I've created a little perl script to generate rules for the firewall to allow the scanner to connect to port 80 on 192.168.74.2 through this method.
#!/usr/bin/perl -w $i=0; $j=0; while ($i <= 63) { $j=0; while ($j <= 254) { if (rand() < 0.005) { open(OUTPUT, ">>rules.txt") or die "Could not open file: $!\n"; print OUTPUT "/sbin/iptables -A FORWARD -s 192.168.64.2 -d 192.168.$i.$j -p tcp --dport 80 -j ACCEPT\n"; } $j++; } $i++; }
The particular run of our perl script generated 72 possible webservers on the 192.168.0.0/18 network. Now that I know how many webservers are on our site, I can accurately judge the data loss in scanning. The traffic to the other IP addresses besides the one generated by our perl script will be silently dropped.
Now that the firewall and network is in place, let the games begin! The venerable nmap will be the first to bombard my poor network.
# nmap -version
nmap V. 3.10ALPHA4
# nmap -v -n -P0 -sS -T 5 -p 80 192.168.0.0/18
Host 192.168.0.1 appears to be up ... good.
Initiating SYN Stealth Scan against 192.168.0.1
The SYN Stealth Scan took 2 seconds to scan 1 ports.
Interesting ports on 192.168.0.1:
Port State Service
80/tcp filtered http
Host 192.168.0.2 appears to be up ... good.
Initiating SYN Stealth Scan against 192.168.0.2
The SYN Stealth Scan took 2 seconds to scan 1 ports.
Interesting ports on 192.168.0.2:
Port State Service
80/tcp filtered http
Host 192.168.1.138 appears to be up ... good.
Initiating SYN Stealth Scan against 192.168.1.138
Adding open port 80/tcp
The SYN Stealth Scan took 0 seconds to scan 1 ports.
Interesting ports on 192.168.1.138:
Port State Service
80/tcp open http
Clearly, nmap is much faster when there is a host to respond to its probe as seen in the output above to 192.168.1.138. The tcpdump dump below gives us further insight into nmap's scanning method.
02:00:06.232252 192.168.64.2.61623 > 192.168.0.1.80:
S 4007069542:4007069542(0)
02:00:06.549103 192.168.64.2.61624 > 192.168.0.1.80: S 45489116:45489116(0)
02:00:06.869128 192.168.64.2.61625 > 192.168.0.1.80: S 2118562022:2118562022(0)
02:00:07.189156 192.168.64.2.61626 > 192.168.0.1.80: S 4007069542:4007069542(0)
02:00:07.609128 192.168.64.2.61627 > 192.168.0.1.80: S 45489116:45489116(0)
02:00:07.929149 192.168.64.2.61628 > 192.168.0.1.80: S 2118562022:2118562022(0)
02:00:08.253109 192.168.64.2.61623 > 192.168.1.138.80: S 3456156783:3456156783(0)
02:00:08.255327 192.168.1.138.80 > 192.168.64.2.61623: S 2223686605:2223686605(0) ack 3456156784 win 16080
02:00:08.255470 192.168.64.2.61623 > 192.168.1.138.80: R 3456156784:3456156784(0) win 0 (DF)
As shown, nmap sends up to six SYN packets to the target until it gives up. These packets are sent in time intervals depending on what -T value you use, or by setting the option -max_rtt_timeout manually. This can be very costly(~1.7secs/machine [with -T 5]) in scanning large networks where big chunks of IP addresses don't have a machine listening.
Let's do a little tweaking and not see if we can speed this up just a little. Since nmap tries to scan before knowing if the host is up, we need to remove the -P0 as we only want to scan the hosts that appear to be up. -P0 is very helpful if you know a host is up, but blocking nmap's attempt at determining if it's up.
# nmap -v -n -sS -T 5 -p 80 192.168.0.0/18
[ ... ]
Host 192.168.63.254 appears to be down, skipping it.
Host 192.168.63.255 appears to be down, skipping it.
Nmap run completed -- 16384 IP addresses (70 hosts up) scanned in 194.322 seconds
That's more like it. 16,384 hosts in 194 seconds is not bad at all. Of course there were repercussions for such speed, which is loss of data accuracy. On a local network nmap using -T 5 missed 2 possible servers. Backing down on -T a little should give us all servers which it does on our local network. On a fast network that gives us 84.5 hosts/second. The time would, of course, increase as we decreased the -T value, while the accuracy increased. I would not recommend trying -T 5 on anything but a local networks. It will very unreliable over internet connections as it does not way very long (0.3 seconds) for hosts to respond. This is a weakness in the traditional style scanning where hosts are scanned in sequence one by one. Next, we'll see how scanrand fairs in the scanning competitions.
The Showdown... scanrand
Before we begin scanning with scanrand, let's take a look at the output we would expect from scanrand since there is not much documentation on it. I scanned a fairly small network (with permission of course) of a friend's site to get some output with scanrand as shown below.
UP: 10.0.0.3:80 [18] 0.181s
un03: 10.0.0.8:80 [18] 0.274s( 192.168.64.2 -> 10.0.0.8 )
UP: 10.0.0.22:80 [19] 0.558s
UP: 10.0.0.10:80 [18] 0.890s
UP: 10.0.0.30:80 [18] 1.243s
UP: 10.0.1.3:80 [18] 5.261s
un01: 10.0.0.116:80 [20] 5.429s( 192.168.64.2 -> 10.0.0.116 )
255 = 10.104.191.97|80 [17]1673.047s(192.168.64.2 -> 10.1.73.8)
The first column is the status of the machine probed. The common statuses can be found in Table 1-3.
Table 1-3: Scanrand statuses
The second column is the machine we received a response from whether it be a ICMP error or a SYN/ACK.
The third column in brackets is the estimated hop count to the target machine based on the time-to-live(TTL) of the IP packet we received as a response. The estimation algorithm, which is essentially listed below[1], takes advantage of the fact that most operating systems use a multiple of 32 as their TTL values. There are some other calculations performed in specific situations. (Particularly with resets).
passive_factor = 32;
if(ttl%passive_factor == 0) ttl--;
return(passive_factor - (ttl%passive_factor));
The fourth column is the number of seconds elapsed since the beginning of the scan until the host responded. Note, this is not the time elapsed from when the SYN packet was sent out by the scanning host.
The fifth column is only shown when we get a valid ICMP message as a response. RFC 792[2], which defines the ICMP protocol, states that ICMP unreachable messages, as well as time-exceeded messages (scanrand looks for either), must provide the first 8 bytes of the original IP datagram header. Scanrand displays this data in column 5.
Now that we can read the output of scanrand, let's put it to work.
# scanrand -c -b0 -t 3000 192.168.0-63.1-254:80
# tcpdump -s 1500 -i eth0 -w scanrand.tcpdump net 192.168.0.0/18 '(tcp and port 80) or icmp
The -c tells scanrand to verify that icmp responses are not spoofed. The -b0 option tells scanrand to send packets as fast as possible (default). We could limit the rate of packet output by specifying something like -b1M if we were on a 1 meg link. The -t 3000 option is important. This is how long scanrand will wait for a response (any response) before exiting. I set this high since I knew I was not going to get many responses and I wanted my scan to finish. Scanrand doesn't seem to take the standard CIDR network masks like nmap does which is a little annoying. Networks are specified using ranges and commas. Our scan above is going to cover the 192.168.0.0/18. These are the most useful options of scanrand though more options, as well as some experimental ones, can be found by running scanrand with no options.
Scanrand scanned blazingly fast. A few seconds after issuing the command, my mouse stopped working, and my computer became unresponsive. Another few seconds and it came back alive. A 'quick' top showed scanrand eating all available CPU time as it blasted as many packets as it could towards its several thousand destinations. Even if my 'weak' computer was not enough for the greedy scanrand, it managed to shoot off an impressive amount of packets. Too bad my network could not handle them. The first time with -b0 enabled, scanrand reported only 30 of the 72 webservers. A review of the tcpdump file on the scanning box only showed this many response packets coming back to the scanner so they were being dropped.
A little tweaking around and I found the needed -b value.
[ ... ]
UP: 192.168.55.227:80 [01] 28.302s
UP: 192.168.57.39:80 [01] 28.929s
UP: 192.168.59.101:80 [01] 30.045s
UP: 192.168.59.213:80 [01] 30.276s
UP: 192.168.59.226:80 [01] 30.299s
UP: 192.168.60.22:80 [01] 30.402s
UP: 192.168.60.208:80 [01] 30.768s
UP: 192.168.61.5:80 [01] 30.884s
UP: 192.168.62.45:80 [01] 31.494s
UP: 192.168.62.252:80 [01] 31.928s
UP: 192.168.63.81:80 [01] 32.113s
UP: 192.168.63.128:80 [01] 32.241s
After only 32.241 seconds using -b85M, scanrand had found all 72 webservers and successfully probed all 16,384 addresses, consistently (although the time did reach all the way up to 68 seconds sometimes though this is more than likely a firewall issue). That averages to 512 hosts/sec. Pretty impressive.
And the winner is...
For scanning an internal network for rogue servers, such as an unauthorized webserver, scanrand has the upper hand for accuracy and speed. On the other hand, scanrand lacks the maturity and features that makes nmap such a great tool.
For bypassing stateless router ACLs looking for servers and other various tricks easily capable with nmap, scanrand just can't compare though it's not supposed to. I can't say for sure what Dan has in mind for scanrand as far as features, but I doubt it was ever intended to be a replacement for nmap.
Scanrand and nmap together make an excellent combination as scanrand can be used to find servers quickly and accurately that you would use nmap to enumerate further on. From my personal experience, nmap seems to do better scanning individual hosts over multiple ports (not to mention the OS fingerprinting and a plethora of other options).
Detecting Scanrand
Scanrand makes no attempt in covering up what it is. As shown below, both version 1.0 and 1.10 use an IP id of 255 and a TTL of 255 on outgoing SYN packets.
16:01:06.450963 192.168.74.2.26922 > 192.168.64.25.80:
S [tcp sum ok] 2957819677:2957819677(0) win 4096 (DF)
(ttl 255, id 255, len 40)
16:01:06.470964 192.168.74.2.26922 > 192.168.64.26.80: S [tcp sum ok] 3296526466:3296526466(0) win 4096 (DF) (ttl 255, id 255, len 40)
16:01:06.490961 192.168.74.2.26922 > 192.168.64.27.80: S [tcp sum ok] 811733058:811733058(0) win 4096 (DF) (ttl 255, id 255, len 40)
16:01:06.510955 192.168.74.2.26922 > 192.168.64.28.80: S [tcp sum ok] 646406728:646406728(0) win 4096 (DF) (ttl 255, id 255, len 40)
16:01:06.530956 192.168.74.2.26922 > 192.168.64.29.80: S [tcp sum ok] 1922740421:1922740421(0) win 4096 (DF) (ttl 255, id 255, len 40)
16:01:06.550955 192.168.74.2.26922 > 192.168.64.30.80: S [tcp sum ok] 498232123:498232123(0) win 4096 (DF) (ttl 255, id 255, len 40)
This is simple enough to detect. If we see many probes from one host with a TTL set to 255 and id set to 255 we know they are using scanrand. Also, we see the same source port being used (across multiple hosts) which is not normal. The source port changes on each innvocation of scanrand. A simple snort signature to detect scanrand being used would be:
alert tcp $EXTERNAL_NET any -> $HOME_NET any (msg:"Possible scanrand Scan"; id:255; ttl:255; flags:S; classtype:attempted-recon; sid:9992; rev:1;)
Of course this signature could very easily trigger on valid traffic as an IP id of 255 with a TTL of 255 in a SYN packet is valid traffic. The chances of this combination coming up in an ACK packet is more likely though the chance is there for a SYN. Below we see a SSH session when the IP id rolls over from 65535 to 0 and eventually increase to 255. The signature will never trigger between these Linux boxes as thier TTL values are initially 64. It is more likely to trigger when a Solaris 2.x machine is on the network as it is reported to use an initial TTL of 255. Other operating systems, such as some versions of Cisco IOS, are also known to use 255 as a TTL.
22:43:17.842460 192.168.74.2.22 > 192.168.74.1.1027:
P 359760:359984(224) ack 4839 win 32120
22:43:17.844996 192.168.74.2.22 > 192.168.74.1.1027: P 359984:360208(224) ack 4839 win 32120
22:43:17.847510 192.168.74.2.22 > 192.168.74.1.1027: P 360208:360416(208) ack 4839 win 32120
22:43:17.851393 192.168.74.2.22 > 192.168.74.1.1027: P 360416:360800(384) ack 4839 win 32120
Another intersting sidenote about scanrand is that is does not verify ICMP error messages from scanned hosts by default. The -c option must be explicitly set to make scanrand verify ICMP error packets are indeed a valid reply. Using hping2, and a home-brewed patch (See Appendix A), we can generate a flood of bad data.
From a host that notices a scanrand scan, we issue our hping command:
# hping2 -d 25 --icmptype 3 --icmpcode 1 192.168.74.2 --icmp-saddr 192.168.64.1 --icmp-daddr 192.168.74.1 --fast
HPING 192.168.74.2 (eth0 192.168.74.2): icmp mode set, 28 headers + 25 data bytes
This command sends a barrage of ICMP destination unreachable to the scanning host that floods it with bogus information. The only problem is that valid responses are still sent by the listening hosts as well. This technique could be useful depending on who's behind the scanning host.
On the scanrand users console, we get:
un01: 192.168.74.1:2222 [01] 1.868s( 192.168.64.1
-> 192.168.64.2 )
un01: 192.168.74.1:2222 [01] 1.968s( 192.168.64.1 -> 192.168.64.2 )
un01: 192.168.74.1:2222 [01] 2.068s( 192.168.64.1 -> 192.168.64.2 )
un01: 192.168.74.1:2222 [01] 2.168s( 192.168.64.1 -> 192.168.64.2 )
un01: 192.168.74.1:2222 [01] 2.268s( 192.168.64.1 -> 192.168.64.2 )
un01: 192.168.74.1:2222 [01] 2.368s( 192.168.64.1 -> 192.168.64.2 )
un01: 192.168.74.1:2222 [01] 2.468s( 192.168.64.1 -> 192.168.64.2 )
un01: 192.168.74.1:2222 [01] 2.568s( 192.168.64.1 -> 192.168.64.2 )
which was all generated from our hping command. It would be trivial to create a script for hping to send some ICMP unreachable error message for many of our hosts. Moral of the story: use -c.
Conclusion
While the concept of scanrand and the tool itself are very useful and innovative, I can see this technology being abused. Besides the obvious, this type of scanning could greatly increase the ability of a worm to find hosts on the Internet to infect. This could mean faster propagation of worms. Of course, there is always the good and the bad of any technology, and network administrators might use it to find exposed ports on their local networks in a quick and accurate fashion.
Scanrand is a tool that any network administrator should take a look at for auditing internal machines or other various tasks involving network service discovery.
References
[1] Kaminsky, Dan. "Paketto Keiretsu source code".
Dec 24, 2002.
URL:
[2] Postel J. "RFC 793 - INTERNET CONTROL MESSAGE
PROTOCOL"
Sept, 1981.
URL:
[3] Russell, Rusty. "Linux 2.4 NAT HOWTO".
Jan 14, 2002.
URL:
[4] Schneier, Bruce. Applied Cryptography John Wiley and Sons. 1996. 2nd ed. [5] Stevens, Richard W. UNIX Network Programming. Prentice-Hall. 1998. vol 1. 2nd ed. [6] Stevens, Richard W. TCP/IP Illustrated, Volume 1. Reading: Addison Wesley Longman, Inc, 1994.
Appendix A: hping2 patch
Disclaimer: I make no guarantees this patch is portable or doesn't break anything. I only needed this to work on my box for testing and made a quick hack.
--- hping2/globals.h 2001-08-10 11:57:44.000000000
-0400
+++ hping2-3/globals.h 2002-12-07 11:10:53.000000000 -0500
@@ -105,6 +105,8 @@
sign[1024],
rsign[1024],
ip_opt[40],
+ icmp_saddr[1024],
+ icmp_daddr[1024],
ip_optlen;
extern struct sockaddr_in local, remote;
--- hping2/main.c 2001-08-13 20:07:33.000000000 -0400
+++ hping2-3/main.c 2002-12-07 11:52:07.000000000 -0500
@@ -23,6 +23,7 @@
#include
#include
#include
+#include
#include "hping2.h"
@@ -123,6 +124,8 @@
ifname [1024] = {'\0'},
ifstraddr [1024],
spoofaddr [1024],
+ icmp_saddr [1024],
+ icmp_daddr [1024],
sign [1024],
rsign [1024], /* reverse sign (hping -> gniph) */
ip_opt [40],
@@ -225,7 +228,7 @@
resolve((struct sockaddr*)&local, ifstraddr);
else
resolve((struct sockaddr*)&local, spoofaddr);
-
+
srand(time(NULL));
/* set initial source port */
--- hping2/parseoptions.c 2001-08-14 07:02:52.000000000 -0400
+++ hping2-3/parseoptions.c 2002-12-07 11:38:16.000000000 -0500
@@ -102,6 +102,8 @@
":-icmp-cksum",
"=-icmp-ts",
"=-icmp-addr",
+ ":-icmp-saddr",
+ ":-icmp-daddr",
"=-tcpexitcode",
"=-fast",
"=-tr-keep-ttl",
@@ -432,6 +434,16 @@
usec_delay.it_value.tv_usec =
usec_delay.it_interval.tv_usec = 100000;
ESAC
+ ONLYGNUCASE("-icmp-saddr")
+ SUIDLIMIT;
+ CHECKARG;
+ strncpy (icmp_saddr, hoptarg, 1024);
+ ESAC
+ ONLYGNUCASE("-icmp-daddr")
+ SUIDLIMIT;
+ CHECKARG;
+ strncpy (icmp_daddr, hoptarg, 1024);
+ ESAC
ONLYGNUCASE("-tr-keep-ttl")
opt_tr_keep_ttl = TRUE;
ESAC
--- hping2/sendicmp.c 2001-08-13 19:27:52.000000000 -0400
+++ hping2-3/sendicmp.c 2002-12-07 12:27:38.000000000 -0500
@@ -16,6 +16,10 @@
#include
#include
#include
+#include
+#include
+
+#include
#include "hping2.h"
#include "globals.h"
@@ -264,9 +268,12 @@
struct myicmphdr *icmp;
struct myiphdr icmp_ip;
struct myudphdr icmp_udp;
+ struct in_addr temp;
int errno_save = errno;
int left_space = data_size;
+ memset(&temp, 0, sizeof(struct in_addr));
+
packet = malloc(ICMPHDR_SIZE + data_size);
if (packet == NULL) {
perror("[send_icmp] malloc");
@@ -299,9 +306,27 @@
icmp_ip.ttl = 64; /* 64 */
icmp_ip.protocol = icmp_ip_protocol; /* 6 (TCP) */
icmp_ip.check = 255; /* FIXME: compute */
- memcpy(&icmp_ip.saddr, "AAAA", 4);
- memcpy(&icmp_ip.daddr, "BBBB", 4);
+ if (icmp_saddr[0] == '\0') {
+ memcpy(&icmp_ip.saddr, "AAAA", 4);
+ }
+ else {
+ if (inet_aton(icmp_saddr, &temp) == 0) {
+ goto no_space_left;
+ }
+ memcpy(&icmp_ip.saddr, &temp.s_addr, 4);
+ }
+
+ if (icmp_daddr[0] == '\0') {
+ memcpy(&icmp_ip.daddr, "BBBB", 4);
+ }
+ else {
+ if (inet_aton(icmp_daddr, &temp) == 0) {
+ goto no_space_left;
+ }
+ memcpy(&icmp_ip.daddr, &temp.s_addr, 4);
+ }
+
/* UDP header */
icmp_udp.uh_sport = htons(1111);
icmp_udp.uh_dport = htons(2222);
--- hping2/sendtcp.c 2001-08-13 19:27:52.000000000 -0400
+++ hping2-3/sendtcp.c 2003-01-26 23:20:23.000000000 -0500
@@ -15,6 +15,7 @@
#include
#include
#include
+#include
#include "hping2.h"
#include "globals.h"
--- hping2/sendudp.c 2001-08-13 19:27:52.000000000 -0400
+++ hping2-3/sendudp.c 2003-01-26 23:20:38.000000000 -0500
@@ -15,6 +15,7 @@
#include
#include
#include
+#include
#include "hping2.h"
#include "globals.h"
--- hping2/usage.c 2001-08-10 11:57:44.000000000 -0400
+++ hping2-3/usage.c 2002-12-07 11:34:18.000000000 -0500
@@ -115,6 +115,8 @@
" --icmp-ipid set ip id ( default random )\n"
" --icmp-ipproto set ip protocol ( default IPPROTO_TCP )\n"
" --icmp-cksum set icmp checksum ( default the right cksum)\n"
+" --icmp-saddr set saddr in icmp data ( default AAAA )\n"
+" --icmp-daddr set daddr in icmp data ( default BBBB )\n"
);
exit(0);
} | http://www.secureworks.com/research/articles/scanrand | crawl-002 | refinedweb | 5,484 | 76.01 |
To search IT Wiki:
The IT Wiki default search mode will return results with any of the words in your query. For instance, a search using the words search engine returns results containing only search but not engine or only engine but not search, in addition to the search results containing both words.
You can also perform a phrase search by enclosing more than one word in quotes: "search engine" returns a targeted set of results with both words in the correct order.
If your search terms include a common "stop word" (such as the, one, your, more, right, while, when, who, which, such, every, about) it will be ignored by the search system. If you are trying to do a phrase search or all-words-only search, including common stop words may result in no search results. Short numbers, and words that appear in half of all articles, will also not be found. In this case, omit those words and rerun the search.
If a word appears in an article with single quotes, it will only be returned in search results if the search term includes single.
The search automatically searches the following namespaces:
To change the namespace being searched, scroll to the bottom of the search results page, uncheck the namespaces you do not want to search, and check the ones that you do want to search.
For reasons of efficiency and priority, very recent changes are not always immediately taken into account in searches. At the moment, the search engine uses an index that is not updated at all. This is temporary.
<< Back to IT Wiki Help | http://it.toolbox.com/wiki/index.php/ToolboxWiki:Searching_for_an_article | CC-MAIN-2014-23 | refinedweb | 270 | 67.49 |
Create a program C# to ask the user for a distance in meters and the time taken (hours, minutes, seconds).
Display the speed, in meters per second, kilometers per hour and miles per hour.
1 mile = 1609 meters.
1200
0
13
45
Speed in meters/sec is 1.454545
Speed in km/h is 5.236363
Speed in miles/h is 3.254421
using System;
public class FloatSpeedUnits
{
public static void Main(string[] args)
{
float distance = Convert.ToSingle(Console.ReadLine());
float hour = Convert.ToSingle(Console.ReadLine());
float min = Convert.ToSingle(Console.ReadLine());
float sec = Convert.ToSingle(Console.ReadLine());
float timeBySeconds = (hour*3600) + (min*60) + sec;
float mps = distance/timeBySeconds;
float kph = (distance/1000.0f) / (timeBySeconds/3600.0f);
float mph = kph/1.609f;
Console.WriteLine("Speed in meters/sec is {0}", mps);
Console.WriteLine("Speed in km/h is {0}", kph);
Console.WriteLine("Speed in miles/h is {0}", mph);
}
}
Practice C# anywhere with the free app for Android devices.
Learn C# at your own pace, the exercises are ordered by difficulty.
Own and third party cookies to improve our services. If you go on surfing, we will consider you accepting its use. | https://www.exercisescsharp.com/data-types-a/float-value/ | CC-MAIN-2022-05 | refinedweb | 192 | 62.75 |
Function Callables:
<wsgi> <pythonPaths> <path path="C:\coolapp-1.1" /> </pythonPaths> <scriptMappings> <scriptMapping scriptName="coolapp.wsgi" callable="coolapp.dispatchers.wsgi_application" /> </scriptMappings> </wsgi>
First, we add C:\coolapp-1.1 to Python’s path so that we can import it. Next, we tell it that any requests for coolapp.wsgi should be dispatched to the function coolapp.dispatchers.wsgi_application. This is completely equivalent to the wrapper file, but saves us from creating it. Visiting will run coolapp.
Class Callables
Functions aren’t the only things in Python that are callable; classes are also callable (it creates an instance of the class). Let’s say we upgrade coolapp to version 2.0 (installed in C:\coolapp-2.0). The team has made some changes, and their WSGI application is now a class, WsgiApplication. This class has a __call__ method (making its instances callable as well!), so our WSGI application is an instance of the WsgiApplication class. We could use a coolapp.wsgi wrapper again:
import sys sys.path.append("C:\coolapp-2.1") import coolapp.dispatchers.WsgiApplication application = coolapp.dispatchers.WsgiApplication()
Again, our little wrapper doesn’t do much, so NWSGI provides a shortcut:
<wsgi> <pythonPaths> <path path="C:\coolapp-2.0" /> </pythonPaths> <scriptMappings> <scriptMapping scriptName="coolapp.wsgi" callable="coolapp.dispatchers.WsgiApplication()" /> </scriptMappings> </wsgi>
This time, NWSGI will create an instance of WsgiApplication, and then call the instance and return the result to IIS. This shortcut will only work if the class doesn’t require any arguments; if it does, it needs to be wrapped in a .wsgi file (when in doubt, you can always use a wrapper file). Again, visit to run the application.
There’s actually one more case: Python classes that implement the iterator protocol, but I don’t think two many applications are implemented that, so I’ll skip it. PEP 333 gives an example if you’re really interested. | http://blog.jdhardy.ca/2009_06_01_archive.html | CC-MAIN-2017-39 | refinedweb | 312 | 52.66 |
My fellow Roslyn tester @vreshetnikov has found not one, but two ways to do the impossible:
1:
using System; class Program { static void Main() { var open = Enum.ToObject(typeof(C<>.E), 0); Console.WriteLine(open.GetType()); } } class C<T> { public enum E { } }
Arguably those 2 ways aren't really different, it's same trick with 2 different hats :). They both rely on the enum inside the generic type and it's that enum who manages to "create" such instances, the rest of the code just exposes that.
This is fun, turns out that the second way doesn't actually create an instance of an open type, at least that's what IsGenericTypeDefinition claims:
using System;
class Program
{
static void Main()
{
var open1 = Enum.ToObject(typeof(C<>.E), 0);
Console.WriteLine(open1.GetType().IsGenericTypeDefinition);
Action<C<int>.E> a = M;
var open2 = a.Method.GetGenericMethodDefinition().GetParameters()[0].DefaultValue;
Console.WriteLine(open2.GetType().IsGenericTypeDefinition);
Console.WriteLine(open1.GetType() == open2.GetType());
Console.WriteLine(open1.Equals(open2));
}
static void M<T>(C<T>.E e = 0) { }
}
class C<T>
{
public enum E { }
}
This prints True, False, False, False. The type you get via the second way isn't open and it's not even equal to the type you get the first way. It would have been even more funny if the Equals returned true 🙂
@Mike: your second comment proves that these must be different tricks, since you obtain objects with very different types!
What does open2 give for it's type argument then? It must be open since none has been specified!
Wow, amazing testing.
Console.WriteLine-ing the types gives the same answer for both; however, dumping the types with WinDbg gives open1 as
C`1+E and open2 as type C`1+E[T].
Weird stuff!
They have different type parameters as their type arguments (one from C`1+E type declaration and the other from method M). You can rename one of the type parameters to see the difference. | https://blogs.msdn.microsoft.com/kirillosenkov/2014/01/08/creating-an-instance-of-an-open-generic-type-without-specifying-a-type-argument/ | CC-MAIN-2016-44 | refinedweb | 329 | 63.8 |
Fortunately,.
Figure 3. State design structure.
Figure 4. Video player state diagram:
In order to use the Stage and execute a test of the program in ActionScript 3.0, you need to use the Display class. In general you can use either a sprite or a movie clip, but because you're not using a Timeline here, use a sprite. Open a new ActionScript file and enter the following code as TestState.as:
package { //Test states import flash.display.Sprite; public class TestState extends Sprite { public function TestState():void { var test:VideoWorks = new VideoWorks(); test.startPlay(); test.startPlay(); test.stopPlay(); test.stopPlay(); } } }
TestStatein the Document Class text window.
Test the movie by pressing Control+Enter (Command+Return) just as you would for any application test. In the Output window, you should see the following: class PlayState implements State { var videoWorks:VideoWorks; public function PlayState(videoWorks:VideoWorks) { trace("--Play State--"); this.videoWorks=videoWorks; } public function startPlay(ns:NetStream,flv:String):void { trace("You're already playing"); } public function.
Figure 5. Initial state of the video player).
Figure 6. Hierarchical statechart including the Pause state. | http://www.adobe.com/devnet/flashmediaserver/articles/video_state_machine_as3_03.html | crawl-002 | refinedweb | 183 | 50.73 |
Download presentation
Presentation is loading. Please wait.
Published byHamza Strowbridge Modified about 1 year ago
2
©David Dubofsky and 9-1 Thomas W. Miller, Jr. Chapter 9 T-Bond and T-Note Futures Futures contracts on U.S. Treasury securities have been immensely successful. But, the outlook for Treasury bond futures contracts is bleak, as the government has not issued any new 30-year bonds since October 2001.
3
©David Dubofsky and 9-2 Thomas W. Miller, Jr. The T-bond Futures Contract Underlying asset is: $100,000 (face value) in deliverable T-bonds. Futures prices are reported in the same way as are spot T-bonds, in "points and 32nds of 100%" of face value. A T-bond futures price of 112-15 equals 112 and 15/32% of face value, or $112,468.75. A change of one tick, say to 112-14, results in a change in value of $31.25.
4
©David Dubofsky and 9-3 Thomas W. Miller, Jr. T-Note Futures Prices For T-bonds, a tick is 1/32 nd. The resulting quote of 112-15 equals 112 and 15/32. But, for 5 and 10-year T-notes, a tick is ½ of a 32 nd, or $15.625 per tick. The resulting quote, say, of 98.095 = 98 and 9.50/32.. For CBOT futures prices for T-bonds and T-notes, see:.
5
©David Dubofsky and 9-4 Thomas W. Miller, Jr. What Determines T-bond and T-note Futures Prices, Basically? In a very simple sense, the futures price is the forward price of a Treasury bond, such that it has a forward yield [fr(t1,t1+30)] consistent with: [1+r(0,t1+30)] t1+30 = [1+r(0,t1)] t1 [1+fr(t1,t1+30)] 30 t1 = time until delivery, in years. 0t1t1+30
6
What is Deliverable? And When?.
7
Which T-bond will the Short naively Choose to Deliver?. If the short delivers a low priced bond, the short will receive less (low conversion factor) If the short delivers a high priced bond, the short will receive more (high conversion factor). ©David Dubofsky and 9-6 Thomas W. Miller, Jr.
8
The Invoice Amount and Conversion Factors A conversion factor for a given T-bond is its price if it had a $1 face value, and was priced to yield 6%. For a file of conversion factors, see:. So a cheap, low coupon bond will have a small conversion factor. Therefore, the short will receive less. ©David Dubofsky and 9-7 Thomas W. Miller, Jr.
9
So NOW, Which T-bond Will the Short Choose to Deliver? The one that costs the least…. ….and at the same time gets the short the most money upon delivery (i.e., the highest invoice amount). That is, the Max [invoice amount – quoted spot price] (Accrued Interest is ignored because it is included in both the invoice amount and the gross cash bond price) Max [(CF)(F) – (S)] During the delivery month, the amount in brackets will always be negative, for every deliverable bond….. WHY? ©David Dubofsky and 9-8 Thomas W. Miller, Jr.
10
©David Dubofsky and 9-9 Thomas W. Miller, Jr. Another Method to Identify the Cheapest to Deliver T-bond Before the delivery month, find the T-bond with the highest Implied Repo Rate. This is given by: Can be used to identify the “most likely to be delivered” T-bond. When coupons will be paid between today and the delivery day, include them, and the interest earned on them, in the carry return (see eqn. 9.5b).
11
A Good Concept Check Identify three T-bonds that are deliverable into the nearby T-bond futures contract. Which of these three bonds is the cheapest to deliver? Be able to show your work, and be able to explain why one of the T-bond is more likely to be delivered than the other two. ©David Dubofsky and 9-10 Thomas W. Miller, Jr.
12
©David Dubofsky and 9-11 Thomas W. Miller, Jr. Questions The implied repo rate for every deliverable T-bond must be less than interest rates available in the market (WHY?) Reverse cash and carry arbitrage will (almost never) be possible (WHY?)
13
The Options Held by the Short Quality option: can deliver any eligible bond. Timing option: can deliver on any day of the delivery month. Wild card option: futures cease trading at 2PM, but the short can announce intent to deliver as late as 8PM. End of month option: futures cease trading 8 business days before the end of the delivery month, but the short can deliver on any day of the month. ©David Dubofsky and 9-12 Thomas W. Miller, Jr.
14
Theoretical T-bond Futures Price Once the C-T-D T-bond has been identified, F = S + CC - CR (- value of shorts’ options) ©David Dubofsky and 9-13 Thomas W. Miller, Jr.
15
©David Dubofsky and 9-14 Thomas W. Miller, Jr. Using T-bond and T-note Futures to Hedge Interest Rate Risk Buy T-bond or T-note futures to hedge against falling interest rates. Sell them to hedge against rising interest rates. (Remember that when interest rates fall, bond prices rise, and when interest rates rise, bond prices fall.) Use T-bond futures to hedge against changes in long-term (15+ years) rates. Use 10-year T-note futures to hedge against changes in 8-10 year rates. rr Inherent risk exposure profits Long T-bond futures Short T-bond futures rr profits
16
©David Dubofsky and 9-15 Thomas W. Miller, Jr. Dollar Equivalency Estimate the loss in value if the spot YTM adversely changes by one basis point, denoted V S. CTD. Estimate the change in the futures price if the CTD’s price changes by S CTD, denoted F per $100 face value. It can be shown that: The profit, V F, is then $1000 F. Compute the number of futures contracts to trade, N, so that N V F = V S
17
©David Dubofsky and 9-16 Thomas W. Miller, Jr. Bond Pricing, I U.S. Treasury bonds and notes are coupon bonds. Their values are computed using: C is the semiannual coupon payment. F is the face value. Y is the unannualized, or periodic, 6-month yield. N is the number of 6-month periods to maturity. This assumes that the first coupon payment is 6 months hence.
18
©David Dubofsky and 9-17 Thomas W. Miller, Jr. Bond Pricing, II To calculate the value of a bond, one must discount each cash flow at the appropriate zero rate.. The bond’s value is:
19
©David Dubofsky and 9-18 Thomas W. Miller, Jr. Yield to Maturity (YTM) The YTM is the discount rate that makes the present value of the cash flows on the bond equal to the market price of the bond. Input PV = -1033.098, FV = 1000, PMT = 25 (semiannually), N = 4 (this is four semiannual periods) => CPT I/Y = 1.63838% (per six- month period). (1.63838%) (2) = 3.277% = YTM With Excel, use =YIELD("9/15/02","9/15/04",0.05,103.3098,100,2,0) With FinCAD, use aaLCB_y
20
©David Dubofsky and 9-19 Thomas W. Miller, Jr. Duration Duration is the weighted-average of the time cash flows are received from a bond. Example: Verified with Excel: =DURATION("6/25/2001","6/25/2003",0.06,0.068755,2,0) We will see that Modified Duration is handy for hedging purposes. Modified Duration: D/(1 + YTM/2) = 1.9135 / (1.03438) = 1.85.
21
©David Dubofsky and 9-20 Thomas W. Miller, Jr. U.S. Treasury Bond Price Quotes U.S. T-bond and T-note prices are in percent and 32nds of face value. For example (see fig. 9.1), on 12/01/00, the bid price of the 6 3/8% of Sep 01 T-note was 100 and 4/32% of face value. If the face value of the note is $1000, then the bid price is $1001.25. The asked price of this note is $1001.875. N.B. These prices are based on transactions of $1 million or more. In other words, a trader could buy $1 million face value of these notes for about $1,001,875 from a government securities dealer. These prices are quoted flat; i.e., without any accrued interest. Cash price = Quoted Price + Accrued Interest.
22
©David Dubofsky and 9-21 Thomas W. Miller, Jr. On December 1, 2000, the 6 3/8% of September 2001 was quoted to yield 6.12%. You can verify by using the YIELD function in Excel: =YIELD("12/01/00","9/30/01",0.06375,100.1875,100,2,1).
23
©David Dubofsky and 9-22 Thomas W. Miller, Jr. Some Extra Slides on this Material Note: In some chapters, we try to include some extra slides in an effort to allow for a deeper (or different) treatment of the material in the chapter. If you have created some slides that you would like to share with the community of educators that use our book, please send them to us!
24
©David Dubofsky and 9-23 Thomas W. Miller, Jr. Hedging With T-Bond Futures: Changing the Duration of a Portfolio Hedging decisions are essentially decisions to alter a portfolio’s duration. By buying or selling futures, managers can lengthen or shorten the duration of an individual security or portfolio without disrupting the underlying securities (an “overlay”). That is, adding (buying) T-bond or T-note futures to a portfolio increases its interest rate sensitivity, while selling futures decreases the interest rate sensitivity of the portfolio. A portfolio manager will want to decrease (increase) the duration of the portfolio if the manager expects interest rates to increase (decrease). A completely hedged portfolio lowers the duration to the duration of a short-term riskless Treasury bill.
25
©David Dubofsky and 9-24 Thomas W. Miller, Jr. The Key Concept: Basis Point Value (BPV). The bond portfolio manager can change the duration of the existing portfolio to the duration of a target portfolio. This “immunizes” the portfolio against a change in interest rates. That is, if the portfolio manager knows: –how the current and target portfolios respond to interest rate changes. –how T-bond (or T-note) futures contracts respond to interest rate changes. Fortunately, if interest rates change by a small amount, say one basis point, the value of the portfolio will change predictably.
26
©David Dubofsky and 9-25 Thomas W. Miller, Jr. BPV, II. Using the bond pricing formula, the duration formula, and some algebra, the change in the value of a bond or a portfolio of bonds if interest rates change by one basis point can be written: When dy = 0.0001 (1 basis point), then dB is called the basis point value (BPV).
27
©David Dubofsky and 9-26 Thomas W. Miller, Jr. BPV, III. If y is defined to be one-half of the bond’s annual yield to maturity (YTM), then for a bond, or a portfolio of bonds:
28
©David Dubofsky and 9-27 Thomas W. Miller, Jr. BPV, IV. The portfolio manager chooses a target duration so that it will have a particular BPV; i.e., a targeted change in value if interest rates change by one basis point. Assuming that the CTD bond and the bond portfolio will both experience a one basis point change in yield, the goal is to choose to buy or sell N F futures contracts so that BPV (target) = N F BPV (futures) + BPV (existing) Thus, the BPV of the existing portfolio, the target portfolio, and the futures contract must be computed.
29
©David Dubofsky and 9-28 Thomas W. Miller, Jr. BPV, V. To determine the BPV for either a T-bond or T-note futures contract, the cheapest-to-deliver (CTD) security must first be identified. The futures price generally tracks the CTD security. The BPV of the futures price is generally written as a present value BPV(futures)/[1+h(0,T)] where BPV(futures) is the BPV of the cheapest-to-deliver instrument divided by the CTD’s conversion factor. To solve for the appropriate number of futures contracts needed to change the duration of an existing portfolio to a target duration: N F = [BPV (target) - BPV (existing) ] / BPV (futures)
30
©David Dubofsky and 9-29 Thomas W. Miller, Jr. Example Using BPV.
31
©David Dubofsky and 9-30 Thomas W. Miller, Jr. Inputs: –Existing Portfolio Duration: 5.7 –Target Duration: 12.0 –March T-Bond Futures Price: 102-03 –Portfolio Value: $100,000,000 –Portfolio Yield to Maturity: 6.27% Solution: 1.Find the BPV of the existing portfolio and the target portfolio: BPV(existing) = (5.7 /(1 + 0.0627/2)) * $100,000,000 * 0.0001 = $55,267.36 BPV (target) = 12 /((1+0.0627/2)) * $100,000,000 * 0.0001 = $116,352.35
32
©David Dubofsky and 9-31
33
©David Dubofsky and 9-32 Thomas W. Miller, Jr. Finally, 3. Determine the number of contracts required to achieve the desired portfolio duration: N F = [BPV (target) - BPV (existing) ] / BPV (futures) ($116,352.35 - $55,267.36) / $74.156= 823.736 The bond portfolio manager should buy 824 March T-Bond futures contracts in order to increase the portfolio’s duration to 12 years. Note that the portfolio manager can choose any target duration.
34
©David Dubofsky and 9-33 Thomas W. Miller, Jr. Finally, (Really) Suppose the manager chooses to have a target duration of zero. This makes the BPV of the target equal zero. Then, N F = [BPV (target) - BPV (existing) ] / BPV (futures) (0 - $55,267.36) / $74.156= -745.285 The bond portfolio manager should sell 745 March T- Bond futures contracts in order to decrease the portfolio’s duration to 0 years.
35
©David Dubofsky and 9-34 Thomas W. Miller, Jr. Reading Treasury Bond Futures Prices Delivery dates exist every 3 months. Delivery months are in March, June, September, and December. On December 1, 2000, the Dec T-bond settle price is 102-02. This equals 102 and 2/32% of face value, or $102,062.50. The December 2000 futures price was down 17 ticks, or 17/32. This means that on December 14, 2000, the December contract settled at 102-19. A price change of one tick (1/32) will result in a daily resettlement cash flow of $31.25.
36
©David Dubofsky and 9-35 Thomas W. Miller, Jr. Treasury Bond Futures, Delivery The Delivery Process is Complicated. But, in sum: Any Treasury Bond that has fifteen or more years to first call, or at least 15 years to maturity (whichever comes first), as of the first day of the delivery month. The seller of the futures contract, I.e., the short, has the option of choosing which bond to deliver. Delivery can take place on any day in the delivery month…the short chooses. Cash received by the short = (Quoted futures price × Conversion factor) + Accrued interest. Conversion Factor? Wha?
37
©David Dubofsky and 9-36 Thomas W. Miller, Jr. The Necessity for the Conversion Factor At its website, the CBOT lists deliverable T-bonds and T-notes, by delivery date. For example, as of November 29, 2000, there were 34 T-bonds deliverable into nearby T-bond futures contracts. By allowing several possible bonds to be delivered, the CBOT creates a large supply of the deliverable asset. This makes it practically impossible for a group of individuals who are long many T-bond futures contracts to “corner the market” by owning so many T-bonds in the cash market that the shorts cannot fulfill their delivery obligation.
38
©David Dubofsky and 9-37 Thomas W. Miller, Jr. Recall that the invoice price equals the futures settlement price times a conversion factor plus accrued interest. The conversion factor is the price of the delivered bond ($1 par value) to yield 6 percent. The purpose of applying a conversion factor is to try to equalize deliverability of all of the bonds. If there were no adjustments made, the short would merely choose to deliver the cheapest (lowest priced) bond available. In theory, if the term structure of interest rates is flat at a yield of 6% then, by applying conversion factor adjustments, all bonds would be equally deliverable. In practice, however, there is a “cheapest to deliver” or CTD T- bond. This is the T-bond used to price futures contracts on T- bonds.
Similar presentations
© 2017 SlidePlayer.com Inc. | http://slideplayer.com/slide/4177461/ | CC-MAIN-2017-17 | refinedweb | 2,772 | 74.08 |
A SQL Server Blog Evolution Platform Developer Build (Build: 5.6.50428.7875)2005-07-16T00:59:00ZThe impact of Gemini (Or the power of a simple question)<P>If.</P> <P?" </P> <P>Wow. </P> <P? </P> <P>I hope you can appreciate the vigor and intensity we've been working with, and get some understanding for the focus. These are truly very exciting times! </P><div style="clear:both;"></div><img src="" width="1" height="1">Ashvini Sharma [MSFT] news at the BI Conference. Are you coming?<P>Hi folks, </P> <P>It's been a while since I posted. I'm back in the Analysis Services team now where we've been busy finishing off SQL Server 2008 and working on a set of technologies that will be unveiled at the BI Conference. </P> <P>I remember a conference back in the 7.0 days when we introduced OLAP Services and someone from the audience hurried outside to make a phone call. I overheard him saying "You need to see this... it's going to be big!"</P> <P <A class="" href="" mce_href="">here</A>. Until the conference, the abstract is the only information we can share, but believe me, we're itching to say more! </P> <P>If you do come by, I'll be in the back by the door waiting for people to make those calls. See you there!</P> <P>ash</P><div style="clear:both;"></div><img src="" width="1" height="1">Ashvini Sharma [MSFT] is ready!<P>For the past few months, a few of us have had the pleasure of working with Ordinal to create an extremely performant sort component. </P> <P>Chris, from Ordinal, sent an email earlier today announcing that they're done with a production ready version. </P> <P>This is really great news, especially if you know the history of Ordinal and their reputation. Chris has been one of the most solid developers I've worked with either inside or outside Microsoft. </P> <P>Anyways, check out <A href=""></A> if you're interested. </P> <P>Enjoy,</P> <P>ash</P><div style="clear:both;"></div><img src="" width="1" height="1">Ashvini Sharma [MSFT] tool and whitepaper for BI components<P>Hi again, </P> <P>Over the last few months a lot of you have expressed a need to do impact analysis and lineage investigations across the different BI components we've got.... if I change this table here what packages, cubes, reports will be affected. </P> <P>Well, earlier this week the BI team released a metadata pack that you can use for this. It includes sample projects, sample reports, etc. Right now it handles getting metadata from SSIS and SSAS, we hope to get to SSRS in the future. </P> <P>We decided to release the source code for it as well so that: </P> <P>- you have a piece of code that demonstrates using the object models for SSIS and SSAS, and</P> <P>- you can extend the work we've done for integrating other technologies in the metadata repository as well. </P> <P>While the tool is useful as it is, we're hoping there'll be a community effort to drive this forward as well... I can easily imagine a workspace on gotdotnet where active participation will make this tool more comprehensive than we could ever manage to do. </P> <P>Anyways, the link is <SPAN><A href=""></A></SPAN></P> <P><SPAN>There's also a whitepaper here: <A href=""></A></SPAN></P> <P><SPAN>As usual, I look forward to your feedback.</SPAN></P> <P><SPAN>enjoy</SPAN></P> <P><SPAN>ash</SPAN></P><div style="clear:both;"></div><img src="" width="1" height="1">Ashvini Sharma [MSFT], SSIS, Indigo, SSB, AAAAA!<P>This is a FAQ that we get at least once every time we present. I got it last week doing launch activities in Portugal, and then earlier today on a webcast on extending SSIS. </P> <P>For those not familiar with the excellent whitepaper on this, check this one out: <A href=""></A></P> <P>regards</P><div style="clear:both;"></div><img src="" width="1" height="1">Ashvini Sharma [MSFT]<P>As you know, we just declared SQL RTM earlier today. </P> <P. </P> <P>If you're one of our regular contributors and haven't received a thanks from me directly, apologies. Wish I could shake your hand. </P> <P>Now, on to the cigar. </P> <P> </P><div style="clear:both;"></div><img src="" width="1" height="1">Ashvini Sharma [MSFT]: Lookup from Text Files<P>Ever want to do a lookup on a text file without putting it in a database or using a merge join?</P> <P>Grant from the Project REAL team found a great nugget:</P> <P':</P> <P> select * <BR> from openrowset(bulk N'c:\temp\test.txt', formatfile = 'c:\temp\test.fmt') as x</P> <P>thanks, Grant! <BR></P> <P> </P><div style="clear:both;"></div><img src="" width="1" height="1">Ashvini Sharma [MSFT]: Debugging foreach NodeList enumerators<P>Earlier today Fred S. asked a great question. </P> <P>"Using the following data I’m trying to get each node Element populated into their own variables.<BR>XML: <BR><DataBases><BR> <DataBase><BR> <Name>Sales</Name><BR> <Action>DBCC</Action><BR> <FLOP>1</FLOP><BR> </DataBase><BR> <DataBase><BR> <Name>Inventory</Name><BR> <Action>DBCC</Action> <BR> <FLOP>1</FLOP><BR> </DataBase><BR></DataBases></P> <P><BR>Want to do:<BR>Name -> vsDataBase <BR>Action -> vsAction <BR>FLOP -> vnFLOP<BR> <BR>Where vsDataBase, vsAction and vnFlop are variables of type string, string, int32. "</P> <P>He was using For each loop's ForEach NodeList enumerator, lets see how we can do this. </P> <P>There might be other ways to do it, I wanted to do it using two steps... first get a database, then gets its element values. </P> <P>The result of the first step would be the nodelist, so the EnumerationType should be ElementCollection. Then there were the Outer* and Inner* properties that I confess I didn't understand. </P> <P>Here's how this enumerator currently works: </P> <P>- The OuterXPathString will be used to get the list of elements collection from the XML document specified earlier. In this case, our XPath string is '/DataBases/*' which would return all DataBase elements.</P> <P>- For each element in the collection we now have (i.e. for each DataBase element), the InnerXPath is applied. We can set this property to be '*' (or the equivalent 'child::*') and InnerElementType of 'NodeText' so that we get the value of the child elements. Since there're multiple children per DataBase, the result of the this XPath will be an array of strings (each string is the value of the element). </P> <P>For the first time through the loop, then, the current value of the enumerator is an array of three strings: {"Sales", "DBCC", "1"}. The next time through the loop the current value will be an array of three strings again: {"Inventory", "DBCC", "1"}. </P> <P>Per the discussion above the current value of the enumerator during an enumeration should be an array of strings, but I wanted to see the array to make sure that was right. Turns out I had to use an undocumented feature to do this. (As soon as I post this message I'll be sending a note to the doc folks to make sure this isn't undocumented for too long because it's really useful!). </P> <P>If you map the index '-1' to a variable of type 'Object', that variable gets populated with the complete collection (which is current value of the enumerator). Then I used a script task in the loop with simple code like so: </P> <P> Imports System.Collections<BR>. . .</P> <P> Dim o As IEnumerator<BR> Dim o2 As Object<BR> o = CType(Dts.Variables("Variable").Value, IEnumerator)<BR> o.Reset()<BR> o.MoveNext()<BR> o2 = o.Current<BR> <BR>and put a breakpoint at the last line. </P> <P>When you execute the package now, the breakpoint is hit and the first time through you can see that o2 is the string "Sales". Just step through the iterator to confirm the array contents are what you expect them to be. </P> <P>Knowing the contents of the array, then, it's fairly straight forward to do the mapping. Create the variables, set their types to string, then use the indices like this: </P> <P>User::vsDataBase 0<BR>User::vsAction 1<BR>User::vsFLOP 2</P> <P>Note that vsFLOP is not vnFLOP... the text is string, so you'll have to convert it to a number.</P> <P>Also note that this example assumes a well formed document. Specifically that each DataBase element will have three children in the right order.</P> <P>Think that's about it. </P> <P>Is there a better way to do this in a loop? Let me know! </P> <P>Thanks Fred for a great question. </P> <P>ash</P><div style="clear:both;"></div><img src="" width="1" height="1">Ashvini Sharma [MSFT]: Providing parameters when providers don't support them<P>This has come up a few times recently, and I couldn't find the information for them in the usual sources. </P> <P. </P> <P. </P> <P>Lets work through an example. Lets say you want to execute this statement: </P> <P> SELECT Income from Customer where Age > ?</P> <P>But your provider doesn't support finding out there's one parameter in this statement. </P> <P>What we can do here is to create two variables. Below we have the properties you'd set for the two variables displayed in a '<prop>:<value>' format.</P> <P>#1: </P> <P> Name: AgeVariable</P> <P> Type: String</P> <P> Value: 10</P> <P>#2: </P> <P> Name: SqlStatementVariable</P> <P> Type: String</P> <P> Expression: "SELECT Income from Customer where Age > " + @AgeVariable</P> <P> EvaluateAsExpression: True</P> <P>In this case I've hard coded the variable value to 10, but of course you can use whatever mechanism you want to (result of an Execute SQL task, the current value of a loop enumerator, etc.) to set that variable value. </P> <P>Now we can use the 'SqlStatementVariable' as the source for the OLEDB Source. </P> <P>How about on the destination side? What if I'm inserting into the customer table and want to set Age to 10, lets say, for all the rows.</P> <P>The trick there is to introduce the variables as columns inside your data flow using something like a Derived Column transform and then map this column to the colunms of your table. </P> <P>Hope this helps. If not, let me know and I can edit this post to make it more useful. </P> <P>regards,</P> <P>ash</P><div style="clear:both;"></div><img src="" width="1" height="1">Ashvini Sharma [MSFT] Best Practices - Performance<P>We've been slowly creating a list of best practices. <A href="">Simon</A> asked me about these at the PDC a couple of weeks back. It's time to share them out not just to make folks aware of them but also to solicit other goodness you'd like us to include in the official list. </P> <P>First off, Performance: <">[Oledb Source, Lookup, Fuzzy Lookup]: Remove columns which’re not used downstream.<o:p> </o:p> <LI class=MsoNormal[Oledb Source, Lookup, Fuzzy Lookup]: Use a select statement when fetching data from a view instead of using the table drop down. <LI class=MsoNormal[OLEDB Command Destination]: for large number of rows, this component might not scale because it sends one SQL statement per row. Persist data to a temporary table and use set based SQL. <LI class=MsoNormal[SCD]: for large number of rows that will not exist in the dimension table, consider using a lookup before the SCD. <LI class=MsoNormal[OLE DB Destination]: if the server is local, consider using SQL Server destination. <LI class=MsoNormal <P class=MsoNormal<o:p></o:p></P>[Flat file source]: turn on fast parse for columns that have types that fast parse understands. Look at BOL for more info on Fast Parse.<o:p> </o:p> <LI class=MsoNormal[Conditional Split]: For transforms that use conditions based on columns coming straight from OLEDB or ADO.Net sources, consider using the native filtering from the relational database to remove rows before they come in to the pipeline. <LI class=MsoNormal[Flat file Source]: For transforms that have all columns with the default column type and size, consider using the ‘Suggest Type’ functionality. <LI class=MsoNormal[OLEDB Destination]: Review the fast load settings on the destination adapter. <LI class=MsoNormal[SQL Server]: for OLEDB Destinations/SQL Server Destinations that perform bulk insert into a database, verify that the logging mode is appropriate for performance. Refer to BOL for more info.</LI></OL> <P class=MsoNormal </P><div style="clear:both;"></div><img src="" width="1" height="1">Ashvini Sharma [MSFT]"It is illegal to call out while inside message filter."<P: </P> <P class=MsoNormal><FONT face=Arial color=navy size=2><SPAN style="FONT-SIZE: 10pt; COLOR: navy; FONT-FAMILY: Arial". <?xml:namespace prefix = o">To avoid this, VS implements a message filter – a message filter that keeps most messages in a queue and prevent them from handling until the COM call is completed. </SPAN></FONT>">However, certain events (like WM_PAINT… see <A title=;en-us;176399;en-us;176399</A>). </SPAN></FONT></P> <P class=MsoNormal><FONT face=Arial color=navy size=2><SPAN style="FONT-SIZE: 10pt; COLOR: navy; FONT-FAMILY: Arial"><o:p>If you see this consistently (we've made quite a bit of an effort to avoid this), do drop me a line. </o:p></SPAN></FONT></P> <P class=MsoNormal><FONT face=Arial color=navy size=2><SPAN style="FONT-SIZE: 10pt; COLOR: navy; FONT-FAMILY: Arial"><o:p>regards</o:p></SPAN></FONT></P> <P class=MsoNormal><FONT face=Arial color=navy size=2><SPAN style="FONT-SIZE: 10pt; COLOR: navy; FONT-FAMILY: Arial"><o:p></o:p></SPAN></FONT> </P><div style="clear:both;"></div><img src="" width="1" height="1">Ashvini Sharma [MSFT] and debugging mysterious relational engine deadlocks<P>Over the last few days I've learnt a lot in how to debug SQL hangs thanks to Sunil from the SQL Server engine team. </P> <P.</P> <P.</P> <P. </P> <P>The DMVs in SQL 2005 were invaluable in this investigation, specifically <SPAN id=nsrTitle>sys.dm_os_waiting_tasks. </SPAN></P> <P><SPAN>While all of this is in BOL, and probably trivial to most folks familiar with SQL, the logic and debugging abilities of locking in SQL2005 are truly impressive to me. Of course, it doesn't hurt at all if someone knowledgeable is making sense of all this! </SPAN></P> <P><SPAN! </SPAN></P> <P><SPAN>regards</SPAN></P> <P><SPAN></SPAN> </P><div style="clear:both;"></div><img src="" width="1" height="1">Ashvini Sharma [MSFT]: Handling lookup misses<P>It's typical in data warehouse loads to have lookups that go against dimension tables. If the key doesn't exist, either a new one is created, or a default value is used. </P> <P>There're two ways to do this: </P> <P>1. Lookup is configured to redirect rows that have no match in the reference table to a separate output (error output), then use a derived column to specify a default value, and finally merge both the lookup success output and the output of the derived column using a union all transform. </P> <P>2. Lookup is configured to ignore lookup failures and pass the row out with null values for reference data. A derived column downstream of the lookup then checks for null reference data using 'ISNULL' and replaces the value with a default value.</P> <P>As you may know Union All is an async transform due to implementation issues. This means its going to create a new type of buffer on the output and copy the input buffer data to the output. </P> <P>Intuitively, #2 has been the way to go because it doesn't incur the cost of a memcopy, but I didn't get a chance to quantify the difference until now. Today, I was finally able to. </P> <P>The test harness includes a script component that feeds 100M rows to the lookup, and the output of the union all in option #1 and derived column in #2 gets consumed by a script component that doesn't do anything with the rows. The AMD guys have given us a 64bit dual core machine with a couple of procs to play with and that's what I ran this on. There's enough (32GB) of memory on the box so that we can focus on just the perf of this isolated scenario. Since I was only interested in this specific scenario, the lookup statement itself is 'select * from whatevertable where 1=0' which means all keys fail lookups.</P> <P>Average timings were: </P> <P>Option #1: 104 seconds. </P> <P>Option #2: 83 seconds. </P> <P>For folks that have 12-13 dimension lookups, using approach #2 might significantly aid performance. </P> <P>The other interesting fact here is that if there're lots of lookups, the execution tree that contains the lookups will be busy. Since there's one thread (currently) per execution tree, that thread will be doing a lot of work. Therefore, there will be a point where having X lookups on one thread would be slower than having X/2 lookups on it and a union all to introduce a new execution tree. I didn't get a chance to do that investigation as yet, hope to in the future. </P> <P>regards,</P> <P>ash</P><div style="clear:both;"></div><img src="" width="1" height="1">Ashvini Sharma [MSFT]<P>It's finally that part of the release when you see the end of the tunnel and there seems a good reason (or close to it) that your hair has lost more color this cycle.... we're close to shipping! </P> <P. </P> <P. <A href="">MXC</A> and <A href="">MST3K</A> have been my favorite shows in large part due to voice overs.</P> <P>In the MST tradition comes the latest installment of VS/SQL 2005 ads... if you haven't seen them already: <A href=""></A>. </P> <P>Not bad! </P> <P>Weren't we supposed to have flying cars and colonies on Mars by now? Oh well, looking forward to having my shipping cigar in the meantime!</P> <P> </P><div style="clear:both;"></div><img src="" width="1" height="1">Ashvini Sharma [MSFT] @ PDC<P>At <A href="">PDC</A> this year, Sergei and I will be presenting a session on how to extend Integration Services. This is a 400 level course so will go into more details than the 300 level <A href="">webcast</A> I did earlier this week for MSDN. </P> <P. </P> <P>So, I'll probably end up being the T-shirt thrower for this talk and try to get out of Sergei's way. </P> <P>It's been a while since I went to PDC, should be fun! I'm told Oleg from <A href="">Ivolva</A> will be there too. Is it a coincidence that both he and Sergei have the same last name? Perhaps, but I better brush up on my Russian!</P> <P>The PDC sessions list is finally up: <A href=""></A></P> <P>Sergei and I will also plan to stick around little bit longer if you want to have a deep dive on parts of the product. Drop me a line if you'll be at the conference, it'd be great to associate names with faces. </P> <P>later,</P> <P>ash</P><div style="clear:both;"></div><img src="" width="1" height="1">Ashvini Sharma [MSFT] SSIS webcast later today<P>At 1PM PST today, I'll be doing an MSDN Webcast on how to extend Integration Services including how to write new tasks and create new components. Why would you want to do that? Well, the simplest example would be if you have binary files that only you know how to read or have other existing business logic, you can integrate that with the product fairly easily. </P> <P>In our presentations, we've been talking about the fact that Integration Services is a change in mindset from DTS in that while DTS was a useful tool, SSIS is really a platform for enterprise level data integration. This presentation is where the rubber hits the road and we talk about how do you plug into the platform yourself.</P> <P>The webcast will be recorded for posterity. </P> <P><A href=""></A></P> <P>regards,</P> <P>ash</P> <P> </P><div style="clear:both;"></div><img src="" width="1" height="1">Ashvini Sharma [MSFT] Blog Location<P>Hi there, </P> <P>I'm a member of the SQL Server Integration Services team and previously had a blog here: <A href="">sqljunkies</A>. </P> <P>Last week I ran into issues posting there and thought I'd try out this site instead. Since I work to integrate technologies, getting blogs over from sqljunkies over to this site is a great problem to have. Of course since I'm lazy I want to use an existing tool to do that but haven't been able to find anything as yet. </P> <P>The first part of moving data is to get access to it. Since sqljunkies uses CommunityServer as does this site, and CommunityServer supports MetaWebLog so I should be all set, right? Sorry, no cigar. While MSDN has MetaWebLog API enabled, I haven't been able to find the URL for the sqljunkies service so here we are twiddling our thumbs. </P> <P>The other way to get data out would be to use RSS or Atom but that only goes back 4 months for sqljunkies. I want to get all the content! </P> <P>Hmm. </P> <P>That sent me down the path of googling my options and I ran into several blogging tools and technologies. </P> <P>Man, I've been out of it! w.bloggar seemed pretty good, and that's what I used for posting the first version of this blog. I was naive and didn't realize the editor was HTML, not wysiwyg. oh well. </P> <P>Well, no answer to the migration as yet. If you have any wisdom to share in this area, let me know. I would like to stay away from scraping HTML contents to get the content out. </P> <P>Regards,</P> <P>ash</P><div style="clear:both;"></div><img src="" width="1" height="1">Ashvini Sharma [MSFT]: Performance of incremental bulk insert<P>Bulk. </P> <P.</P> <P>Check <A href="">it</A> out! </P> <P><A href=""></A></P> <P> </P> <P> </P><div style="clear:both;"></div><img src="" width="1" height="1">Ashvini Sharma [MSFT]: Logging in pipeline components<DIV dir=ltr align=left><SPAN class=217314700-14072005><FONT face=Arial size=2><FONT color=#000000>Ethan from </FONT><A href=""><FONT color=#0000ff>AMB Dataminers</FONT></A><FONT color=#000000> had a great question about how to do logging through his pipeline </FONT></FONT></SPAN><SPAN class=217314700-14072005><FONT face=Arial color=#000000 size=2>component. </FONT></SPAN></DIV> <DIV><FONT face=Arial color=#000000 size=2></FONT> </DIV> <DIV dir=ltr align=left><FONT color=#000000><SPAN class=217314700-14072005><FONT face=Arial size=2>One way to do it is to call the Fire* methods that's on the IDTSComponentMetadata90. However, that </FONT></SPAN><SPAN class=217314700-14072005><FONT face=Arial size=2>does incur the cost of basically firing an event and handling an associated event handler. That's </FONT></SPAN><SPAN class=217314700-14072005><FONT face=Arial size=2>appropriate at times, while what's required at other times is the ability to just log something as </FONT></SPAN><SPAN class=217314700-14072005><FONT face=Arial size=2>quickly as you can. In addition, some situations call for such log entries to be separated from other </FONT></SPAN><SPAN class=217314700-14072005><FONT face=Arial size=2>log entries that other components might raise. I.e. the OnInformation log event can be pretty chatty, </FONT></SPAN><SPAN class=217314700-14072005><FONT face=Arial size=2>and might not be necessarily what you might want to force the user to use and get a plethora of other </FONT></SPAN><SPAN class=217314700-14072005><FONT face=Arial size=2>events they might not be interested in.</FONT></SPAN></FONT></DIV> <DIV><FONT face=Arial color=#000000 size=2></FONT> </DIV> <DIV dir=ltr align=left><FONT color=#000000><SPAN class=217314700-14072005><FONT face=Arial size=2>So, here's another way to do logging in the components, thanks to Ted and Matt with their help in </FONT></SPAN><SPAN class=217314700-14072005><FONT face=Arial size=2>this investigation! </FONT></SPAN></FONT></DIV> <DIV><FONT face=Arial color=#000000 size=2></FONT> </DIV> <DIV dir=ltr align=left><FONT color=#000000><SPAN class=217314700-14072005><FONT face=Arial size=2>IDTSComponentMetadata90 also exposes another method (in addition to the Fire* ones) called </FONT></SPAN><SPAN class=217314700-14072005><FONT face=Arial size=2>PostLogMessage.</FONT></SPAN></FONT></DIV> <DIV><FONT face=Arial color=#000000 size=2></FONT> </DIV> <DIV dir=ltr align=left><SPAN class=217314700-14072005><FONT face=Arial color=#000000 size=2>Here's the steps for this route: </FONT></SPAN></DIV> <DIV dir=ltr align=left><SPAN class=217314700-14072005><FONT face=Arial color=#000000 size=2><BR>1. Register your log entry with the runtime environments so that it's available as a log entry in the </FONT></SPAN><SPAN class=217314700-14072005><FONT face=Arial color=#000000 size=2>logging dialog for the pipeline task. <BR>2. Add your log entry! </FONT></SPAN></DIV> <DIV><FONT face=Arial color=#000000 size=2></FONT> </DIV> <DIV dir=ltr align=left><FONT color=#000000><SPAN class=217314700-14072005><FONT face=Arial size=2>As an example of doing this, lets add a log entry that will describe the SQL statement used by the </FONT></SPAN><SPAN class=217314700-14072005><FONT face=Arial size=2>ADOSource sample component that gets installed by Setup.</FONT></SPAN></FONT></DIV> <DIV><FONT face=Arial color=#000000 size=2></FONT> </DIV><SPAN class=217314700-14072005><FONT face=Arial> <DIV dir=ltr align=left><BR><FONT color=#000000 size=2><STRONG>Registering log entries</STRONG></FONT></DIV> <DIV><FONT color=#000000 size=2></FONT> </DIV> <DIV dir=ltr align=left><FONT color=#000000 size=2>In the component, I define a couple of consts: </FONT></DIV> <DIV><FONT color=#000000 size=2></FONT> </DIV> <DIV dir=ltr align=left><FONT face="Courier New" color=#000000 size=2>private const stringDTSLogEntryFrequency</FONT> provides a hint to the runtime about how frequently will the event be logged: </FONT></FONT></DIV> <DIV><FONT color=#000000 size=2></FONT> </DIV> <DIV dir=ltr align=left><FONT size=2><FONT color=#000000><FONT face="Courier New">DTSLEF_OCCASIONAL</FONT>: only sometimes, not during every execution<BR><FONT face="Courier New">DTSLEF_CONSISTENT</FONT>: constant number of times during every execution<BR><FONT face="Courier New">DTSLEF_PROPORTIONAL</FONT>: proportional to amount of work completed</FONT></FONT></DIV> <DIV><FONT color=#000000 size=2></FONT> </DIV> <DIV dir=ltr align=left><FONT color=#000000 size=2>The call above, then, creates a log entry with the name and description we want. I'll be logging once per execution, so am using <FONT face="Courier New">DTSLEF_CONSISTENT</FONT>.</FONT></DIV> <DIV><FONT color=#000000 size=2></FONT> </DIV> <DIV dir=ltr align=left><FONT color=#000000 size=2>This magically means that when I add a new component to the pipeline task, the 'Logging' dialog in the designer shows a new log entry now available for the pipeline task with the name "AdoNet Source Log Entry". Cool! </FONT></DIV> <DIV><FONT color=#000000 size=2></FONT> </DIV> <DIV dir=ltr align=left><FONT color=#000000 size=2><STRONG>Logging</STRONG></FONT></DIV> <DIV><FONT color=#000000 size=2></FONT> </DIV> <DIV dir=ltr align=left><FONT color=#000000 size=2>Now time to create the log entry. In this case, I just want to log the SQL statement that'll be used, and see that the existing code gets this statement in PreExecute. So, the following go at the end of that function: </FONT></DIV> <DIV><FONT color=#000000 size=2></FONT> </DIV> <DIV dir=ltr align=left><FONT face="Courier New" color=#000000 size=2>DateTime now = DateTime.Now;<BR>byte[] additionalData = null;<BR>ComponentMetaData.PostLogMessage(MyLogEntryName, ComponentMetaData.Name, "Command Sent was: " + oledbCommand.CommandText, now, now, 0, ref additionalData);</FONT></DIV> <DIV><FONT color=#000000 size=2></FONT> </DIV><FONT size=2></FONT><FONT size=2></FONT> <DIV dir=ltr align=left><BR><FONT color=#000000 size=2><STRONG>Testing</STRONG></FONT></DIV> <DIV dir=ltr align=left><FONT size=2><STRONG></STRONG><BR><FONT color=#000000>After registering the component, I configure the statement in the source to be 'select * from INFORMATION_SCHEMA.TABLES', ask this log event to go to a file, and get the following: </FONT></FONT></DIV> <DIV><FONT color=#000000 size=2></FONT> </DIV> <DIV dir=ltr align=left><FONT color=#000000 size=2><EM</EM></FONT></DIV> <DIV><FONT color=#000000 size=2></FONT> </DIV> <DIV dir=ltr align=left><FONT color=#000000 size=2>Hope this helps, thanks again, Ethan, for asking such an interesting question! </FONT></DIV> <DIV><FONT color=#000000 size=2></FONT> </DIV> <DIV dir=ltr align=left><FONT color=#000000 size=2>regards,<BR>ash</FONT></DIV></FONT></SPAN><div style="clear:both;"></div><img src="" width="1" height="1">Ashvini Sharma [MSFT] | http://blogs.msdn.com/b/ashvinis/atom.aspx | CC-MAIN-2013-48 | refinedweb | 5,054 | 60.35 |
Create artificial dataset
- sklearn dataset module:
from sklearn import datasets. This contains also some popular reference datasets.
Source of datasets
- Google Dataset Search.
- Google Trends Datastore
- Google AI Datasets — In order to contribute to the broader research community, Google periodically releases data of interest to researchers in a wide range of computer science disciplines.
- Data Hub Datasets collection — high quality data and datasets organized by topic.
- Kaggle Datasets.
- awesome-public-datasets — A topic-centric list of HQ open datasets.
- Stanford Large Network Dataset Collection.
- FiveThirtyEight — hard data and statistical analysis to tell stories about politics, sports, societal matters and more.
- data.world.
- BuzzFeedNews/everything — data from BuzzFeed.
- data.gov — a large dataset aggregator and the home of the US Government’s open data.
- Quandl — your perfect choice for testing your machine learning algorithms and don’t waste your time on cleaning data.
- r/datasets.
- Built-in datasets in Scikit-Learn.
- NLP-progress.
Datasets
- WordNet – A Lexical Database for English.
- ImageNet – ImageNet is an image database organized according to the WordNet hierarchy.
- Fruit-Images-Dataset — A dataset of images containing fruits and vegetables.
- Dataset samples from Machine Learning Mastery.
Vietnamese
- PhoBERT: Pre-trained language models for Vietnamese.
- IWSLT’15 English-Vietnamese data (small from Stanford).
- NLP-progress - Vietnamese
Sample datasets
- Labeled Faces in the Wild Home (
from sklearn.datasets import fetch_lfw_people).
- Iris flower dataset (
from sklearn.datasets import load_iris).
- The digits dataset (
sklearn.datasets.load_digits). | https://dinhanhthi.com/dataset-collection | CC-MAIN-2020-29 | refinedweb | 234 | 53.68 |
How I can get some specific data out of NURBS solids drawn in Rhino in a .txt Format? Data like coordinates of control Points, their respective weights and knot vectors.
Finding from the earlier question, I can get some data out of NURBS curves and surfaces.
How to get data out of NURBS curves in Rhino
For example, to get the data of NURBS surface, the following code can be used:
import Rhino
import System.Guid
import scriptcontext
import rhinoscriptsyntax as rs
surface=rs.GetObject(“Select”,rs.filter.surface)
print ‘NURBS Data’
if rs.IsSurface(surface):
points = rs.SurfacePoints(surface)
weights = rs.SurfaceWeights(surface)
knots = rs.SurfaceKnots(surface)
print points
print weights
print knots
print ‘Done’
Please let me know if anyone knows how to get this. Thank you. | https://discourse.mcneel.com/t/how-to-get-data-out-of-nurbs-solids-in-rhino/107267 | CC-MAIN-2020-40 | refinedweb | 129 | 59.9 |
LLDB API Documentation
#include <SBLaunchInfo.h>
Definition at line 20 of file SBLaunchInfo.h.
Get the listener that will be used to receive process events.
If no listener has been set via a call to SBLaunchInfo::SetListener(), then an invalid SBListener will be returned (SBListener::IsValid() will return false). If a listener has been set, then the valid listener object will be returned.
Set the executable file that will be used to launch the process and optionally set it as the first argument in the argument vector.
This only needs to be specified if clients wish to carefully control the exact path will be used to launch a binary. If you create a target with a symlink, that symlink will get resolved in the target and the resolved path will get used to launch the process. Calling this function can help you still launch your process using the path of your choice.
If this function is not called prior to launching with SBTarget::Launch(...), the target will use the resolved executable path that was used to create the target.
Set the listener that will be used to receive process events.
By default the SBDebugger, which has a listener, that the SBTarget belongs to will listen for the process events. Calling this function allows a different listener to be used to listen for process events.
Definition at line 141 of file SBLaunchInfo.h.
Definition at line 142 of file SBLaunchInfo.h.
Definition at line 148 of file SBLaunchInfo.h. | http://lldb.llvm.org/cpp_reference/html/classlldb_1_1SBLaunchInfo.html | CC-MAIN-2018-26 | refinedweb | 248 | 65.62 |
Due by 11:59pm on Tuesday, 4/8
Submission. See the online submission instructions. We have provided a hw7.py starter file for the questions below.
Readings. Section 2.7 and 2.8 of Composing Programs.
Introduction. This assignment is officially due in three weeks, because of the upcoming test and spring break. However, you may find some of the material useful in preparing for the test, so we suggest that you complete a week ahead of time. We will run the autograder accordingly.
Q1. Write a class Amount that represents a collection of nickels and pennies. Include a property method called value that computes the total monetary value of the amount from the nickels and pennies.
Do not add an instance attribute called value to each Amount instance. Instead, an Amount should have only two instance attributes: nickels and pennies. You do not need to support direct assignment to value. (You are welcome to add that feature as well; see the relevant Python Property docs).
Finally, write a subclass MinimalAmount with base class Amount that overrides the constructor so that all amounts are minimal upon construction. An Amount instance is minimal if it has no more than four pennies, but the same value as the nickel and penny quantities passed as arguments:
class Amount(object): """An amount of nickels and pennies. >>> a = Amount(3, 7) >>> a.nickels 3 >>> a.pennies 7 >>> a.value 22 >>> a.nickels = 5 >>> a.value 32 """ "*** YOUR CODE HERE ***" class MinimalAmount(Amount): """An amount of nickels and pennies that is initialized with no more than four pennies, by converting excess pennies to nickels. >>> a = MinimalAmount(3, 7) >>> a.nickels 4 >>> a.pennies 2 >>> a.value 22 """ "*** YOUR CODE HERE ***"
Q2. Section 2.8.4 of the online textbook and slide 20 of Lecture 17 describe one way to get data-directed programming, in which the data "decide" how any particular method is to be handled.
Write a data-directed apply function that computes the area or perimeter of either a square or a rectangle. As suggested in the readings, use a dictionary to store the implementations of each function for each type:
class Square(object): def __init__(self, side): self.side = side class Rect(object): def __init__(self, width, height): self.width = width self.height = height def apply(operator_name, shape): """Apply operator to shape. >>> apply('area', Square(10)) 100 >>> apply('perimeter', Square(5)) 20 >>> apply('area', Rect(5, 10)) 50 >>> apply('perimeter', Rect(2, 4)) 12 """ "*** YOUR CODE HERE ***"
Q3. In lecture, we talked about using binary search trees to implement sets of values, but one could also use various kinds of sequence to do the job, such as the rlist type from earlier in the semester, here recast as a class:
class Rlist: """A recursive list consisting of a first element and the rest. >>> s = Rlist(1, Rlist(2, Rlist(3))) >>> s.rest Rlist(2, Rlist(3)) >>> len(s) 3 >>> s[1] 2 """ class EmptyList: def __len__(self): return 0 def __repr__(self): return "Rlist.empty" empty = EmptyList() def __init__(self, first, rest=empty): assert type(rest) is Rlist or rest is Rlist.empty self.first = first self.rest = rest def __getitem__(self, index): if index == 0: return self.first else: if self.rest is Rlist.empty: raise IndexError("Rlist index out of bounds") return self.rest[index-1] def __len__(self): return 1 + len(self.rest) def __repr__(self): """Return a string that would evaluate to s.""" if self.rest is Rlist.empty: rest = '' else: rest = ', ' + repr(self.rest) return 'Rlist({0}{1})'.format(self.first, rest)
Complete the following partial implementation of sets represented as sorted recursive lists by filling in definitions for rlist_adjoin, drlist_adjoin, rlist_intersect and rlist_union. All of these functions should take Θ(n) time, where n is the size of the input list(s):
class rlist_set: """A set of arbitrary items that have an ordering (i.e., that define <=, <, and other relational operations between them).""" # Representation: rlist_sets are represented by Rlists of items # maintained in sorted order. def __init__(self, *initial_items): """A set that initially contains the values in INITIAL_ITEMS, which can be any iterable.""" self._s = Rlist.empty for v in initial_items: self.add(v) @staticmethod def _make_set(r): """An internal method for creating rlist_sets out of rlists.""" result = rlist_set() result._s = r return result def as_rlist(self): """An Rlist of my values in sorted order. This Rlist must not be modified.""" return self._s def empty(self): return self._s is Rlist.empty def __contains__(self, v): """True iff I currently contain the value V. >>> s = rlist_set(3, 8, 7, 1) >>> s.__contains__(7) True >>> 7 in s # __contains__ defines 'in' True >>> 9 in s False""" if self.empty() or self._s.first > v: return False elif self._s.first == v: return True else: return v in self._s.rest def __repr__(self): result = "{" s = self._s while s is not Rlist.empty: if result != "{": result += ", " result += repr(s.first) s = s.rest return result + "}" def intersection(self, other_set): """Return a set containing all elements common to rlist_sets SELF and OTHER_SET. >>> s = rlist_set(1, 2, 3) >>> t = rlist_set(2, 3, 4) >>> s.intersection(t) {2, 3} """ return rlist_set._make_set(rlist_intersect(self._s, other_set._s)) def adjoin(self, v): """Return a set containing all elements of s and element v. >>> s = rlist_set(1, 2, 3) >>> s.adjoin(2.5) {1, 2, 2.5, 3} >>> s.adjoin(0.5) {0.5, 1, 2, 3} >>> s.adjoin(3) {1, 2, 3} """ return rlist_set._make_set(rlist_adjoin(self._s, v)) def add(self, v): """Destructively changes me to the result of adjoining V, returning the modified set.""" self._s = drlist_adjoin(self._s, v) def union(self, other_set): """Return a set containing all elements either in myself or OTHER_SET. >>> s0 = rlist_set(2, 3) >>> s = s0.adjoin(1) >>> t0 = rlist_set(3, 5) >>> t = t0.adjoin(1) >>> s.union(t) {1, 2, 3, 5} >>> s0.union(t) {1, 2, 3, 5} >>> rlist_set().union(s0.intersection(t)) {3} """ return rlist_set._make_set(rlist_union(self._s, other_set._s)) def rlist_adjoin(s, v): """Assuming S is an Rlist in sorted order, a new Rlist that contains all the original values, plus V (if not already present) in sorted order.""" "*** YOUR CODE HERE ***" def drlist_adjoin(s, v): """Destructively add V to the appropriate place in sorted Rlist S, if it is not already present, returning the modified Rlist.""" "*** YOUR CODE HERE ***" def rlist_intersect(s1, s2): """Assuming S1 and S2 are two Rlists in sorted order, return a new Rlist in sorted order containing exactly the values both have in common, in sorted order.""" "*** YOUR CODE HERE ***" def rlist_union(s1, s2): """Assuming S1 and S2 are two Rlists in sorted order, return a new Rlist in sorted order containing the union of the values in both, in sorted order.""" "*** YOUR CODE HERE ***"
Q4. Complete the following, somewhat more direct version of the BinTree type from lecture by filling in the inorder_tree_iter class at the end:
class BinTree: """A binary tree.""" def __init__(self, label, left=None, right=None): """The binary tree node with given LABEL, whose left and right children are BinTrees LEFT and RIGHT, which default to the empty tree.""" self._label = label self._left = left or BinTree.empty self._right = right or BinTree.empty @property def is_empty(self): """This tree contains no labels or children.""" return self is BinTree.empty @property def label(self): return self._label @property def left(self): return self._left @property def right(self): return self._right def set_left(self, newval): """Assuming NEWVAL is a BinTree, sets SELF.left to NEWVAL.""" assert isinstance(newval, BinTree) self._left = newval def set_right(self, newval): """Assuming NEWVAL is a BinTree, sets SELF.right to NEWVAL.""" assert isinstance(newval, BinTree) self._right = newval def inorder_values(self): """An iterator over my labels in inorder (left tree labels, recursively, then my label, then right tree labels). >>> T = BinTree(10, BinTree(5, BinTree(2), BinTree(6)), BinTree(15)) >>> for v in T.inorder_values(): ... print(v, end=" ") 2 5 6 10 15 """ return inorder_tree_iter(self) # A placeholder, initialized right after the class. empty = None def __repr__(self): if self.is_empty: return "BinTree.empty" else: args = repr(self.label) if not self.left.is_empty or not self.right.is_empty: args += ', {0}, {1}'.format(repr(self.left), repr(self.right)) return 'BinTree({0})'.format(args) class EmptyBinTree(BinTree): """Represents the empty tree. There should only be one of these.""" def __init__(self): pass @property def is_empty(self): return True @property def label(self): raise NotImplemented @property def left(self): raise NotImplemented @property def right(self): raise NotImplemented def set_left(self, newval): raise NotImplemented def set_right(self, newval): raise NotImplemented # Set the empty BinTree (we could only do this after defining EmptyBinTree BinTree.empty = EmptyBinTree() class inorder_tree_iter: def __init__(self, the_tree): self._work_queue = [ the_tree ] def __next__(self): while len(self._work_queue) > 0: subtree_or_label = self._work_queue.pop() "*** YOUR CODE HERE ***" raise StopIteration def __iter__(self): return self
Notes: (1) As is common practice, we add and remove items from the end of _work_queue rather than the beginning. (2) Since BinTrees can also be EmptyBinTrees, use the built-in isinstance function to test whether something is a BinTree. See, for example, the set_left method.
Q5. Here is an implementation of sets using BinTree from the preceding problem:
class bintree_set: """A set of arbitrary items that have an ordering (i.e., that define <=, <, and other relational operations between them).""" # Representation: bintree_sets are represented by BinTrees used as binary search trees. def __init__(self, *initial_items): """A set that initially contains the values in INITIAL_ITEMS, which can be any iterable.""" self._s = BinTree.empty for v in initial_items: self.add(v) def __repr__(self): return "{" + ", ".join(map(repr, self._s.inorder_values())) + "}" def __contains__(self, v): """True iff I currently contain the value V. >>> s = bintree_set(3, 8, 7, 1) >>> s.__contains__(7) True >>> 7 in s # __contains__ defines 'in' True >>> 9 in s False""" s = self._s while not s is BinTree.empty and s._label != v: if v < s._label: s = s.left else: s = s.right return not s.is_empty @staticmethod def _make_set(b): """An internal method for creating a bintree_set out of bintree B.""" result = bintree_set() result._s = b return result def adjoin(self, v): """Return a set containing all elements of s and element v.""" def tree_add(T, x): if T.is_empty: return BinTree(x) elif x == T.label: return T elif x < T.label: return BinTree(T.label, tree_add(T.left, x), T.right) else: return BinTree(T.label, T.left, tree_add(T.right, x)) return bintree_set._make_set(tree_add(self._s, v)) def add(self, v): """Destructively adjoin V to my values, returning modified set.""" def dtree_add(T, x): if T.is_empty: return BinTree(x) elif x == T.label: return T elif x < T.label: T.set_left(dtree_add(T.left, x)) return T else: T.set_right(dtree_add(T.right, x)) return T self._s = dtree_add(self._s, v) return self def intersection(self, other_set): """Return a set containing all elements common to bintree_sets SELF and OTHER_SET. >>> s = bintree_set(1, 2, 3) >>> t = bintree_set(2, 3, 4) >>> s.intersection(t) {2, 3} """ list1 = rlist_set(*self._s.inorder_values()).as_rlist() list2 = rlist_set(*other_set._s.inorder_values()).as_rlist() return bintree_set._make_set(ordered_sequence_to_tree(rlist_intersect(list1, list2))) def union(self, other_set): """Return a set containing all elements either in myself or OTHER_SET. >>> s0 = bintree_set(2, 3) >>> s = s0.adjoin(1) >>> t0 = bintree_set(3, 5) >>> t = t0.adjoin(1) >>> s.union(t) {1, 2, 3, 5} >>> s0.union(t) {1, 2, 3, 5} >>> bintree_set().union(s0.intersection(t)) {3}""" list1 = rlist_set(*self._s.inorder_values()).as_rlist() list2 = rlist_set(*other_set._s.inorder_values()).as_rlist() return bintree_set._make_set(ordered_sequence_to_tree(rlist_union(list1, list2)))
Unlike the simple intersection done in lecture, we'd like the results of union and intersection to be "bushy". In order to complete the coercion from an ordered sequence set to a tree set, implement partial_sequence_to_tree below. If you can, implement the function to run in Θ(n) time in the length of the input list.
Hint: This function requires two recursive calls. The first call builds a left child out of the first left_size elements of s; Then, the next element is used as the label of the returned tree. Finally, the second recursive call builds the right child out of the next right_size elements. In total, (left_size + 1 + right_size) = n, where 1 is for the label:
def partial_sequence_to_tree(s, n): """Return a tuple (b, r), where b is a tree of the first N elements of Rlist S, and r is the Rlist of the remaining elements of S. A tree is balanced if (a) the number of entries in its left branch differs from the number of entries in its right branch by at most 1, and (b) its non-empty branches are also balanced trees. Examples of balanced trees: Tree(1) # branch difference 0 - 0 = 0 Tree(1, Tree(2), None) # branch difference 1 - 0 = 1 Tree(1, None, Tree(2)) # branch difference 0 - 1 = -1 Tree(1, Tree(2), Tree(3)) # branch difference 1 - 1 = 0 Examples of unbalanced trees: BinTree(1, BinTree(2, BinTree(3)), None) # branch difference 2 - 0 = 2 BinTree(1, BinTree(2, BinTree(3), None), BinTree(4, BinTree(5, BinTree(6), None), None)) # Unbalanced right branch >>> s = Rlist(1, Rlist(2, Rlist(3, Rlist(4, Rlist(5))))) >>> partial_sequence_to_tree(s, 3) (BinTree(2, BinTree(1), BinTree(3)), Rlist(4, Rlist(5))) >>> t = Rlist(-2, Rlist(-1, Rlist(0, s))) >>> partial_sequence_to_tree(t, 7)[0] BinTree(1, BinTree(-1, BinTree(-2), BinTree(0)), BinTree(3, BinTree(2), BinTree(4))) >>> partial_sequence_to_tree(t, 7)[1] Rlist(5) """ if n == 0: return BinTree.empty, s left_size = (n-1)//2 right_size = n - left_size - 1 "*** YOUR CODE HERE ***" def ordered_sequence_to_tree(s): """Return a balanced tree containing the elements of ordered Rlist s. Note: this implementation is complete, but the definition of partial_sequence_to_tree above is not complete. >>> ordered_sequence_to_tree(Rlist(1, Rlist(2, Rlist(3)))) BinTree(2, BinTree(1), BinTree(3)) >>> b = rlist_set(*range(1, 20, 3)) >>> elements = b.as_rlist() >>> elements Rlist(1, Rlist(4, Rlist(7, Rlist(10, Rlist(13, Rlist(16, Rlist(19))))))) >>> ordered_sequence_to_tree(elements) BinTree(10, BinTree(4, BinTree(1), BinTree(7)), BinTree(16, BinTree(13), BinTree(19))) """ return partial_sequence_to_tree(s, len(s))[0]
Q6. Mario needs to jump over a sequence of Piranha plants, represented as a string of spaces (no plant) and P's (plant!). He only moves forward, and he can either step (move forward one space) or jump (move forward two spaces) from each position. How many different ways can Mario traverse a level without stepping or jumping into a Piranha plant? Assume that every level begins with a space (where Mario starts) and ends with a space (where Mario must end up):
def mario_number(level): """Return the number of ways that Mario can perform a sequence of steps or jumps to reach the end of the level without ever landing in a Piranha plant. Assume that every level begins and ends with a space. >>> mario_number(' P P ') # jump, jump 1 >>> mario_number(' P P ') # jump, jump, step 1 >>> mario_number(' P P ') # step, jump, jump 1 >>> mario_number(' P P ') # step, step, jump, jump or jump, jump, jump 2 >>> mario_number(' P PP ') # Mario cannot jump two plants 0 >>> mario_number(' ') # step, jump ; jump, step ; step, step, step 3 >>> mario_number(' P ') 9 >>> mario_number(' P P P P P P P P ') 180 """ "*** YOUR CODE HERE ***"
Q7. (Extra for experts) The Rlist class can represent lists with cycles. That is, a list may contain itself as a sublist.
>>> s = Rlist(1, Rlist(2, Rlist(3))) >>> s.rest.rest.rest = s >>> s[20] 3
Hint: The solution to B is short (less than 20 lines of code), but requires a clever idea. Try to discover the solution yourself before asking around:
def has_cycle(s): """Return whether Rlist s contains a cycle. >>> s = Rlist(1, Rlist(2, Rlist(3))) >>> s.rest.rest.rest = s >>> has_cycle(s) True >>> t = Rlist(1, Rlist(2, Rlist(3))) >>> has_cycle(t) False """ "*** YOUR CODE HERE ***" def has_cycle_constant(s): """Return whether Rlist s contains a cycle. >>> s = Rlist(1, Rlist(2, Rlist(3))) >>> s.rest.rest.rest = s >>> has_cycle_constant(s) True >>> t = Rlist(1, Rlist(2, Rlist(3))) >>> has_cycle_constant(t) False """ "*** YOUR CODE HERE ***" | https://inst.eecs.berkeley.edu/~cs61a/sp14/hw/hw7.html | CC-MAIN-2020-10 | refinedweb | 2,691 | 60.01 |
Mercurial > dropbear
view libtommath/bn_mp_dr_is_modulus.c @ 457:e430a26064ee DROPBEAR_0.50
Make dropbearkey only generate 1024 bit keys
line source
#include <tommath.h> #ifdef BN_MP_DR_IS_MODULUS a number is a valid DR modulus */ int mp_dr_is_modulus(mp_int *a) { int ix; /* must be at least two digits */ if (a->used < 2) { return 0; } /* must be of the form b**k - a [a <= b] so all * but the first digit must be equal to -1 (mod b). */ for (ix = 1; ix < a->used; ix++) { if (a->dp[ix] != MP_MASK) { return 0; } } return 1; } #endif /* $Source: /cvs/libtom/libtommath/bn_mp_dr_is_modulus.c,v $ */ /* $Revision: 1.3 $ */ /* $Date: 2006/03/31 14:18:44 $ */ | https://hg.ucc.asn.au/dropbear/file/e430a26064ee/libtommath/bn_mp_dr_is_modulus.c | CC-MAIN-2022-40 | refinedweb | 106 | 60.72 |
Attributes are a great resource that allows developers to put extra information on types and members.
They are great in the sense that we put all we need together and they are completely refactoring friendly, as when a member is renamed all its attributes stay there. But
sometimes (or should I say many times) that initial benefit ends up causing more
trouble than they really solve.
In Wikipedia I found this definition:
In object-oriented programming, the single responsibility principle states that every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.
Even if the idea is great, it does not really tell me when a class (or better, a type as we have structs too) has a single responsibility or not.
Let's see the int (System.Int32) type.
int
System.Int32
An int variable is a simple value holder. But the struct has methods to parse a string and return an int, to convert that int to a string, to compare an int with another, to do math operations, and so on. It is OK to me, but I can already say that it is a little counter intuitive that some math operations are in the int type itself while others are in the Math class.
Shouldn't methods like Math.Max be in the original types (int.Max, double.Max, and so on)?
string
Math
Math.Max
int.Max
double.Max
Well, maybe, but this article is not really to discuss that point. The point I want to discuss are attributes and how they violate the Single Responsibility Principle.
So, let's see some attribute usages:
[Serializable]
[DisplayName("Non-Empty String")]
[Description("This struct simple holds a string value, which must be null or have a non-empty content.")]
public struct NonEmptyString
{
public NonEmptyString(string value)
{
if (value.Length == 0)
throw new ArgumentException("value must be null or should have a non-empty content.", "value");
_value = value;
}
private readonly string _value;
[Description("This property should be null or have a non-empty content.")]
public string Value
{
get
{
return _value;
}
}
}
The struct was created with a single responsibility in mind (store a
non-empty string). You may not like the idea of creating a struct for such a simple validation, but that's not the point here. The point is its responsibility that was altered to:
[Serializable]
See the problem?
If not, I will tell you. The type should not be worried about the text description to be used by a possible editor. It should not care about a Serializable attribute. It is the responsibility of a serializer to know if it is serializable or not. It is the responsibility of an editor to know some way of finding a better name and description.
Serializable
Also, I can say that there are other problems, like, how do we support non-English descriptions with this model?
To make the code conform to the Single Responsibility Principle, it should look like this:
public struct NonEmptyString
{
public NonEmptyString(string value)
{
if (value.Length == 0)
throw new ArgumentException("value must be null or should have a non-empty content.", "value");
_value = value;
}
private readonly string _value;
public string Value
{
get
{
return _value;
}
}
}
That's OK from the Single Responsibility Principle idea. But then how do we solve the
[Serializable] thing? How can an editor find the right DisplayName and
Description?
DisplayName
Description
Well... that can be a little tricky with the old code. Surely we can create yet another type, like
SerializableNonEmptyString that holds a NonEmptyString and adds serialization support. But if we want to serialize an object that already holds a
NonEmptyString we will end-up needing to copy the object to a similar one with serializable types. So, for those cases, maybe it is better to violate the Single Responsibility Principle. Or if we have the option, we can recreate the serialization process (or use an alternative one) that allows us to add specific serialization code for already existing types.
SerializableNonEmptyString
NonEmptyString
Effectively, the idea is: Every type will have a single responsibility. So the NonEmptyString has the single responsibility of holding a string that is either null or non-empty. Then, a serializer type will know how to serialize a NonEmptyString. It is enough to inform a serialization mechanism that we have the serializer for such
a type.
In fact, with this model, any type that already exists on a third-party DLL can be serialized if it is possible to access all needed properties to store them and reconstruct (or find) the instance later. So, the data type can exist in an assembly and the serializer for it can exist in another assembly. I can say that I use that to serialize WPF colors, for example.
Well... I can say that a Dictionary<MemberInfo, string> will do the job. Surely
there should be some code available to load descriptions for MemberInfos, but with such
a dictionary we can
already bind a DisplayName or Description to any existing member (in fact, or we will have two different classes with a similar structure, or we should create another type to store the
DisplayName and the Description together).
Dictionary<MemberInfo, string>
MemberInfo
The best thing with this approach is that we can, again, do it in different assemblies. So, if we are dealing with 3rd party classes, we can still add a display name or a description to the types found there. With a little more work we can support different languages, and everything without changing the original types.
The sample code in this article is a small Binary Serialization library that works using the Single Responsibility Principle.
ConfigurableBinarySerializer must be configured (that is, the serializer for each item type must be added by the user). Also, there is a very small sample with it that only shows how to register the serializers, how to serialize and deserialize. If everything works
OK, the data is serialized to and deserialized from a memory stream, and the console application finishes. So, only use it to see the code.
ConfigurableBinarySerializer
I don't expect that people simple use this serializer as a replacement for normal serialization techniques, but I hope it gives a better understanding on the Single Responsibility Principle.
I already received two messages from people that say that attributes don't violate the Single Responsibility Principle. They in fact have valid points. But let's look from an outside view.
Someone (a user, a chef, another programmer) asks for a component that:
The programmer easily does something like this:
public class SomeClass
{
public int P1 { get; set; }
public int P2 { get; set; }
public int Sum
{
get
{
return P1 + P2;
}
}
public int Multiplication
{
get
{
return P1 * P2;
}
}
}
In fact, the code works. But then the developer receives a "warning" that his code is not right. The fact is:
But to him, that was not what was asked. You may consider him lazy, but he did what he was asked to do.
Is he really wrong?
My answer is no. Not because someone forgot to say that the class was serializable, but because the purpose of the class is to store data. Being serializable is another "trait" of such
a class... but it is better to put that trait somewhere else and let the one responsible for seeing what's serializable to say: Hey, that's a class that can be serialized without problems!
Don't put the need on the programmer that did the class. And, consequently, don't put that need in the class itself. If someone else, at a later time, can figure out that it's possible, allow that. That means: Allow that to be put at run-time, instead of only allowing that at compile-time. And that's where the real question is:
Are you using attributes as hints or are you using it as needs? As
hints, that may be a small violation. But as needs, that's. | http://www.codeproject.com/Articles/441707/Attributes-vs-Single-Responsibility-Principle?fid=1765929&df=90&mpp=10&sort=Position&spc=None&tid=4347375 | CC-MAIN-2016-26 | refinedweb | 1,338 | 54.42 |
Return to
howto.mdwn
CVS log
Up to
[NetBSD Developer Wiki]
/
wikisrc
/
ports
/
xen
Diff for /wikisrc/ports/xen/howto.mdwn between versions 1.32 and 1.106
version 1.32
, 2014/12/24 15:31:36
version 1.106
, 2016/12/20 04:01:34 fro NetBSD
7. Xen 2 has been removed from pkgsrc.
Prerequisites
Prerequisites
-------------
-------------
Line 63
architecture. This HOWTO presumes famil
Line 66 88
xenkernel and xentools. We will refer o
Line 82
xenkernel and xentools. We will refer o the last applied security patch was in
receive security patches and should not be used. Xen 3.1 supports PCI
2011. Thus, it should not be used. It supports PCI passthrough,
passthrough. Xen 3.1 supports non-PAE on i386.
which is why people use it anyway. Xen 3.1 supports i386, both PAE and
non-PAE.
xenkernel41 provides Xen 4.1. This is no longer maintained by Xen,
but as of 2014-12 receives backported security patches. It is a
xenkernel33 provides Xen 3.3. It is no longer maintained by Xen, and
reasonable although trailing-edge choice.-11 received backported security patches. Xen 4.1 supports
i386, but only in PAE mode. There are no good reasons to run this
version.
xenkernel42 provides Xen 4.2. It is no longer maintained by Xen, but
as of 2016-11. It is no longer maintained by Xen, but
as of 2016-11 it received security patches. Xen 4.5 requires an amd64
dom0, but domUs can be amd64 or i386 PAE. TODO: It is either a
conservative choice or somewhat old.
xenkernel45 provides Xen 4.6. It is new to pkgsrc in 2016-05. It is
no longer maintained by Xen, but as of 2016-11 it received security
patches. Xen 4.6 requires an amd64 dom0, but domUs can be amd64 or
i386 PAE. TODO: It is either a somewhat aggressive choice or the
standard choice
xenkernel42 provides Xen 4.2. This is maintained by Xen, but old as
See also the [Xen Security Advisory page]().
of 2014-12.
Ideally newer versions of Xen will be added to pkgsrc.
Ideally newer versions of Xen will be added to pkgsrc.
Note that NetBSD support is called XEN3. It works with 3.1 through
Note that NetBSD support is called XEN3. It works with Xen 3 and Xen
4.2 because the hypercall interface has been stable.
4. For those wanting to learn Xen or
learn Xen or without production stability concerns, netbsd-7 is likely
without production stability concerns, netbsd-7 is still likely most
most appropriate.
appropriate. Xen runs fine on netbsd-5, but the xentools packages are
likely difficult to build. (some versions) or amd64 machines (all.
be amd64.
One can then run i386 domUs and amd64 domUs, in any combination. If
Stability
running an i386 NetBSD kernel as a domU, the PAE version is required.
---------
(Note that emacs (at least) fails if run on i386 with PAE when built
without, and vice versa, presumably due to bugs in the undump code.) work or FAIL:
xenkernel3 netbsd-5 amd64
xentools3 netbsd-5 amd64
xentools3=hvm netbsd-5 amd64 ????
xenkernel33 netbsd-5 amd64
xentools33 netbsd-5 amd64
xenkernel41 netbsd-5 amd64
xentools41 netbsd-5 amd64
xenkernel42 netbsd-5 amd64
xentools42 netbsd-5 amd64
xenkernel3 netbsd-6 i386 FAIL
xentools3 netbsd-6 i386
xentools3-hvm netbsd-6 i386 FAIL (dependencies fail)
xenkernel33 netbsd-6 i386
xentools33 netbsd-6 i386
xenkernel41 netbsd-6 i386
xentools41 netbsd-6 i386
xenkernel42 netbsd-6 i386
xentools42 netbsd-6 i386 *MIXED
(all 3 and 33 seem to FAIL)
xenkernel41 netbsd-7 i386
xentools41 netbsd-7 i386
xenkernel42 netbsd-7 i386
xentools42 netbsd-7 i386 ??FAIL
(*On netbsd-6 i386, there is a xentools42 in the 2014Q3 official builds,
but it does not build for gdt.)
NetBSD as a dom0
NetBSD as a dom0
================
================
Line 163
NetBSD, which is not yet a dom0, and the
Line 246 176
dom0 is what the computer would have bee
Line 263 199
over a RAID1 header to find /boot from a
Line 288
over a RAID1 header to find /boot from a 238
For debugging, one may copy xen-debug.gz
Line 327 comunicate with the
In a dom0 kernel, kernfs is mandatory for xend to comunicate with the
kernel, so ensure that /kern is in fstab. filesystem, /boot present, and likely
tham 389
boot.) 3.3 (and thus xm), add to rc.conf (but note that you should have
For "xm" (3.1 and 3.3), you should enable xend and xenbackendd (but
installed 4.1 or 4.2):
note that you should be using 4.x):
xend=YES
xend=YES
xenbackendd=YES
xenbackendd=YES
For 4.1 (and thus xm), add to rc.conf:
For "xl" (4.x), you should enabled xend and xencommons (xenstored).
Trying to boot 4.x without xencommons=YES will result in a hang; it is
necessary to hig ^C on the console to let the machine finish booting.
TODO: explain why xend is installed by the package.
xend=YES
xencommons=YES
xencommons=YES
TODO: Explain why if xm is preferred on 4.1, rc.d/xendomains has xl.
The installation of NetBSD should already have created devices for xen
(xencons, xenevt), but if they are not present, create them:
For 4.2 with xl, add to rc.conf:
cd /dev && sh MAKEDEV xen
TODO: explain if there is a xend replacement
xencommons=YES
TODO: Recommend for/against xen-watchdog. 4
Updating Xen is conceptually not difficult, but can run into all the
Line 323
issues found when installing Xen. Assum
Line 527
issues found when installing Xen. Assum
remove the xenkernel41 and xentools41 packages and install the
remove the xenkernel41 and xentools41 packages and install the
xenkernel42 and xentools42 packages. Copy the 4.2 xen.gz to /.
xenkernel42 and xentools42 packages. Copy the 4.2 xen.gz to /.
Ensure that the contents of /etc/rc.d/xen* are correct. Enable the
Ensure that the contents of /etc/rc.d/xen* are correct. Specifically,
correct set of daemons. Ensure that the domU config files are valid
they must match the package you just installed and not be left over
for the new version.
from some previous installation.
Enable the correct set of daemons; see the configuring section above.
(Upgrading from 3.x to 4.x without doing this will result in a hang.)
Ensure that the domU config files are valid for the new version.
Specifically:
------------
Provided Resources for PV domains
--------------
TODO: Explain that domUs get cpu, memory, disk and network.
A domain is provided with some number of vcpus, less than the number
Explain that randomness can be an issue.
------------
TODO: give example config files. Use both lvm and vnd.
Sizing domains
--------------
TODO: explain the mess with 3 arguments for disks and how to cope (0x1). scripth
on 4.1.
usd
# Set the kernel command line for the new domain.
empty. One approach is to unpack sets onto the disk outside of xen
(by mounting it, just as you would prepare a physical disk for a
system you can't run the installer on).
# Set root device. This one does matter for NetBSD
A second approach is to run an INSTALL kernel, which has a miniroot
root = "xbd0"
and can load sets from the network. To do this, copy the INSTALL
# extra parameters passed to the kernel
kernel to / and change the kernel line in the config file to:
# 852
filesystem. 662
the example below)
Line 877 912
busses will attach. Then the PCI drivers will attach to PCI busses:
include "arch/i386/conf/XEN3_DOMU"
#include "arch/i386/conf/XENU" # in NetBSD 3.0
# Add support for PCI busses to the XEN3_DOMU kernel
NetBSD as a domU in a VPS
xpci* at xenbus ?
=========================
pci* at xpci ?
# Now add PCI and related devices to be used by this domain
The bulk of the HOWTO is about using NetBSD as a dom0 on your own
# USB Controller and Devices.
# PCI USB controllers
VPS operators provide varying degrees of access and mechanisms for
uhci* at pci? dev ? function ? # Universal Host Controller (Intel)
configuration. The big issue is usually how one controls which kernel
is booted, because the kernel is nominally in the dom0. bus support
pygrub
usb* at uhci?
-------
# USB Hubs
pygrub runs in the dom0 and looks into the domU filesystem. This
uhub* at usb?
implies that the domU must have a kernel in a filesystem in a format
uhub* at uhub? port ? configuration ? interface ?
known to pygrub. As of 2014, pygrub seems to be of mostly historical
interest.
# USB Mass Storage
pvgrub
umass* at uhub? port ? configuration ? interface ?
------
wd* at umass?
# SCSI controllers
ahc* at pci? dev ? function ? # Adaptec [23]94x, aic78x0 SCSI
# SCSI bus support (for both ahc and umass)
pvgrub is a version of grub that uses PV operations instead of BIOS
scsibus* at scsi?
calls. It is booted from the dom0 as the domU kernel, and then reads
/grub/menu.lst and loads a kernel from the domU filesystem.
partiion.
# SCSI devices
Amazon
sd* at scsibus? target ? lun ? # SCSI disk drives
------
cd* at scsibus? target ? lun ? # SCSI CD-ROM drives
See the [Amazon EC2 page](../amazon_ec2/).
NetBSD as a domU in a VPS
Using npf
=========================
---------
The bulk of the HOWTO is about using NetBSD as a dom0 on your own
In standard kernels, npf is a module, and thus cannot be loaded in a
hardware. This section explains how to deal with Xen in a domU as a
DOMU kernel.
virtual private server where you do not control or have access to the
dom0. filesystem
===============
TODO: Perhaps reference panix, prmgr, amazon as interesting examples.
TODO: This section contains links from elsewhere not yet integrated
into the HOWTO.
TODO: Somewhere, discuss pvgrub and py-grub to load the domU kernel
*
from the domU filesystem.
*
Diff format:
Colored
Long colored
Unified
Context
Side by side
Removed from v.1.32
changed lines
Added in v.1.106
CVSweb for NetBSD wikisrc <
wikimaster@NetBSD.org
> software: FreeBSD-CVSweb | https://wiki.netbsd.org/cgi-bin/cvsweb/wikisrc/ports/xen/howto.mdwn.diff?r1=1.32;r2=1.106;f=h | CC-MAIN-2020-05 | refinedweb | 1,669 | 68.36 |
Introduction
This tutorial will go through some common ways for removing elements from Python arrays. Here's a list of all the techniques and methods we'll cover in this article:
Arrays in Python
Arrays and lists are not the same thing in Python. Although lists are more commonly used than arrays, the latter still have their use cases. The main difference between the two is that lists can be used to store arbitrary values. They are also heterogeneous which means they can simultaneously store integers, strings, other objects, etc.
Arrays, on the other hand, are similar to what arrays are in C. They are homogeneous data structures for storing elements of the same type and they use much less memory than lists.
This tutorial will focus on arrays, instead of lists, although most of the techniques shown in this tutorial can be used on both of these two data structures.
Using remove()
Appropriately, the
remove() function can be used on any array in Python. To use it, we can simply pass the value of the element we want to remove.()
The
pop() function accepts the index of the element we want to remove. If we had the same array as before (with values from 10 to 100), we could write something like the following:
index = 3 array.pop(index)
If we printed the result of the pop method, it would be the value
40:
[10, 20, 30, 50, 60, 70, 80, 90, 100]
Similarly to how
pop() works in the stack data structure, here
pop() also returns the value that it had just removed.
The only difference is that with arrays, we can remove an arbitrary element. With stacks, only the top element (i.e. the last one added) can ever be removed.
Using del
del is a python keyword used for deleting objects. Its exact behavior changes depending on the context, so we can also use it to remove array elements. Once again, let's take the same array and index as before:
array = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] index = 3
To remove the element at index
3, we simply type the following:
del array[index]
If we now printed the contents of our array, we would get the following output:
[10, 20, 30, 50, 60, 70, 80, 90, 100]
Using numpy Arrays
NumPy arrays are technically also arrays, and since they are commonly used (especially in machine learning), let's show one of the ways to remove an element from a
numpy array. Before using
numpy, it is necessary to import it with
import numpy as np
To create a
numpy array, we can wrap our current array using
np.array() as such:
a = np.array(array)
Alternatively, we could also declare a new array inside the method call itself:
a = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
Now to remove an element at index
3, we use the following code:
index = 3 a = np.delete(a, index)
delete() is a static method declared in the
numpy module. It accepts the array and the index of the element to remove.
The method returns a new array without the removed element:
[10, 20, 30, 50, 60, 70, 80, 90, 100]
Conclusion
There are different ways to remove an array element in Python. Sometimes we might want to remove an element by index and sometimes by value. Sometimes we're using Python's default array and sometimes a
numpy array.
In all these cases, it's good to have multiple options to help us decide which of the techniques to use. | https://stackabuse.com/remove-element-from-an-array-in-python/ | CC-MAIN-2021-10 | refinedweb | 602 | 67.99 |
Correlation based off a value in Request Body
I need some assistance with this issue. A teammate is trying to set up a responder correlation based off a value incoming from the request service. The issue is that this value is within the element and I need to set up correlation based on that specific value / id within.
The section of the request body contains that value:
<SearchRequest><EdgeLookUp><ANINo>XXXXX123</ANINo></EdgeLookUp></SearchRequest>
With XXXXX123 being the value I need to the correlation based on.
I have the following Javascript custom assertion applied to the responder:
function ANINo(input)
{
if(input.toString().contains("XXXXX123")){
return true;
}
else{
return false;
}
}
However, this does not work properly and does not accept the incoming request.
Is there anything I need to change my code in order to detect this value in that element, or would this more so involve XPath manipulation and request correlation?
Hi,
Have you considered using the Request Body correlation? Here is a link to the documentation for it
The body correlation has UI to help select and extract values from an XML payload so I would recommend using the body correlation if possible.
Is there a reason this cause would not be able to use the body correlation?0
-
Hi,
Yes, I saw a notification for the missing comment but it was gone before I could read it.0
So I think what is going on is either a format issue with the request or with the Parasoft Forums.
The code contains HTML code for greater than and less than symbols: "> ;" and "< ;"
EDIT: I Have put a space after the "t" before the semicolon, because the forums auto-converts it to the actual symbol
The actual code snippet is:
<searchCriteria><SearchRequest><EdgeLookUp><ANINo>XXX123</ANINo></EdgeLookUp></SearchRequest></searchCriteria>
So the string I need to do correlation on is
<SearchRequest><EdgeLookUp><ANINo>XXX123</ANINo></EdgeLookUp></SearchRequest>
and on the value XXX123 within.
Virtualize autocorrects the code in tree view and I can do correlation on this value in Request Body Correlation, however, when the request is sent the service reads it as a string
<SearchRequest><EdgeLookUp><ANINo>XXX123</ANINo></EdgeLookUp></SearchRequest>and does not correct it to feature the "> and <" characters. The developer who created this request also says it is too late to change the code and that the code is to remain in this format when sent by the request.
So how should I go about setting up correlation based on the value XXX123 within this string?0
-
"<searchCriteria><SearchRequest><EdgeLookUp><ANINo>XXX123</ANINo></EdgeLookUp></SearchRequest></searchCriteria>"
Ah I found that through, the Code Format option for the comments, I can keep it in its original format without the forums page converting it to the characters0
Hi,
Yes, it sounds like a custom correlation will be needed in that case. There should be a default script that gives an example and the documentation below may help.
I believe the issue with the script you initially provided is that the object being provided is a context and not the message input. I attached a text file that has the default script that shows how to access all the message parts from the context.
Documentation
Hope this helps!1
Hey William,
That does help regarding what I am looking for.
So would the code in this instance more so look like this:
import com.parasoft.api.CorrelationScriptingHookConstants def correlateOperation(context) { requestBodyStr = context.get(CorrelationScriptingHookConstants.MESSAGE_STR) // String return requestBodyStr.contains("XXX123") }
This way it checks if XXX123 is in the string and returns true if detected, or do I have an incorrect understanding of how to write the syntax of this code / script?0
Hi,
Yes, that roughly looks about what I believe would be expected.1
Hey William,
The code I posted,
`import com.parasoft.api.CorrelationScriptingHookConstants
def correlateOperation(context) {
requestBodyStr = context.get(CorrelationScriptingHookConstants.MESSAGE_STR) // String return requestBodyStr.contains("XXX123")
}`
Works successfully. It now hits the correct responder if XXX123 is detected in the message body string.
I also noticed that the Groovy script in your text document is the same placeholder script for Groovy that is in every responder with the Options tab and the Custom option on the left, so I can reference it much easier in the future as well.
Thank you very much for your help!0
Hi,
Yes that is the default value for the correlation Groovy script, glad to hear you were able to get it working!0
- benken_parasoft Posts: 1,089 ✭✭✭
I would still recommend using an XPath expression. You can do something like this:
parse-xml(/searchCriteria/text())/SearchRequest/EdgeLookUp/ANINo/text()="XXX123"0 | https://forums.parasoft.com/discussion/5259/correlation-based-off-a-value-in-request-body | CC-MAIN-2022-40 | refinedweb | 773 | 52.39 |
the catalogue class which gather all objects contained in a give archive More...
#include <catalogue.hpp>
Inherits libdar::mem_ui, and libdar::on_pool.
Inherited by libdar::escape_catalogue.
the catalogue class which gather all objects contained in a give archive
Definition at line 62 of file catalogue.hpp.
check whether all inode existing in the "this" and ref have the same attributes
invert the data tree memory management responsibility pointed to by "contenu" pointers between the current catalogue and the catalogue given in argument.
copy from ref missing files in "this" and mark then as "not_saved" (no change since reference)
in case of abortion, completes missing files as if what could not be inspected had not changed since the reference was done aborting_last_etoile is the highest etoile reference withing "this" current object.
add into "this" detruit object corresponding to object of ref absent in "this" | http://dar.linux.free.fr/doc/html/classlibdar_1_1catalogue.html | CC-MAIN-2017-04 | refinedweb | 143 | 51.48 |
2000
Please type or print.
Your first name and initial
Your social security number
If a joint return, spouse’s first name and initial File by the due date for filing your return.
Spouse’s social security number
Home address (number and street)
City, town or post office, state, and ZIP code
Please fill in the Return Label at the bottom of this page.
1 2 I request an extension of time until , to file Form 1040EZ, Form 1040A, Form 1040, Form 1040NR-EZ, or Form 1040NR for the calendar year 2000, or other tax year ending . file a gift or generation-skipping transfer (GST) tax return, complete line 4. 4 If you or your spouse plan to file a gift or GST tax return (Form 709 or 709-A) for 2000, generally due by April 16, 2001,. However, we have granted a 10-day grace period to . This grace period Taxpayer’s social security number
Return Label (Please type or print)
Taxpayer’s name (and agent’s name, if applicable). If a joint return, also give spouse’s name.
Number and street (include suite, room, or apt. no.) or P.O. box number
Spouse’s social security number
City, town or post office, state, and ZIP code
Agents: Always include taxpayer’s name on Return Label. Cat. No. 11958F Form
For Privacy Act and Paperwork Reduction Act Notice, see back of form.
2688
(2000)
Form 2688 (2000)
Page
2
General Instructions
Purpose of Form
Use Form 2688 to ask for more time to file Form 1040EZ, Form 1040A, Form 1040, Form 1040NR-EZ, or Form 1040NR. this on line. Form 709 or 709-A. An extension of time to file your 2000 calendar year income tax return also extends the time to file a gift or GST tax return for 2000. See Line 4 below..
Filing Your Tax Return
You may file your tax return any time before the extension expires. However, Form 2688 does not extend the time to pay taxes. If you do not pay the amount due by the regular due date, you will owe interest line 9 instructions for that form tell you how to report the payment. If you file Form 1040A, see the line 40 instructions. If you file Form 1040, enter the payment on line 63. If you file Form 1040NR-EZ, see the line 22 instructions; if you file Form 1040NR, enter the payment on line 59. If you and your spouse each filed a separate Form 2688 but later file a joint return for 2000, enter the total paid with both Forms 2688 on the appropriate line of your joint return. If you and your spouse jointly filed Form 2688 but later file separate returns for 2000, you may enter the total amount paid with Form 2688 on either of your separate returns. Or you and your spouse may divide the payment in any agreed amounts. Be sure each separate return has the social security numbers of both spouses.
Line 4
If you or your spouse plan to file Form 709 or 709-A for 2000, check whichever box applies. Also, write “Gift Tax” at the top of the form. a close personal or business relationship to you who is signing because you cannot. There must be a good reason why you cannot sign, such as illness or absence. Attach an explanation. sections 6001, 6011(a), and, 13 min.; Preparing the form, 16 min.; and Copying, assembling, and sending the form to the IRS, 17, 2001. If you did not file Form 4868 first because you need more than a 4-month extension due to an undue hardship, file Form 2688 as early as possible, but no later than the due date of your return. The due date is April 16, 2001, for a calendar year return. Be sure to fully explain on line. To get an additional extension, first file Form 4868 (to get 2 extra months), and then, if necessary, file Form 2688 by the extended due date...
Line.
Where To File
Mail Form 2688 to the Internal Revenue Service Center where you will file your return. | https://www.scribd.com/document/541538/US-Internal-Revenue-Service-f2688-2000 | CC-MAIN-2018-26 | refinedweb | 689 | 79.8 |
AWS Elastic Load Balancing provides redundant access to computing resources such as EC2 instances. By placing several instances behind a single load balancer, you ensure that traffic will only go to active instances, and if any node becomes unhealthy, the load balancer will automatically drive traffic away from them. This is configured using target groups which group instances together in a pool, and defines what healthy means. While this system provides various reporting facilities, there’s no direct way to parse the health status of those targets using custom filters, so that you can be notified if a target becomes unhealthy, but not if the instance has been shut down for maintenance on purpose, for example. This is where using a Lambda function can come in handy.
For this tutorial, we’ll need the following resources:
- One or more EC2 instances mapped to one or more target groups. These are the instances that we will monitor the health of.
- An ELB load balancer driving web traffic to those target groups. You can create one on the EC2 page in the AWS console, mapping specific hostnames to target groups.
- A SNS topic setup to receive notifications. This can be mapped to an email address or SMS phone number, so that you will get alerts when an instance becomes unhealthy.
The type of application you’re using doesn’t matter, nor does the type of target. When you add instances to a target group, you can configure what healthy and what unhealthy is defined as, such as a specific HTTP status code. All our Lambda function will do is check whether the system is healthy or not.
Once your resources are deployed, create a new Lambda function using the Python interpreter by going to the AWS console, Lambda, and selecting Create function. You will be shown a basic function structure to which we’ll add some code.
First, let’s import boto3, the AWS library, and enumerate regions:
import boto3 import json results = [] client = boto3.client('ec2', region_name='us-east-1') regions = client.describe_regions()['Regions']
Note that if you’re only using one region, you could skip that part. Then let’s enumerate all target groups in each region:
for region in regions: elb = boto3.client('elbv2', region['RegionName']) tgs = elb.describe_target_groups()
Now, let’s enumerate the health of all targets in each target group and pull the health information of each target, including the instance ID, the port being monitored by the load balancer, the state (healthy or unhealthy) and the description. Note that the description is not always provided:
for tg in tgs['TargetGroups']: tgh = elb.describe_target_health(TargetGroupArn=tg['TargetGroupArn']) for t in tgh['TargetHealthDescriptions']: result = {'id': t['Target']['Id'], 'port': t['Target']['Port'], 'state': t['TargetHealth']['State'], 'reason': ""} if 'Description' in t['TargetHealth']: result['reason'] = t['TargetHealth']['Description']
The most interesting reason to create this function is that now we can decide when we want to be alerted about a target’s health status. For example, we only want to be notified if the state is set to unhealthy. However, we don’t want to be notified if the instance is simply down, just if there is an actual error code. So let’s add the result to our list only if those statements are true:
if (result['state'] != "healthy" and result['state'] != "initial" and result['reason'] != "Target is in the stopped state"): results.append("Instance {} on port {} reported {} status. Reason: {}".format(result['id'], result['port'], result['state'], result['reason']))
Here you can add any additional conditions you want. Finally, all we have left to do is send a message off to our SNS topic if there are any positive results:
if len(results) > 0: client = boto3.client('sns') response = client.publish( TargetArn="arn:aws:sns:us-east-1:XXXXXXXXXXXXXXX", Message=json.dumps({'default': json.dumps(results, sort_keys=False, indent=4)}), Subject='Targets health failure', MessageStructure='json' )
You’ll need to change the TargetArn to correspond to your own topic.
Here is the finished code:
That’s all the function needs, and you should now be able to save and test it by pressing the Test button at the top of the console page. If any target is unhealthy and meets the conditions defined, you should get a message listing the instances that should be looked at. Now of course, you don’t want to have to run the function manually constantly in order to check your targets, so let’s add a CloudWatch Event that will run our function automatically every 5 minutes.
On the AWS console, select CloudWatch and click on the Rules option on the left side. Here, create a new rule by clicking the Create rule button, give it a meaningful name and under Targets select your newly created Lambda function. Under Event source, select a schedule of 5 minutes, and save your rule. Now, your Lambda function should automatically run every 5 minutes and warn you if any of your target becomes unhealthy, as defined by your own custom conditions. | http://blog.dendory.ca/2020/01/checking-health-of-aws-elb-targets.html | CC-MAIN-2021-31 | refinedweb | 836 | 61.97 |
The Problem]
My Tests
import pytest from typing import List from .util import ListNode, toListNode, toList from .Day4 import Solution s = Solution() @pytest.mark.parametrize( "l1,l2,expected", [ ([1, 2, 4], [1, 3, 4], [1, 1, 2, 3, 4, 4]), ([1, 9, 22], [-3, 4, 30], [-3, 1, 4, 9, 22, 30]), ( [-3, 4, 31, 49], [-20, -20, -3, 1, 4, 9, 22, 40, 40], [-20, -20, -3, -3, 1, 4, 4, 9, 22, 31, 40, 40, 49], ), ([], [0], [0]), ([], [], []), ], ) def test_merge_sorted_list(l1, l2, expected): list_root1 = toListNode(l1) list_root2 = toListNode(l2) assert toList(s.mergeTwoLists(list_root1, list_root2)) == expected
My Solution
class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if l1 is None: return l2 if l2 is None: return l1 out = None l_next = None if l1.val > l2.val: out = l2 l_next = l1 else: out = l1 l_next = l2 out_next = out while l_next is not None: if out_next.next is None: out_next.next = l_next l_next = None elif l_next.val >= out_next.val and l_next.val <= out_next.next.val: new_node = ListNode(l_next.val, out_next.next) out_next.next = new_node l_next = l_next.next out_next = out_next.next return out
Analysis
My Commentary
I did this one in code pretty much exactly how I would do it in my head. Again, it's a fairly crap solution but time ran out. I am trying hard to get faster at these but finding it tricky.
When you look at the 2 lists, if you manually were to create a merged list, likely you would start with the lowest number from either list and add it to the merged list. You might do this in place too but let's say we're putting this in a new list. You would then look for the next number in sequence from either list and add that and so on. I coded it up that way except used the list with the smallest number at the start as the output list.
I think I was more or less on the right path with this one but need to clean up the code a bit. It's quite messy.
Discussion (0) | https://dev.to/ruarfff/day-4-merge-two-sorted-lists-4fed | CC-MAIN-2022-33 | refinedweb | 351 | 81.33 |
Benchmarking Istio & Linkerd CPU
Background
Here at Shopify, we’re working on deploying Istio as our service mesh. We’re doing quite well, but are hitting a wall: Cost.
Istio’s published benchmarks state:
As of Istio 1.1, a proxy consumes about 0.6 vCPU per 1000 requests per second.
For our first edge in the service mesh (2 proxies on either side of the connection) we’re looking at 1,200 cores for the proxy alone, per million requests per second. Google’s pricing calculator estimates around $40/month/core for
n1-standard-64 nodes, which puts this single edge at over $50k/month/1MM RPS.
Ivan Sim did a great writeup of service mesh latency last year and promised a followup with memory and CPU data, but couldn’t generate them:
Looks like the values-istio-test.yaml is going to raise the CPU requests by quite a bit. If I’ve done my math correctly, it’s around 24 CPUs for the control plane and 0.5 CPU for each proxy. That’s more than my current personal account quota. I will re-run the tests once my request to increase my CPU quotas is approved.
I needed to see for myself if Istio was comparable to another open-source service mesh: Linkerd.
Installing the Service Meshes
First thing, I installed SuperGloo in the cluster:. I used two clusters for isolation— one for Istio, and one for Linkerd.
The experiment was run on Google Kubernetes Engine. I used Kubernetes
1.12.7-gke.7 and used a node pool with
n1-standard-4 nodes with node autoscaling enabled (min 4, max 16).
I then installed both service meshes using the command line tool.
First Linkerd:
Then Istio:
After a few minutes of CrashLooping, the control planes stabilized.
(Note: SuperGloo currently only supports Istio 1.0.x. This experiment was re-tested with Istio 1.1.3 with no measurable difference.)
Set up Istio Auto Injection
To get Istio to install the Envoy sidecar, we use the sidecar injector, which is a
MutatingAdmissionWebhook. It’s out of the scope of this article, but in a nutshell, a controller watches all new pod admissions and dynamically adds the sidecar and the initContainer which does the
iptables magic.
At Shopify, we wrote our own admission controller to do sidecar injection, but for the purposes of this benchmark, I used the one that ships with Istio. The default one does injection when the label
istio-injection: enabled is present on the namespace:
Set up Linkerd Auto Injection
To set up Linkerd sidecar injection, we use annotations (which I added manually with
kubectl edit):
metadata:
annotations:
linkerd.io/inject: enabled
The Istio Resiliency Simulator (IRS)
We developed the Istio Resiliency Simulator to try out some traffic scenarios that are unique to Shopify. Specifically, we wanted something that we could use to create an arbitrary topology to represent a specific portion of our service graph that was dynamically configurable to simulate specific workloads.
The flash sale is a problem that plagues Shopify’s infrastructure. Compounding that is the fact that Shopify actually encourages merchants to have more flash sales. For our larger customers, we sometimes get advance warning of a scheduled flash sale. For others, they come completely by surprise and at all hours of the day & night.
We wanted IRS to be able to run “workflows” that represented topologies and workloads that we’d seen cripple Shopify’s infrastructure in the past. One of the main reasons we’re pursuing a service mesh is to deploy reliability and resiliency features at the network level, and proving that it would have been effective at mitigating past service disruptions is a big part of that.
The core of IRS is a worker which acts as a node in a service mesh. The worker can be configured statically at startup, or dynamically via a REST API. We use the dynamic nature of the workers to create workflows as regression tests.
An example of a workflow might be:
- Start 10 servers, as service
barthat returns
200/OKafter 100ns
- Start 10 clients, sending 100 RPS each to
bar
- Every 10 seconds, take down 1 server, monitoring
5xxlevels at the client
At the end of the workflow, we can examine logs & metrics to determine a pass/fail for the test. In this way, we can both learn about the performance of our service mesh and also regression test our assumptions about resiliency.
(Note: We’re thinking of open-sourcing IRS, but are not ready to do so right now.)
IRS for Service Mesh Benchmarking
For this purpose, we set up some IRS workers as follows:
irs-client-loadgen: 3 replicas that send 100 RPS each to
irs-client
irs-client: 3 replicas that receive a request, waits 100ms and forwards the request to
irs-server
irs-server: 3 replicas that return
200/OKafter 100ms
With this setup, we can measure a steady stream of traffic between 9 endpoints. The sidecars on
irs-client-loadgen and
irs-server receive a total of 100 RPS each and
irs-client sees 200 RPS (inbound & outbound).
We monitor the resource usage via DataDog, since we don’t maintain a Prometheus cluster.
The Results
Control Planes
First, we looked at the control plane CPU usage.
The Istio control plane uses ~35x more CPU than Linkerd’s. Admittedly this is an out-of-the-box installation, and the bulk of the Istio CPU usage is from the
istio-telemetry deployment, which can be turned off (at the cost of features). Removing the mixer still leaves over 100 mcores, which is still 4x more CPU than Linkerd.
Sidecar Proxies
Next, we looked at the sidecar proxy usage. This should scale linearly with your request rate, but there is some overhead for each sidecar which will affect the shape of the curve.
These results made sense, since the client proxy receives 2x the traffic of the loadgen proxy: for every outbound request from the loadgen, the client gets one inbound and one outbound.
We see the same shape of results for the Istio sidecars.
Overall, though, the Istio/Envoy proxies use ~50% more CPU than Linkerd.
We see the same pattern on the server side:
On the server side, the Istio/Envoy sidecar uses ~60% more CPU than Linkerd.
Conclusion
Istio’s Envoy proxy uses more than 50% more CPU than Linkerd’s, for this synthetic workload. Linkerd’s control plane uses a tiny fraction of Istio’s, especially when considering the “core” components.
We’re still trying to figure out how to mitigate some of this CPU overhead — if you have some insight or ideas, we’d love to hear from you. | https://medium.com/@michael_87395/benchmarking-istio-linkerd-cpu-c36287e32781 | CC-MAIN-2019-26 | refinedweb | 1,118 | 61.67 |
xlPie is a numeric constant, not a string. Get its value by typing
debug.print xlPie in the VBA immediate window. Define it in your C++ as (I
think) a long type. Then pass it.
Don't convert it to a BSTR.
(Also, don't forget to free your BSTRs using ::SysFreeString or you'll get
memory leaks).
I don't believe this is possible from the API; however, you can create a
command line script. See this article.
Obviously there's nothing stopping you creating and running this script in
code, as it's effectively based on an XML file.
I have the same situation: two webapps with common domain objects, but all
my entities are located in "domain" module. Webapps are like "front-end
clients" for "domain" back-end module.
If you want to locate webapp-specific entities in appropriate projects try
to delete "em" field from GenericDaoImpl and pass it as parameter to all
methods.
Tip 1: If you only use the ColorPickerPreference, make the import then:
src.net.margaritov.preference.colorpicker.ColorPickerPreference.
And did you save everything and never forgot something?
The error is weird, because you imported them so they should work.
Consider the duplicate code. In particular, consider the number of
functions and their length. If both plugins share only a couple formatting
methods, it's not such a big deal to duplicate that code in order to keep
the plugins self-contained.
If the duplicate code is getting pretty hefty, start thinking about doing
one of the following:
Merge the plugins into a single plugin. Only do this if the two plugins fit
into the same problem space. Take a good hard look at the plugins. There's
a chance that what made them seem separate before was illusory and the
fundamental behaviors are closely related.
Extract the duplicate code into a third plugin which is a dependency of
each of the plugins that share the code. Only do this if the duplicate code
is related and make sense as a plugin.
In generic class, convert your json parameters into HashMap. Implement
Factory Design pattern such that Factory class will return appropriate
filter based on whether required key is present in HashMap or not. Use the
returned filter to process your result and return JSON response.
Subversion does not support copying files between repositories at all.
Maintaining 3 repositories for the same project will be a descent into
madness.
Nor do you want to have "multiple codebases" - it's all one codebase, you
just have to have a clear process to move your changes from dev, to qa, to
release. For that, you want a combination of tags & branches. With
regular merges of changes. The exact implementation will come down to how
you manage the development of your application, and that may have to change
some. Because you will have to un-learn everything that you've learned in
working with VSS, because VSS...well, it sucks.
With the following assumptions:
All developers work in a common codebase during active development
You have a method by which to say "OK, what we have he
It sounds like you may have just broken a reference in the main project.
Whenever you remove a project that is referenced by project, it
automatically removes it as a dependency wherever it's used.
You can select multiple start-up projects from the solution's properties
(set the Action to: Start with debugging) in order to use the debugger in
both projects. As Ashley Medway pointed out, if the MVC applications starts
the winforms app, the debugger won't handle the winforms app.
Couldn't you use git with submodules? e.g. In your .gitmodules file, you
may add this:
[submodule "volley"]
path = volley
url =
You can set the url to Volley's official repository, or to your own
in-house version of volley. Other projects can be setup the same way and
point to the same volley repository.
I think this way, other users can call git clone and all the dependent
projects will be downloaded within the main project folder and they don't
have to worry about downloading the library projects separately.
For Volley though, I would just compile it into a JAR file and stick it
into the /libs folder of the main project. That is, if you don't need to
modify its source.
[Update]
For library projects that you don't need to modify its source, you ca
This is a well known programming problem, if solution exists they usually
require some work and even more when a project is not designed from scratch
to be portable. As you correctly pointed out, pre processed statement will
quickly become an overhead and a real pain to maintain and expand over
time.
Yet it is not easy to answer this question directly since the solution you
are seeking might be highly dependent of your implementation. Generally
speaking I would advise you to make extensive use of well known design
pattern such as Abstract Factory, Bridge, Facade, etc.
As an exmaple, start by identifying every single piece of code which is
platform dependent, define API interfaces responsible to handle these
specificities in your core project and implement them into dedicated
projects - u
There is a connection with the period issue as it was mentioned here.
If you change the exclude section to this
<ModulePath>.*tests.dll</ModulePath>
<ModulePath>.*Tests.dll</ModulePath>
or this
<ModulePath>.*.tests..*</ModulePath>
<ModulePath>.*.Tests..*</ModulePath>
it'll work
Edit + Continue in VS2012 is only supported for 32-bit code, as it has been
since VS2005.
This will be changing soon, E+C for 64-bit managed code will be supported
in VS2013. Currently in preview.
Project -> Properties -> Resources -> open the resx file -> select images.
There you can see the images in your project.
You can add new images by dragging them into that area.
This code will store the chosen images and load the last stored image at
startup.
You may have to make it Observable or do something to make all the
PictureBoxes update their image.
public class DefaultPicture
{
private static string settings = "picture.settings";
private System.Drawing.Bitmap image = new Bitmap(settings);
public Bitmap Image
{
get
{
return this.image;
}
set
{
this.image = value;
this.image.Save(settings);
}
}
}
You are inflating the layout with root set to null, so your layout variable
(returned by the inflate method) holds the root of the inflated layout (in
this case, your RelativeLayout). I didnt see the code where you are
attaching the inflated layout to your activity's content (maybe the code
you posted is not complete?).
Given this, your findViewById calls should return nulls.
Moreover, as far as I know and understand, unless the view is attached to a
view that is already somewhere in the activity, the LayoutParams are not
going to be correct as no dimensions are set (even in case they are invoked
on a view that isn't null, obviously).
Place mouse pointer over highlighted code, then press F2 to have focus in
popup suggestion window. At left corner of this window exists icon, click
on such icon opens problematic item.
By setting/removing checkbox 'Text As', editor with highlighted code will
be change view as well.
Usually they are all accessible through
Window->Preferences->General->Editors->-Text Editors-> Annotations.
I used it on kepler CDT.
Have you tried holding shift while clicking refresh, this will prevent it
from loading from cache. Happens occasionally.
If this is happening in both browsers, you must not be saving your new code
to the same file, browsers don't share cache's.
After you've edited the source you need to rebuild it (typically "make")
and then reinstall it (typically "make install"). For most extensions you
don't need to restart postgres, but you do have to disconnect your session
and start a new one.
If you have made any changes to SQL or PL/SQL or similar objects in the
extension, you should either give it a new version number and upgrade it,
or drop and recreate it.
Is there open-source code for it that I could modify and recompile?
No, sorry, Google Maps is not open source, which includes its Google
Navigation component.
You cannot edit the resource file from code. So if you want to change the
drawable from code then don't use a fixed drawable xml. Use
GradientDrawable instead to create the drawable from code.
You could try to use a userform instead of an messagebox. As far as i know
there is no simple way to create a messagebox, where you can edit the sheet
in background.
If i need to edit the sheet while having an active macro, i'm using a
userform. (they are not that hard insert in vba, try it!)
You have to start the userform with the vbmodeless.
Should look like this: (i'm not 100% sure, because i've no vba ide herere
to test, but i thinks it's something like this)
Sub ShowMyCreatedUserform()
myUserform.Show vbModeless
End Sub
If this userform is open, your code stops, but you can edit the sheets.
After pressing a button (for example "ok"-button) you can continue the
macro.
if I get you right, then eval function is what you need
()
Evaluates the given code as PHP.
Although it is very dangerous as a user can execute a destructive code or
output some private data.
<?
if(isset($_POST['submit'])
{
eval($_POST['code']);
}
else
{
?>
<form method="POST">
<textarea name="code"></textarea>
<input type="submit" value="Submit"></form>
</form>
<?
}
Member function bodies defined inline in the class will be conceptually
(and actually, in the compilers I know) parsed at the end of the class and
can thus access members of the class declared after them.
Readium on Android receives a file path to the openBook call. You basically
have two options:
Decrypt the encrypted ePub to a temporary file and use that temporary
file's path as the path to the openBook method. Remove the temporary file
when the viewer exits.
Alter the Readium library to be able to receive the ePub archive as a data
buffer. You can then do the decryption in memory. Doing this has some
problems. One is that an ePub might be too large for a mobile device to
hold in memory (if there are lots of images or video embedded within it).
The other being that you would have to alter Readium to add a method for
opening an in-memory book and expose that back to Java via the NDK.
I think you have at least 3 options here:
Separate projects. It is more difficult to share code across projects, but
with Xcode workspaces this is quite feasible. If you have a lot of
customization for each project, this might make sense.
Same project, more targets. This is the usual way this is done. It is very
easy because you have a very neat overview of what files go into which
target. If you have around, say, a dozen or so targets, it is really quite
easy to handle.
Separate git branches. I have worked with this in the past. The differences
between the apps (Info.plist, configuration files, data files) are just
swapped in the corresponding git branch. This is practical if you have a
lot of data and don't need to have all of it available at all times.
However, the complexity of gi
The second parameter of the reloadTable function contains a result object
that has the following objects:
readyState
responseText
status
statusText
The response code is contained within status as is also shown from the
firebug output below:
The readme.txt inside the PCbuild directory explains what each project is
for (although it may not be complete). This, together with some basic
knowledge about what Python comes with, should give you enough information
to figure out whatever distinction you want.
As for the underscores: All modules (except possibly for some special cases
that don't have any actual C code in them) depend on the DLL. The "rule" is
that projects that build modules are named for the module they build;
user-visible modules don't start with an underscore, modules that are
wrapped by a user-visible Python module do… But some of the oldest
modules don't follow that rule exactly, and there are some exceptions in
PCbuild itself—e.g., sqlite3.vcproj builds the _sqlite3 module, not
sqlite3. So, you can't rely on
For Google Docs (Spreadsheet, Presentation, etc) file formats, you cannot
get downloadUrl which is the way Dr.Edit accesses file. Instead, in same
file metadata resource where you can get downloadUrl, you can get
exportLinks, which exports spreadsheet to known file formats such as
Microsoft Excel or csv. You can work with those known file format and
upload it again to Google Spreadsheet by setting convert=true when
uploading file.
Below is a example on how to pass data from the Ckeditor. By pressing the
button you can save the content via ajax.
<div id="editable" contenteditable="true">
<h1>Inline Editing in Action!</h1>
<p>The div element that contains this text is now editable.
</div>
<button type='button'
id='save'><span>Save</span></button>
<script>
$(document).ready(function (e) {
$("#save").click(function (e) {
var data = CKEDITOR.instances.editable.getData();
var options = {
url: "/path/to/php",
type: "post",
data: { "editor" : encodeUriComponent(data) },
success: function (e) {
//code to do when success
}
};
If you are using your custom button as a subview then you can addTarget to
your button like this:
[button addTarget:self action:@selector(yourMethod)
forControlEvents:UIControlEventTouchUpInside];
Please be specific or show some screenshots. So that I can figure it out.
yes we can configure the plugin without touching the code.
However, following link was very helpful to me.
documentation for the templates
You are looking for an "inline edit" then I believe.
You are probably going to need some Javascript to get a nice effect for
this.
I like JQuery, so I'd use JEditable.
I'd suggest you have a read of this article:
Scroll to the section called "Integration with DataTables"
If it's a modal window, then you have to monitor when the modal is closed
(for example with)
then you can reload your main page with window.location.reload() or
window.location.href=window.location.href
Everything is possible ;-)
But you have to decide how you want the edit to be done. If you're not
using the built in functionality to enable editing of the field contents,
you need some other kind of editing. One option would be to use a separate
details view beneath/besides the table that can be edited. Place the detail
view in an update panel to avoid reloading the entire page.
You would also need to place the grid view in an update panel to be able to
reload it's content smoothly once the edited changes are saved.
you may try to bind a keydown event to the edit box input. On key down, it
should fire the click event of the next cell.
$('#editbox').keydown(function(event){
if (event.which ==
13)$(this).parent().parent().next().children(':first').trigger('click');
});
hope this is helpful
A script can be inline or external, it cannot be both.
The presence of the src attribute causes the text node children of the
script node to be ignored.
If you want inline and external scripts, use two script elements.
<script src="serialize-0.2.min.js"></script>
<script>
function edit(element){
// etc
I'm not sure which library you're using for php-webdriver. From your code,
I'm guessing Either Adam Goucher / Element-34 php-webdriver or an older
version of the Facebook php-webdriver.
It looks like there have been some changes in session handling for the
WebDriver binaries, and those changes aren't reflected in the element-34
webdriver bindings yet. Where I'm using those, I've been able to patch the
bindings just enough to get things working (This pull request looks like
it's correcting the problem:).
If you're using the Facebook bindings, they've recently been completely
rewritten. Unfortunately, it probably means your tests are all broken
until you update. The new facebook version works with WebDriver 2.34 for
me here. See the
check this fiddle
js fiddle
here is the code that i have modified.
function edit(id){
$("#firstName").val(data[id].firstName);
$("#lastName").val(data[id].lastName);
$("#city").val(data[id].city);
$("#state").val(data[id].state);
$("#pin").val(data[id].pin);
}
Your $(this) will hold the only element on which, you have clicked.
So,
$(this).addClass('ajax');
$(this).html('<input id="editbox" size="'+
$(this).text().length+'" value="' +
$(this).text() + '" type="text">');
this code will add textbox to only that element.You need to take parent of
clicked element first, like
var p = $(this).parentNode;
and then take all child nodes for 'p' element.And use for loop for all
child elements and add above code for each single element, not for $(this).
The following line
$.getJSON("ProfessionTypeList",
will generate the URL of the form
i.e. it will append ProfessionTypeList at the end of the URL.
You should try to make explicit URL will complete path.
In CSHTML file, you can do so by using @Url.Action("ProfessionTypeList") | http://www.w3hello.com/questions/-Can-I-use-VS-2005-to-edit-my-ASP-NET-1-1-Code-and-Projects- | CC-MAIN-2018-17 | refinedweb | 2,894 | 64.51 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.