INSERT INTO Person
(First, Last)
VALUES
('Joe', 'O''Brien')
/\
here
Friday, December 5, 2014
how to do a SQL insert with a value with an apostrophe in it
Monday, November 3, 2014
PostgreSQL Error 42501: Permission Denied for Schema
I appear to have gotten it working. I looked back over all of the
permission settings on the schema, except that this time I went back
through all of the "Default Privileges" as well. I set my "systemusers"
group to have
So, apparently I DID overlook something rather important. Even with all of the individual permission settings I had assigned on the specific objects, those default privileges were still not set the way they needed to be. Lesson learned
SELECT on tables and sequences, EXECUTE on functions and USAGE on types. When I tested again, my stored procedure ran correctly and created my profile record in the database as expected.So, apparently I DID overlook something rather important. Even with all of the individual permission settings I had assigned on the specific objects, those default privileges were still not set the way they needed to be. Lesson learned
Postgres INSERT ERROR: permission denied for schema public
|
Assuming the username is
testing, you probably want to do:
Note about granting ALL PRIVILEGES: you don't say on what this GRANT command was applied. Assuming it was ON DATABASE..., it just means CONNECT, CREATE and TEMP privileges, nothing about the public schema or any other contained object, which is why it "doesn't work".EDIT: when that's not sufficient If the tables referenced by the foreign keys are not owned by testing, their owner needs also to have the USAGE privilege on the schema in order to look up the referenced tables.It's not obvious from the result of \dp (the result of \d would tell for sure) but if category is owned by super and that user also has no privilege on the schema, you'd need to assign it with:
|
Friday, October 24, 2014
how to get active frame on JDesktopPane
Use JDekstopPane.getSelectedFrame() method (From doc: currently active JInternalFrame in this JDesktopPane, or null if no JInternalFrame is currently active.) or
JDesktopPane.getAllFrames() to get list of all JInternalFrames currently displayed in the desktop and check isSelected() method.
Monday, September 29, 2014
how to check number in java
Hi all, this simple code to check number that I wrote with java code.
public boolean isNumeric(String st){
try{
double d = Double.parseDouble(st);
}catch(NumberFormatException e){
return false;
}
return true;
}
Please enjoy and sharing your ideas!
public boolean isNumeric(String st){
try{
double d = Double.parseDouble(st);
}catch(NumberFormatException e){
return false;
}
return true;
}
Please enjoy and sharing your ideas!
How to check dot(.) in java code
Hi everyone, today I want to show you how to check dot(.) by using java code. The purpose of this code, we want to allow dot one time when we trigger it. example like calculator ...
Please enjoy with my code and then pls you help to comment me to improve our knowledge each other. Thanks Advance!
public boolean checkDot(String st){
char ch[] = st.toCharArray();
for(int i=0;i<ch.length;i++)
if(ch[i] =='.')
return true;
return false;
}
This code, I allow to pass arguments as String. But you can modify it by your needs. Thanks!
Please enjoy with my code and then pls you help to comment me to improve our knowledge each other. Thanks Advance!
public boolean checkDot(String st){
char ch[] = st.toCharArray();
for(int i=0;i<ch.length;i++)
if(ch[i] =='.')
return true;
return false;
}
This code, I allow to pass arguments as String. But you can modify it by your needs. Thanks!
Thursday, September 11, 2014
How to list directories, subdirectories and files using java
Hi everyone, I welcome to my post. Today I want to show you some codes using java language to list directories, subdirectories, and files. You can see my as below:
package com.saretsothea.files.classwork;
import java.io.File;
import java.util.Scanner;
/**
*
* @author Sout Saret
*/
public class ListFiles{
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
String folder;
System.out.print("Please the path of folder:");
folder =sc.nextLine();
System.out.println("List all directories, subdirectries and files:");
File f = new File(folder);
System.out.println(f.getName());
listFile(folder);
}
public static void listFile(String folder){
try{
File f = new File(folder);
File[] listOfFiles = f.listFiles();
for(int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("--" + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("-"+listOfFiles[i].getName());
listFile(listOfFiles[i].getAbsolutePath());
}
}
}catch(NullPointerException e){}
}
}
Thanks for reading!!!!!!!!!!!!!!
package com.saretsothea.files.classwork;
import java.io.File;
import java.util.Scanner;
/**
*
* @author Sout Saret
*/
public class ListFiles{
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
String folder;
System.out.print("Please the path of folder:");
folder =sc.nextLine();
System.out.println("List all directories, subdirectries and files:");
File f = new File(folder);
System.out.println(f.getName());
listFile(folder);
}
public static void listFile(String folder){
try{
File f = new File(folder);
File[] listOfFiles = f.listFiles();
for(int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("--" + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("-"+listOfFiles[i].getName());
listFile(listOfFiles[i].getAbsolutePath());
}
}
}catch(NullPointerException e){}
}
}
Thanks for reading!!!!!!!!!!!!!!
Monday, July 14, 2014
How to convert a numeric value into English words in Excel
How to create the sample function Called SpellNumber
- Start Microsoft Excel.
- Press ALT+F11 to start the Visual Basic Editor.
- On the Insert menu, click Module.
- Type the following code into the module sheet.
Option Explicit
'Main Function
Function SpellNumber(ByVal MyNumber)
Dim Dollars, Cents, Temp
Dim DecimalPlace, Count
ReDim Place(9) As String
Place(2) = " Thousand "
Place(3) = " Million "
Place(4) = " Billion "
Place(5) = " Trillion "
' String representation of amount.
MyNumber = Trim(Str(MyNumber))
' Position of decimal place 0 if none.
DecimalPlace = InStr(MyNumber, ".")
' Convert cents and set MyNumber to dollar amount.
If DecimalPlace > 0 Then
Cents = GetTens(Left(Mid(MyNumber, DecimalPlace + 1) & _
"00", 2))
MyNumber = Trim(Left(MyNumber, DecimalPlace - 1))
End If
Count = 1
Do While MyNumber <> ""
Temp = GetHundreds(Right(MyNumber, 3))
If Temp <> "" Then Dollars = Temp & Place(Count) & Dollars
If Len(MyNumber) > 3 Then
MyNumber = Left(MyNumber, Len(MyNumber) - 3)
Else
MyNumber = ""
End If
Count = Count + 1
Loop
Select Case Dollars
Case ""
Dollars = "No Dollars"
Case "One"
Dollars = "One Dollar"
Case Else
Dollars = Dollars & " Dollars"
End Select
Select Case Cents
Case ""
Cents = " and No Cents"
Case "One"
Cents = " and One Cent"
Case Else
Cents = " and " & Cents & " Cents"
End Select
SpellNumber = Dollars & Cents
End Function
' Converts a number from 100-999 into text
Function GetHundreds(ByVal MyNumber)
Dim Result As String
If Val(MyNumber) = 0 Then Exit Function
MyNumber = Right("000" & MyNumber, 3)
' Convert the hundreds place.
If Mid(MyNumber, 1, 1) <> "0" Then
Result = GetDigit(Mid(MyNumber, 1, 1)) & " Hundred "
End If
' Convert the tens and ones place.
If Mid(MyNumber, 2, 1) <> "0" Then
Result = Result & GetTens(Mid(MyNumber, 2))
Else
Result = Result & GetDigit(Mid(MyNumber, 3))
End If
GetHundreds = Result
End Function
' Converts a number from 10 to 99 into text.
Function GetTens(TensText)
Dim Result As String
Result = "" ' Null out the temporary function value.
If Val(Left(TensText, 1)) = 1 Then ' If value between 10-19...
Select Case Val(TensText)
Case 10: Result = "Ten"
Case 11: Result = "Eleven"
Case 12: Result = "Twelve"
Case 13: Result = "Thirteen"
Case 14: Result = "Fourteen"
Case 15: Result = "Fifteen"
Case 16: Result = "Sixteen"
Case 17: Result = "Seventeen"
Case 18: Result = "Eighteen"
Case 19: Result = "Nineteen"
Case Else
End Select
Else ' If value between 20-99...
Select Case Val(Left(TensText, 1))
Case 2: Result = "Twenty "
Case 3: Result = "Thirty "
Case 4: Result = "Forty "
Case 5: Result = "Fifty "
Case 6: Result = "Sixty "
Case 7: Result = "Seventy "
Case 8: Result = "Eighty "
Case 9: Result = "Ninety "
Case Else
End Select
Result = Result & GetDigit _
(Right(TensText, 1)) ' Retrieve ones place.
End If
GetTens = Result
End Function
' Converts a number from 1 to 9 into text.
Function GetDigit(Digit)
Select Case Val(Digit)
Case 1: GetDigit = "One"
Case 2: GetDigit = "Two"
Case 3: GetDigit = "Three"
Case 4: GetDigit = "Four"
Case 5: GetDigit = "Five"
Case 6: GetDigit = "Six"
Case 7: GetDigit = "Seven"
Case 8: GetDigit = "Eight"
Case 9: GetDigit = "Nine"
Case Else: GetDigit = ""
End Select
End Function
Thursday, May 29, 2014
Permission denied in PostgreSQL
You've granted
Can be done per schema:
Don't forget to
CREATE, CONNECT, and TEMPORARY privileges on the database to myuser but you haven't granted SELECT and INSERT table privileges yet. You'll need something like:GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO myuser;
In addition you need privileges on sequences if you have any serial columns or other column defaults drawing from sequences. Generally, the USAGE privilege is be enough for INSERT operations to work, but since you asked to "give all rights":GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO myuser;
You will probably want to grant DEFAULT PRIVILEGES, too. So your administrator can access future objects automatically, too.Can be done per schema:
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO administrator;
If you omit the schema, it applies to the whole database:ALTER DEFAULT PRIVILEGES GRANT ALL ON TABLES TO administrator;
Only applies to objects created by the role specified (defaulting to the role that executes this command):ALTER DEFAULT PRIVILEGES FOR staff GRANT IN SCHEMA public ... ;
Available since PostgreSQL 9.0.Don't forget to
GRANT privileges on SEQUENCES in addition if you have any. (For instance as source for default values in a serial column.)
ERROR: permission denied for sequence using PostgreSQL
Since PostgreSQL 8.2 you have to use:
GRANT USAGE, SELECT ON SEQUENCE cities_id_seq TO user;
GRANT USAGE - For sequences, this privilege allows the use of the currval and nextval functions.Thursday, May 22, 2014
Granting access to all tables for a user on PostgreSQL Database
First, you have to be able to connect to the database in order to run queries. This can be achieved by
REVOKE CONNECT ON DATABASE your_database FROM PUBLIC;
GRANT CONNECT
ON DATABASE database_name
TO user_name;
The REVOKE is necessary becauseThe key word PUBLIC indicates that the privileges are to be granted to all roles, including those that might be created later. PUBLIC can be thought of as an implicitly defined group that always includes all roles. Any particular role will have the sum of privileges granted directly to it, privileges granted to any role it is presently a member of, and privileges granted to PUBLIC.If you really want to restrict your user to DML statements, then you have a little more to do:
REVOKE ALL
ON ALL TABLES IN SCHEMA public
FROM PUBLIC;
GRANT SELECT, INSERT, UPDATE, DELETE
ON ALL TABLES IN SCHEMA public
TO user_name;
These assume that you will have only one schema (which is named 'public' by default).Wednesday, May 21, 2014
Configuring MS SQL Server for Remote Access
Problem:
A Microsoft SQL instance cannot be accessed remotely through ODBC, Visual Studio, or SQL Server Management Studio connection.Resolution:
(applies to MS SQL 2005, 2008, 2008 R2, and 2012)The Windows firewall is usually the culprit in these scenarios. Open TCP port 1433 for the service itself, and 1434 if you need to use the SQL Browser service. Read this article to learn how to Open an Inbound Custom Allow Rule in Windows Firewall.
- Open cliconfg from a RUN prompt and make sure TCP/IP is an enabled protocol.
For SQL 2005/2008/2008 R2: Check the Services tool, Start > Administrative Tools > Services, to see that the service named SQL Server (MSSQLSERVER) is started.
For MS SQL 2012: Use the Windows key or hover over the left lower corner of the desktop and select Administrative Tools, then Services to see that the service named SQL Server (MSSQLSERVER) is started.
- Ensure that you are using the correct credentials to authenticate. The default SQL administrator account is named sa and if you built the server from one of our server images with MSSQL pre-installed, the password will be in a text file on the root of the C partition.
- Use netstat –an from the command prompt to verify that the server is listening for SQL traffic on the correct ports.
- If the server is not listening for SQL traffic on the correct ports, use SQL Server Configuration Manager to change the ports.
- For MS SQL 2005/2008/2008 R2, go to Start > All Programs > Microsoft SQL Server 2005 (or 2008/2008 R2) > Configuration Tools > SQL Server Configuration Manager.
For MS SQL 2012: Use the Windows key or hover over the left lower corner of the desktop and select All Programs > Microsoft SQL Server 2012 > Configuration Tools > SQL Server Configuration Manager.
- Open the + next to SQL Server Network Configuration.
- Right-click TCP/IP and select Properties.
- Select IP Addresses.
- All TCP ports mentioned on all interfaces should be 1433. Change this to reflect the correct port number and restart the SQL services.
- For MS SQL 2005/2008/2008 R2, go to Start > All Programs > Microsoft SQL Server 2005 (or 2008/2008 R2) > Configuration Tools > SQL Server Configuration Manager.
For MS SQL 2012: Use the Windows key or hover over the left lower corner of the desktop and select All Programs > Microsoft SQL Server 2012 > Configuration Tools > SQL Server Configuration Manager.
- If you are using named instances when installing SQL, giving you the ability to host multiple SQL versions or service types, you will have to specify the name of the SQL instance when connecting rather than just using the server’s name or IP. If you have created a named instance, you will need to access it by appending the name to the server’s name or IP, following a backslash (e.g. 12.34.56.78\SQLINSTANCENAME or SQLSERVERNAME\SQLINSTANCENAME).
Tuesday, April 8, 2014
How to download spring framework zip file
Unfortunately there is no official link on the new
spring.io website. You now have to download the zip files form their
repository, as stated here: https://github.com/spring-projects/spring-framework/wiki/Downloading-Spring-artifacts (at the bottom).
Direct link to complete Spring zip files: http://repo.spring.io/release/org/springframework/spring/
Direct link to complete Spring zip files: http://repo.spring.io/release/org/springframework/spring/
Download spring-framework-3.2.4 here.
http://maven.springframework.org/release/org/springframework/spring/3.2.4.RELEASE/
http://maven.springframework.org/release/org/springframework/spring/3.2.4.RELEASE/
It is always recommended to use Maven like build tools as
it fetches not only the Spring JARs but also the JARs which Spring
depends upon (like e.g. commons-logging) and so on...
How to do this quickly is given in this post by "fujy":-
Where can I download Spring Framework jars
Cheers, Akshay
Cheers, Akshay
You can find out all spring jar in zip format at here .
can i use Spring framework for developing JSP application?
You can use Spring MVC. Try following tutorials:
http://static.springsource.org/docs/Spring-MVC-step-by-step/
http://www.vaannila.com/spring/spring-mvc-tutorial-1.html
http://maestric.com/doc/java/spring
Thanks.
http://static.springsource.org/docs/Spring-MVC-step-by-step/
http://www.vaannila.com/spring/spring-mvc-tutorial-1.html
http://maestric.com/doc/java/spring
Thanks.
Thursday, April 3, 2014
Font Configuration
Fontconfig is a library designed to provide a list of available fonts to applications, and also for configuration for how fonts get rendered. See package fontconfig and Wikipedia:Fontconfig. The Free type library (freetype2 package) renders the fonts, based on this configuration.
Though Fontconfig is the standard in today's Linux, some applications still rely on the original method of font selection and display, the X Logical Font Description.
The font rendering packages on Arch Linux includes support for freetype2 with the bytecode interpreter (BCI) enabled. Patched packages exist for better font rendering, especially with an LCD monitor. See #Patched packages below. The Infinality package allows both auto-hinting and subpixel rendering, allows the LCD filter to be tweaked without recompiling, and allows the auto-hinter to work well with bold fonts.
The font paths initially known to Fontconfig are:
To see a list of known Fontconfig fonts:
Check for Xorg's known font paths by reviewing its log:
Configuration can be done per-user through
For example, to enable sub-pixel RGB rendering globally:
To enable subpixel rendering:
The
First, refresh the freetype2 PKGBUILD as root:
Though Fontconfig is the standard in today's Linux, some applications still rely on the original method of font selection and display, the X Logical Font Description.
The font rendering packages on Arch Linux includes support for freetype2 with the bytecode interpreter (BCI) enabled. Patched packages exist for better font rendering, especially with an LCD monitor. See #Patched packages below. The Infinality package allows both auto-hinting and subpixel rendering, allows the LCD filter to be tweaked without recompiling, and allows the auto-hinter to work well with bold fonts.
Font paths
For fonts to be known to applications, they must be cataloged for easy and quick access.The font paths initially known to Fontconfig are:
/usr/share/fonts/ and ~/.fonts/
(of which Fontconfig will scan recursively). For ease of organization
and installation, it is recommended to use these font paths when adding fonts.
To see a list of known Fontconfig fonts:
$ fc-list : fileSee
man fc-list for more output formats.
Check for Xorg's known font paths by reviewing its log:
$ grep /fonts /var/log/Xorg.0.log
Tip: You can also check the list of Xorg's known font paths using the command
Keep in mind that Xorg does not search recursively through the xset q./usr/share/fonts/ directory like Fontconfig does. To add a path, the full path must be used:
Section "Files"
FontPath "/usr/share/fonts/local/"
EndSection
If you want font paths to be set on a per-user basis, you can add and
remove font paths from the default by adding the following line(s) to ~/.xinitrc:
xset +fp /usr/share/fonts/local/ # Prepend a custom font path to Xorg's list of known font paths xset -fp /usr/share/fonts/sucky_fonts/ # Remove the specified font path from Xorg's list of known font pathsTo see a list of known Xorg fonts use
xlsfonts, from the xorg-xlsfonts package.
Fontconfig configuration
Fontconfig is documented in the fonts-conf man page.Configuration can be done per-user through
$XDG_CONFIG_HOME/fontconfig/fonts.conf, and globally with /etc/fonts/local.conf.
The settings in the per-user configuration have precedence over the
global configuration. Both these files use the same syntax.
Note: Configuration files and directories:
Fontconfig gathers all its configurations in a central file (~/.fonts.conf/, ~/.fonts.conf.d/ and ~/.fontconfig/*.cache-* are deprecated since fontconfig 2.10.1 (upstream commit) and will not be read by default in the future versions of the package. New paths are $XDG_CONFIG_HOME/fontconfig/fonts.conf, $XDG_CONFIG_HOME/fontconfig/conf.d/NN-name.conf and $XDG_CACHE_HOME/fontconfig/*.cache-* respectively. If using the second location, make sure the naming is valid (where NN is a two digit number like 00, 10, or 99)./etc/fonts/fonts.conf).
This file is replaced during fontconfig updates and shouldn't be
edited. Fontconfig-aware applications source this file to know
available fonts and how they get rendered. This file is a
conglomeration of rules from the global configuration (/etc/fonts/local.conf), the configured presets in /etc/fonts/conf.d/, and the user configuration file ($XDG_CONFIG_HOME/fontconfig/fonts.conf). fc-cache can be used to rebuild fontconfig's configuration, although changes will only be visible in newly launched applications.
Note: For some desktop environments (such as GNOME and KDE) using the Font Control Panel
will automatically create or overwrite the user font configuration
file. For these desktop environments, it is best to match your already
defined font configurations to get the expected behavior.
Fontconfig configuration files use XML format and need these headers:
<?xml version="1.0"?> <!DOCTYPE fontconfig SYSTEM "fonts.dtd"> <fontconfig> <!-- settings go here --> </fontconfig>The configuration examples in this article omit these tags.
Presets
There are presets installed in the directory/etc/fonts/conf.avail. They can be enabled by creating symbolic links to them, both per-user and globally, as described in /etc/fonts/conf.d/README. These presets will override matching settings in their respective configuration files.
For example, to enable sub-pixel RGB rendering globally:
# cd /etc/fonts/conf.d # ln -s ../conf.avail/10-sub-pixel-rgb.confTo do the same but instead for a per-user configuration:
$ mkdir $XDG_CONFIG_HOME/fontconfig/conf.d $ ln -s /etc/fonts/conf.avail/10-sub-pixel-rgb.conf $XDG_CONFIG_HOME/fontconfig/conf.d
Anti-aliasing
Font rasterization converts vector font data to bitmap data so that it can be displayed. The result can appear jagged due to aliasing. anti-aliasing is enabled by default and increases the apparent resolution of font edges. <match target="font">
<edit name="antialias" mode="assign">
<bool>true</bool>
</edit>
</match>
Note: Some applications, like Gnome 3 may override default anti-alias settings.
Hinting
Font hinting (also known as instructing) is the use of mathematical instructions to adjust the display of an outline font so that it lines up with a rasterized grid, (i.e. the pixel grid of the display). Its intended effect is to make fonts appear more crisp so that they are more readable. Fonts will line up correctly without hinting when displays have around 300 DPI. Two types of hinting are available.Byte-Code Interpreter (BCI)
Using BCI hinting, instructions in TrueType fonts fonts are rendered according to FreeTypes's interpreter. BCI hinting works well with fonts with good hinting instructions. To enable hinting: <match target="font">
<edit name="hinting" mode="assign">
<bool>true</bool>
</edit>
</match>
Autohinter
The Autohinter attempts to do automatic hinting and disregards any existing hinting information. Originally it was the default because TrueType2 fonts were patent-protected but now that these patents have expired there's very little reason to use it. It does work better with fonts that have broken or no hinting information but it will be strongly sub-optimal for fonts with good hinting information. Generally common fonts are of the later kind so autohinter will not be useful. To enable auto-hinting: <match target="font">
<edit name="autohint" mode="assign">
<bool>true</bool>
</edit>
</match>
Hintstyle
Hintstyle is the amount of font reshaping done to line up to the grid. Hinting values are:hintnone, hintslight, hintmedium, and hintfull. hintslight will make the font more fuzzy to line up to the grid but will be better in retaining font shape, while hintfull will be a crisp font that aligns well to the pixel grid but will lose a greater amount of font shape. Preferences vary.
<match target="font">
<edit name="hintstyle" mode="assign">
<const>hintfull</const>
</edit>
</match>
Note: Some applications, like Gnome 3 may override default hinting settings.
Subpixel rendering
Most monitors manufactured today use the Red, Green, Blue (RGB) specification. Fontconfig will need to know your monitor type to be able to display your fonts correctly. Monitors are either: RGB (most common), BGR, V-RGB (vertical), or V-BGR. A monitor test can be found here).To enable subpixel rendering:
<match target="font">
<edit name="rgba" mode="assign">
<const>rgb</const>
</edit>
</match>
Note: Subpixel
rendering effectively triples the horizontal (or vertical) resolution
for fonts by making use of subpixels. The autohinter and subpixel
rendering are not designed to work together and should not be used in
combination without the Infinality patch set.
LCD filter
When using subpixel rendering, you should enable the LCD filter, which is designed to reduce colour fringing. This is described under LCD filtering in the FreeType 2 API reference. Different options are described under FT_LcdFilter, and are illustrated by this LCD filter test page.The
lcddefault filter will work for most users. Other filters are available that can be used in special situations: lcdlight; a lighter filter ideal for fonts that look too bold or fuzzy, lcdlegacy, the original Cairo filter; and lcdnone to disable it entirely.
<match target="font">
<edit mode="assign" name="lcdfilter">
<const>lcddefault</const>
</edit>
</match>
Advanced LCD filter specification
If the available, built-in LCD filters are not satisfactory, it is possible to tweak the font rendering very specifically by building a custom freetype2 package and modifying the hardcoded filters. The Arch Build System can be used to build and install packages from source.First, refresh the freetype2 PKGBUILD as root:
# abs extra/freetype2This example uses
/var/abs/build
as the build directory, substitute it according to your personal ABS
setup. Download and extract the freetype2 package as a regular user:
$ cd /var/abs/build $ cp -r ../extra/freetype2 . $ cd freetype2 $ makepkg -oEdit the file
src/freetype-VERSION/src/base/ftlcdfil.c and look up the definition of the constant default_filter[5]:
static const FT_Byte default_filter[5] =
{ 0x10, 0x40, 0x70, 0x40, 0x10 };
This constant defines a low-pass filter applied to the rendered
glyph. Modify it as needed. Save the file, build and install the custom
package:
$ makepkg -e # pacman -Rd freetype2 # pacman -U freetype2-VERSION-ARCH.pkg.tar.xzReboot or restart X. The lcddefault filter should now render fonts differently.
Disable auto-hinter for bold fonts
The auto-hinter uses sophisticated methods for font rendering, but often makes bold fonts too wide. Fortunately, a solution can be turning off the autohinter for bold fonts while leaving it on for the rest:...
<match target="font">
<test name="weight" compare="more">
<const>medium</const>
</test>
<edit name="autohint" mode="assign">
<bool>false</bool>
</edit>
</match>
...
Enable anti-aliasing only for bigger fonts
Some users prefer the sharper rendering that anti-aliasing does not offer:...
<match target="font">
<edit name="antialias" mode="assign">
<bool>false</bool>
</edit>
</match>
<match target="font" >
<test name="size" qual="any" compare="more">
<double>12</double>
</test>
<edit name="antialias" mode="assign">
<bool>true</bool>
</edit>
</match>
<match target="font" >
<test name="pixelsize" qual="any" compare="more">
<double>16</double>
</test>
<edit name="antialias" mode="assign">
<bool>true</bool>
</edit>
</match>
...
Replace fonts
The most reliable way to do this is to add an XML fragment similar to the one below. Using the "binding" attribute will give you better results, for example, in Firefox where you may not want to change properties of font being replaced. This will cause Ubuntu to be used in place of Georgia:... <match target="pattern"> <test qual="any" name="family"><string>georgia</string></test> <edit name="family" mode="assign" binding="same"><string>Ubuntu</string></edit> </match> ...An alternate approach is to set the "preferred" font, but this only works if the original font is not on the system, in which case the one specified will be substituted:
...
< !-- Replace Helvetica with Bitstream Vera Sans Mono -->
< !-- Note, an alias for Helvetica should already exist in default conf files -->
<alias>
<family>Helvetica</family>
<prefer><family>Bitstream Vera Sans Mono</family></prefer>
<default><family>fixed</family></default>
</alias>
...
Disable bitmap fonts
To disable bitmap fonts in fontconfig, use70-no-bitmaps.conf (which is not placed by fontconfig by default):
# cd /etc/fonts/conf.d # rm 70-yes-bitmaps.conf # ln -s ../conf.avail/70-no-bitmaps.confThis oneliner should also work:
# ln -s /etc/fonts/conf.avail/70-no-bitmaps.conf /etc/fonts/conf.d/You may not need to remove
70-yes-bitmaps.conf
if it does not exist. You can choose which fonts to replace bitmaps
fonts with (Helvetica, Courier and Times bitmap mapts to TTF fonts) by:
~/.config/fontconfig/conf.d/29-replace-bitmap-fonts.conf
<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
<!-- Replace generic bitmap font names by generic font families -->
<match target="pattern" name="family">
<test name="family" qual="any">
<string>Helvetica</string>
</test>
<edit mode="assign" name="family">
<string>Arial</string>
<string>Liberation Sans</string>
<string>sans-serif</string>
</edit>
</match>
<match target="pattern" name="family">
<test name="family" qual="any">
<string>Courier</string>
</test>
<edit mode="assign" name="family">
<string>Courier New</string>
<string>Liberation Mono</string>
<string>monospace</string>
</edit>
</match>
<match target="pattern" name="family">
<test name="family" qual="any">
<string>Times</string>
</test>
<edit mode="assign" name="family">
<string>Times New Roman</string>
<string>Liberation Serif</string>
<string>serif</string>
</edit>
</match>
</fontconfig>
To disable embedded bitmap for all fonts:
Start by editing
Assuming the Dupree font is installed:
To guarantee that personal settings take precedence over any other rules, change their ordering:
A simple starting point:
Infinality's settings are all configurable at runtime via environment variables in
It is recommended to also install fontconfig-infinality to enable selection of predefined font substitution styles and antialiasing settings, apart from the rendering settings of the engine itself. After doing so, you can select the font style (win7, winxp, osx, linux, ...) with:
Please, see Infinality-bundle+fonts for more information and installation instructions.
Install the patched packages from the AUR, the package names are: freetype2-ubuntu fontconfig-ubuntu cairo-ubuntu.
The global configuration will need to be added. See #Example fontconfig configurations for a starting point. Ubuntu rendering works the best with hintslight option.
Note that the *-ubuntu AUR packages need to be kept up-to-date by the user, and will not be updated by pacman along with other packages. The whole graphical system can become inoperable if the user-installed core graphical libraries become incompatible with the official repository applications.
Fontconfig should be able to detect DPI parameters as discovered by the Xorg server. You can check the automatically discovered DPI with
Fontconfig will default to the Xft.dpi variable if it is set. Xft.dpi is usually set by desktop environments (usually to Xorg's DPI setting) or manually in
~/.config/fontconfig/conf.d/20-no-embedded.conf
<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
<match target="font">
<edit name="embeddedbitmap" mode="assign">
<bool>false</bool>
</edit>
</match>
</fontconfig>
To disable embedded bitmap fonts for a specific font:
<match target="font">
<test qual="any" name="family">
<string>Monaco</string>
</test>
<edit name="embeddedbitmap"><bool>false</bool></edit>
</match>
Disable scaling of bitmap fonts
To disable scaling of bitmap fonts (which often makes them blurry), remove/etc/fonts/conf.d/10-scale-bitmap-fonts.conf.
Create bold and italic styles for incomplete fonts
Freetype has the ability to automatically create italic and bold styles for fonts that do not have them, but only if explicitly required by the application. Given programs rarely send these requests, this section covers manually forcing generation of missing styles.Start by editing
/usr/share/fonts/fonts.cache-1 as explained below. Store a copy of the modifications on another file, because a font update with fc-cache will overwrite /usr/share/fonts/fonts.cache-1.
Assuming the Dupree font is installed:
"dupree.ttf" 0 "Dupree:style=Regular:slant=0:weight=80:width=100:foundry=unknown:index=0:outline=True:etc...Duplicate the line, change
style=Regular to style=Bold or any other style. Also change slant=0 to slant=100 for italic, weight=80 to weight=200 for bold, or combine them for bold italic:
"dupree.ttf" 0 "Dupree:style=Bold Italic:slant=100:weight=200:width=100:foundry=unknown:index=0:outline=True:etc...Now add necessary modifications to
$XDG_CONFIG_HOME/fontconfig/fonts.conf:
...
<match target="font">
<test name="family" qual="any">
<string>Dupree</string>
<!-- other fonts here .... -->
</test>
<test name="weight" compare="more_eq"><int>140</int></test>
<edit name="embolden" mode="assign"><bool>true</bool></edit>
</match>
<match target="font">
<test name="family" qual="any">
<string>Dupree</string>
<!-- other fonts here .... -->
</test>
<test name="slant" compare="more_eq"><int>80</int></test>
<edit name="matrix" mode="assign">
<times>
<name>matrix</name>
<matrix>
<double>1</double><double>0.2</double>
<double>0</double><double>1</double>
</matrix>
</times>
</edit>
</match>
...
Tip: Use the value 'embolden' for existing bold fonts in order to make them even bolder.
Change rule overriding
Fontconfig processes files in/etc/fonts/conf.d
in numerical order. This enables rules or files to override one
another, but often confuses users about what file gets parsed last.
To guarantee that personal settings take precedence over any other rules, change their ordering:
# cd /etc/fonts/conf.d # mv 50-user.conf 99-user.confThis change seems however to be unnecessary for the most of the cases, because a user is given enough control by default to set up own font preferences, hinting and antialiasing properties, alias new fonts to generic font families, etc.
Example fontconfig configurations
Example fontconfig configurations can be found on this page.A simple starting point:
$XDG_CONFIG_HOME/fontconfig/fonts.conf
<?xml version='1.0'?> <!DOCTYPE fontconfig SYSTEM 'fonts.dtd'> <fontconfig> <match target="font"> <edit mode="assign" name="antialias"> <bool>true</bool> </edit> <edit mode="assign" name="embeddedbitmap"> <bool>false</bool> </edit> <edit mode="assign" name="hinting"> <bool>true</bool> </edit> <edit mode="assign" name="hintstyle"> <const>hintslight</const> </edit> <edit mode="assign" name="lcdfilter"> <const>lcddefault</const> </edit> <edit mode="assign" name="rgba"> <const>rgb</const> </edit> </match> </fontconfig>
Patched packages
These patched packages are available in the AUR. A few considerations:- Configuration is usually necessary.
- The new font rendering will not kick in until applications restart.
- Applications which statically link to a library will not be affected by patches applied to the system library.
Infinality
The infinality patchset aims to greatly improve freetype2 font rendering. It adds multiple new capabilities.Infinality's settings are all configurable at runtime via environment variables in
/etc/profile.d/infinality-settings.sh, and include the following:
- Emboldening Enhancement: Disables Y emboldening, producing a much nicer result on fonts without bold versions. Works on native TT hinter and autohinter.
- Auto-Autohint: Automatically forces autohint on fonts that contain no TT instructions.
- Autohint Enhancement: Makes autohint snap horizontal stems to pixels. Gives a result that appears like a well-hinted truetype font, but is 100% patent-free (as far as I know).
- Customized FIR Filter: Select your own filter values at run-time. Works on native TT hinter and autohinter.
- Stem Alignment: Aligns bitmap glyphs to optimized pixel boundaries. Works on native TT hinter and autohinter.
- Pseudo Gamma Correction: Lighten and darken glyphs at a given value, below a given size. Works on native TT hinter and autohinter.
- Embolden Thin Fonts: Embolden thin or light fonts so that they are more visible. Works on autohinter.
- Force Slight Hinting: Force slight hinting even when programs want full hinting. If you use the local.conf I provide (included in infinality-settings fedora package) you will notice nice improvements on @font-face fonts.
- ChromeOS Style Sharpening: ChromeOS uses a patch to sharpen the look of fonts. This is now included in the infinality patchset.
/etc/profile.d/infinality-settings.sh.
Installation and configuration
Tip: All AUR packages in this section can also be downloaded from bohoomil's custom repository. See the section below for how to enable this repository.
Note: If
you have been using fontconfig-infinality-ultimate < 2.11.0-2, you
need to re-install (not upgrade!) fontconfig-infinality-ultimate
package:
freetype2-infinality can be installed from the AUR. If you are a multilib user, also install lib32-freetype2-infinality from the AUR. The AUR also contains the latest development snapshot of freetype2 with the Infinality patchset: freetype2-infinality-git and lib32-freetype2-infinality-git.
pacman -Rdd fontconfig-infinality-ultimate pacman -S fontconfig-infinality-ultimate
It is recommended to also install fontconfig-infinality to enable selection of predefined font substitution styles and antialiasing settings, apart from the rendering settings of the engine itself. After doing so, you can select the font style (win7, winxp, osx, linux, ...) with:
# infctl setstyleIf you set e.g. win7 or osx you need the corresponding fonts installed.
Note:
for more information see this article: http://www.infinality.net/forum/viewtopic.php?f=2&t=77
- The user bohoomil maintains a very good configuration in his github repo which is available as fontconfig-infinality-ultimate-git in the AUR.
- Install grip-git from the AUR to have a realtime font preview.
- Default infinality settings can cause some programs to display fonts at 72 DPI instead of 96. If you notice a problem open
/etc/fonts/infinality/infinality.confsearch for the section on DPI and change 72 to 96. This problem can specifically affect conky causing the fonts to appear smaller than they should. Thus not aligning properly with images. - The README for fontconfig-infinality says that /etc/fonts/local.conf should either not exist, or have no infinality-related configurations in it. The local.conf is now obsolete and completely replaced by this configuration.
Install from custom repository
bohoomil also maintains infinality-bundle repository, offering three basic libraries (freetype2-infinality-ultimate, fontconfig-infinality-ultimate & cairo-infinality-ultimate) as pre-patched, pre-configured and pre-built binaries for all architectures (i686, x86_64, multilib). There is also an additional repository avaiable, infinality-bundle-fonts, offering a collection of entirely free, high quality typefaces, replacing common proprietary font families. Using infinality-bundle and infinality-bundle-fonts makes the whole installation and configuration process dramatically simplified (i.e., it lets you skip most steps necessary to install and configure fonts in your system).Please, see Infinality-bundle+fonts for more information and installation instructions.
Ubuntu
Ubuntu adds extra configurations, and occasionally patches to the font rendering libraries.Install the patched packages from the AUR, the package names are: freetype2-ubuntu fontconfig-ubuntu cairo-ubuntu.
The global configuration will need to be added. See #Example fontconfig configurations for a starting point. Ubuntu rendering works the best with hintslight option.
Note that the *-ubuntu AUR packages need to be kept up-to-date by the user, and will not be updated by pacman along with other packages. The whole graphical system can become inoperable if the user-installed core graphical libraries become incompatible with the official repository applications.
Reverting to unpatched packages
To restore the unpatched packages, reinstall the originals:# pacman -S --asdeps freetype2 cairo fontconfigAppend 'lib32-cairo lib32-fontconfig lib32-freetype2' if you also installed 32 bit versions.
Applications without fontconfig support
Some applications like URxvt will ignore fontconfig settings. This is very apparent when using the infinality patches which are heavily reliant on proper configuration. You can work around this by using~/.Xresources, but it is not nearly as flexible as fontconfig. Example (see #Fontconfig configuration for explanations of the options):
~/.Xresources
Xft.autohint: 0 Xft.lcdfilter: lcddefault Xft.hintstyle: hintfull Xft.hinting: 1 Xft.antialias: 1 Xft.rgba: rgbMake sure the settings are loaded properly when X starts with
xrdb -q (see Xresources for more information).
Troubleshooting
Distorted fonts
Note: 96
DPI is not a standard. You should use your monitor's actual DPI to get
proper font rendering, especially when using subpixel rendering.
If fonts are still unexpectedly large or small, poorly proportioned
or simply rendering poorly, fontconfig may be using the incorrect DPI.
Fontconfig should be able to detect DPI parameters as discovered by the Xorg server. You can check the automatically discovered DPI with
xdpyinfo (provided by the xorg-xdpyinfo package):
$ xdpyinfo | grep dots
resolution: 102x102 dots per inchIf the DPI is detected incorrectly (usually due to an incorrect monitor EDID), you can specify it manually in the Xorg configuration, see Xorg#Display size and DPI. This is the recommended solution, but it may not work with buggy drivers.
Fontconfig will default to the Xft.dpi variable if it is set. Xft.dpi is usually set by desktop environments (usually to Xorg's DPI setting) or manually in
~/.Xdefaults or ~/.Xresources. Use xrdb to query for the value:
$ xrdb -query | grep dpi
Xft.dpi: 102Those still having problems can fall back to manually setting the DPI used by fontconfig:
... <match target="pattern"> <edit name="dpi" mode="assign"><double>102</double></edit> </match> ...
Calibri, Cambria, Monaco, etc. not rendering properly
Some scalable fonts have embedded bitmap versions which are rendered instead, mainly at smaller sizes. Force using scalable fonts at all sizes by #Disabling embedded bitmap.Older GTK and QT applications
Modern GTK apps enable Xft by default but this was not the case before version 2.2. If it is not possible to update these applications, force Xft for old GNOME applications by adding to~/.bashrc:
export GDK_USE_XFT=1For older QT applications:
export QT_XFT=true
Applications overriding hinting
Some applications may override default fontconfig hinting and anti-aliasing settings. This may happen with Gnome 3, for example while you are using QT applications like vlc,smplayer. Use the specific configuration program for the application in such cases. For gnome, try gnome-tweak-tool and set the anti-aliasing to rgba instead of the default grayscale while using infinality.See also
- Fonts in X11R6.8.2 - Official Xorg font information
- FreeType 2 overview
- Gentoo font-rendering thread
Tuesday, April 1, 2014
How to Read and Write UTF-8 File in Java?
The
InputStreamReader and the OutputStreamWriter support UTF-8 character encoding. Here is example code:public class Program {
public static void main(String... args) {
if (args.length != 2) {
return ;
}
try {
Reader reader = new InputStreamReader(
new FileInputStream(args[0]),"UTF-8");
BufferedReader fin = new BufferedReader(reader);
Writer writer = new OutputStreamWriter(
new FileOutputStream(args[1]), "UTF-8");
BufferedWriter fout = new BufferedWriter(writer);
String s;
while ((s=fin.readLine())!=null) {
fout.write(s);
fout.newLine();
}
//Remember to call close.
//calling close on a BufferedReader/BufferedWriter
// will automatically call close on its underlying stream
fin.close();
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You can run it:
c:\>java Program inputfilename outputfilename
Also, you can use
Scanner which is provided by Java 5.0 to read UTF-8 file.Saturday, March 29, 2014
AES Encrypt String in VB.NET
This is example code for AES Encrypted String:
Public Function AES_Encrypt(ByVal input As String, ByVal pass As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim encrypted As String = ""
Try
Dim hash(31) As Byte
Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
Array.Copy(temp, 0, hash, 0, 16)
Array.Copy(temp, 0, hash, 15, 16)
AES.Key = hash
AES.Mode = Security.Cryptography.CipherMode.ECB
Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Return encrypted
Catch ex As Exception
End Try
End Function
Public Function AES_Decrypt(ByVal input As String, ByVal pass As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim decrypted As String = ""
Try
Dim hash(31) As Byte
Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
Array.Copy(temp, 0, hash, 0, 16)
Array.Copy(temp, 0, hash, 15, 16)
AES.Key = hash
AES.Mode = Security.Cryptography.CipherMode.ECB
Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateDecryptor
Dim Buffer As Byte() = Convert.FromBase64String(input)
decrypted = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Return decrypted
Catch ex As Exception
End Try
End Function
Public Function AES_Encrypt(ByVal input As String, ByVal pass As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim encrypted As String = ""
Try
Dim hash(31) As Byte
Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
Array.Copy(temp, 0, hash, 0, 16)
Array.Copy(temp, 0, hash, 15, 16)
AES.Key = hash
AES.Mode = Security.Cryptography.CipherMode.ECB
Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Return encrypted
Catch ex As Exception
End Try
End Function
Public Function AES_Decrypt(ByVal input As String, ByVal pass As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim decrypted As String = ""
Try
Dim hash(31) As Byte
Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
Array.Copy(temp, 0, hash, 0, 16)
Array.Copy(temp, 0, hash, 15, 16)
AES.Key = hash
AES.Mode = Security.Cryptography.CipherMode.ECB
Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateDecryptor
Dim Buffer As Byte() = Convert.FromBase64String(input)
decrypted = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Return decrypted
Catch ex As Exception
End Try
End Function
Friday, March 28, 2014
How to Catching the close button event click
This is an example code for knowing when we click on close button:
Example 1:
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
MessageBox.Show("Closing Form")
End Sub
Example 2:
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If boolCloseByButton Then
'Closed by a different button
Else
'Closed by the x on the form
End If
End Sub
Example 3:
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
'You could put a Select Case statement here and take action for all
'different types of closing conditions.
If e.CloseReason = System.Windows.Forms.CloseReason.UserClosing Then
'Closed by the x on the form or Alt-F4
Else
'Closed for some other reason
End If
End Sub
Wednesday, March 26, 2014
hex to string conversion
This is an example of hex to string:
Function HexToString(ByVal hex As String) As String Dim text As New System.Text.StringBuilder(hex.Length \ 2) For i As Integer = 0 To hex.Length - 2 Step 2 text.Append(Chr(Convert.ToByte(hex.Substring(i, 2), 16))) Next Return text.ToString End Function
How to use:
Console.WriteLine(HexToString("73696D306E"))
Tuesday, March 25, 2014
Getting JSTL to run within Tomcat and Eclipse
It's very simple to include jstl in your projects, what I do is:
- Download jstl-1.2.jar (JSP 2.1 containers only i.e. Tomcat 6, otherwise jstl-1.1.jar) fromhttp://repo1.maven.org/maven2/javax/servlet/jstl/1.2/
or
the interfaces (javax.servlet.jsp.jstl-api-1.2.1.jar) from http://search.maven.org/#browse|707331597and the actual implementing classes (javax.servlet.jsp.jstl-1.2.2.jar) fromhttp://search.maven.org/#browse%7C-1002239589. - Copy to your project's WEB-INF/lib directory
- Include the following tags in yours jsp's:
- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
- <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
- <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
- <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
As for eclipse I need to know if your using any framework plugin, I use MyEclipse and it does it automatically for me.
Friday, March 21, 2014
VB.NET Split
The Split function separates Strings. It receives a string or character delimiter. It parses and separates the source string by separating the parts that come between the delimiter. It is used often in VB.NET programs.
Notes:Input string = "Dot Net Perls".
Delimiter = space.
Output array = "Dot" "Net" "Perls".
Delimiter = space.
Output array = "Dot" "Net" "Perls".
Example
To start, we split a VB.NET String based on a space character. We allocate a New Char array as well as a String array to store the words. Finally we loop over the Strings and display them to the Console.
Char ArrayString ArrayProgram that uses Split on String: VB.NET
Module Module1
Sub Main()
' We want to split this input string
Dim s As String = "there is a cat"
' Split string based on spaces
Dim words As String() = s.Split(New Char() {" "c})
' Use For Each loop over words and display them
Dim word As String
For Each word In words
Console.WriteLine(word)
Next
End Sub
End Module
Output
there
is
a
cat
File path parts
Continuing on, we Split a file system path into separate parts using Visual Basic .NET. We use a New Char array with one string, "\""c. We then loop through and display the results.
Program that splits file path: VB.NET
Module Module1
Sub Main()
' The file system path we need to split
Dim s As String = "C:\Users\Sam\Documents\Perls\Main"
' Split the string on the backslash character
Dim parts As String() = s.Split(New Char() {"\"c})
' Loop through result strings with For Each
Dim part As String
For Each part In parts
Console.WriteLine(part)
Next
End Sub
End Module
Output
C:
Users
Sam
Documents
Perls
Main
Regex.Split words
Often you need to extract the words from a String or sentence. The code here needs to handle punctuation and non-word characters differently than the String Split method. Here we use Regex.Split to parse the words.
Program that splits words: VB.NET
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
' Declare iteration variable
Dim s As String
' Loop through words in string
Dim arr As String() = SplitWords("That is a cute cat, man!")
' Display each word. Note that punctuation is handled correctly.
For Each s In arr
Console.WriteLine(s)
Next
Console.ReadLine()
End Sub
''' <summary>
''' Split the words in string on non-word characters.
''' This means commas and periods are handled correctly.
''' </summary>
Private Function SplitWords(ByVal s As String) As String()
'
' Call Regex.Split function from the imported namespace.
' Return the result array.
'
Return Regex.Split(s, "\W+")
End Function
End Module
Output
That
is
a
cute
cat
man
In the Main subroutine you can see that two variables are declared. The second variable is a String array that receives the results from the Private Function next. This is the SplitWords Function.
Regex. The Function shown in the example calls the Regex.Split method, which can be accessed with dot notation, with no instance necessary. The second argument to the method is a regular expression pattern.
Regex.Split
Regex pattern. The pattern "\W+" is used, and this means "one or more non-word characters". This pattern will match punctuation and spaces. Therefore all those characters will be used as delimiters.
Note:Regex Functions tend to be slower. They can handle much more complex patterns than the String Split Function.
And:It is best to use the fastest and simplest Function that handles your problem.
File lines
Next, we see one way to Split each line in a file using File.ReadAllLines and Split. We have a comma-separated-values CSV file, and want to print out each value and its row number. It first reads in the file with ReadAllLines.
Then:This function puts each line in the file into an array element. The example Splits on ","c. We show the output of the program.
File HandlingInput file used
frontal,parietal,occipital,temporal
pulmonary artery,aorta,left ventricle
Program that splits lines: VB.NET
Imports System.IO
Module Module1
Sub Main()
Dim i As Integer = 0
' Loop through each line in array returned by ReadAllLines
Dim line As String
For Each line In File.ReadAllLines("example.txt")
' Split line on comma
Dim parts As String() = line.Split(New Char() {","c})
' Loop over each string received
Dim part As String
For Each part In parts
' Display to Console
Console.WriteLine("{0}:{1}", i, part)
Next
i += 1
Next
End Sub
End Module
Output
0:frontal
0:parietal
0:occipital
0:temporal
1:pulmonary artery
1:aorta
1:left ventricle
Summary
We saw some ways to Split your String in VB.NET. Split returns a String array that you can use in a For Each loop. We used Split on different characters and strings. Then we called Regex.Split in a more complex pattern example.
Convert a String to Stream
Why have you converted binary (image) data to a string? This makes no sense... unless you are using base-64?
Anyway, to reverse what you have done, you could try using new MemoryStream(Encoding.UTF8.GetBytes(text))?
This will create a new MemoryStream primed with the string (via UTF8). Personally, I doubt it will work - you are going to run into a lot of encoding issues treating raw binary as UTF8 data... I expect either the read or write (or both) to throw an exception.
(edit)
I should add that to work with base-64, simply get the data as a byte[], then call Convert.ToBase64String(...); and to get back the array, just use Convert.FromBase64String(...).
Re your edit, this is precisely what I tried to warn about above... in .NET, a string is not just a byte[], so you can't simply fill it with binary image data. A lot of the data simply won't make sense to the encoding, so might be quietly dropped (or an exception thrown).
To handle raw binary (such as images) as strings, you need to use base-64 encoding; this adds size, however. Note that WebClient might make this simpler, as it exposes byte[] functionality directly:
using(WebClient wc = new WebClient()) {
byte[] raw = wc.DownloadData("http://www.google.com/images/nav_logo.png")
//...
}
Anyway, using a standard Stream approach, here's how to encode and decode the base-64:
// ENCODE
// where "s" is our original stream
string base64;
// first I need the data as a byte[]; I'll use
// MemoryStream, as a convenience; if you already
// have the byte[] you can skip this
using (MemoryStream ms = new MemoryStream())
{
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = s.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, bytesRead);
}
base64 = Convert.ToBase64String(ms.GetBuffer(), 0, (int) ms.Length);
}
// DECODE
byte[] raw = Convert.FromBase64String(base64);
using (MemoryStream decoded = new MemoryStream(raw))
{
// "decoded" now primed with the binary
}
Anyway, to reverse what you have done, you could try using new MemoryStream(Encoding.UTF8.GetBytes(text))?
This will create a new MemoryStream primed with the string (via UTF8). Personally, I doubt it will work - you are going to run into a lot of encoding issues treating raw binary as UTF8 data... I expect either the read or write (or both) to throw an exception.
(edit)
I should add that to work with base-64, simply get the data as a byte[], then call Convert.ToBase64String(...); and to get back the array, just use Convert.FromBase64String(...).
Re your edit, this is precisely what I tried to warn about above... in .NET, a string is not just a byte[], so you can't simply fill it with binary image data. A lot of the data simply won't make sense to the encoding, so might be quietly dropped (or an exception thrown).
To handle raw binary (such as images) as strings, you need to use base-64 encoding; this adds size, however. Note that WebClient might make this simpler, as it exposes byte[] functionality directly:
using(WebClient wc = new WebClient()) {
byte[] raw = wc.DownloadData("http://www.google.com/images/nav_logo.png")
//...
}
Anyway, using a standard Stream approach, here's how to encode and decode the base-64:
// ENCODE
// where "s" is our original stream
string base64;
// first I need the data as a byte[]; I'll use
// MemoryStream, as a convenience; if you already
// have the byte[] you can skip this
using (MemoryStream ms = new MemoryStream())
{
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = s.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, bytesRead);
}
base64 = Convert.ToBase64String(ms.GetBuffer(), 0, (int) ms.Length);
}
// DECODE
byte[] raw = Convert.FromBase64String(base64);
using (MemoryStream decoded = new MemoryStream(raw))
{
// "decoded" now primed with the binary
}
Subscribe to:
Comments (Atom)