Search Results

Search found 246 results on 10 pages for 'addhandler'.

Page 10/10 | < Previous Page | 6 7 8 9 10 

  • Problem monitoring directory for file activity in VB.net 2010...

    - by Mike Cialowicz
    I'm trying to write a simple program to monitor a folder for new files in VB.NET 2010, and am having some trouble. Here's a simplified version of what my program looks like: Imports System.IO Public Class Main Public fileWatcher As FileSystemWatcher Sub btnGo_Click(sender As System.Object, e As System.EventArgs) Handles btnGo.Click '//# initialize my FileSystemWatcher to monitor a particular directory for new files fileWatcher = New FileSystemWatcher() fileWatcher.Path = thisIsAValidPath.ToString() fileWatcher.NotifyFilter = NotifyFilters.FileName AddHandler fileWatcher.Created, AddressOf fileCreated fileWatcher.EnableRaisingEvents = True End Sub Private Sub fileCreated(sender As Object, e As FileSystemEventArgs) '//# program does not exit when I comment the line below out txtLatestAddedFilePath.Text = e.FullPath '//# e.FullPath is valid when I set a breakpoint here, but when I step into the next line, the program abruptly halts with no error code that I can see End Sub End Class As you can see, I have a button which will initialize a FileSystemWatcher when clicked. The initialization works, and when I place a new file in the monitored directory, the program reaches the fileCreated sub. I can even see that e.FullPath is set correctly. However, it exits abruptly right after that with no error code (none that I can see, anyways). If I comment everything in the fileCreated sub out, the program continues running as expected. Any ideas as to why it's dying on me? Any help would be greatly appreciated. I'm fairly new to VS/VB.NET, so maybe I'm just making a silly mistake. Thanks!

    Read the article

  • Django rewrites URL as IP address in browser - why?

    - by Mitch
    I am using django, nginx and apache. When I access my site with a URL (e.g., http://www.foo.com/) what appears in my browser address is the IP address with admin appended (e.g., http://123.45.67.890/admin/). When I access the site by IP, it is redirected as expected by django's urls.py (e.g., http://123.45.67.890/ - http://123.45.67.890/accounts/login/?next=/) I would like to have the name URL act the same way as the IP. That is, if the URL goes to a new view, the host in the browser address should remain the same and not change to the IP address. Where should I be looking to fix this? My files: ; cpa.com (apache) NameVirtualHost *:8080 <VirtualHost *:8080> AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/x-javascript BrowserMatch ^Mozilla/4 gzip-only-text/html BrowserMatch ^Mozilla/4\.0[678] no-gzip BrowserMatch \bMSIE !no-gzip !gzip-only-text/htm DocumentRoot /path/to/root ServerName www.foo.com <IfModule mod_rpaf.c> RPAFenable On RPAFsethostname On RPAFproxy_ips 127.0.0.1 </IfModule> <Directory /public/static> AllowOverride None AddHandler mod_python .py PythonHandler mod_python.publisher </Directory> Alias / /dj <Location /> SetHandler python-program PythonPath "['/usr/lib/python2.5/site-packages/django', '/usr/lib/python2.5/site-packages/django/forms'] + sys.path" PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE dj.settings PythonDebug On </Location> </VirtualHost> ; ; ports.conf (apache) Listen 127.0.0.1:8080 ; ; cpa.conf (nginx) server { listen 80; server_name www.foo.com; location /static { root /var/public; index index.html; } location /cpa/js { root /var/public/js; } location /cpa/css { root /var/public/css; } location /djmedia { alias "/usr/lib/python2.5/site-packages/django/contrib/admin/media/"; } location / { include /etc/nginx/proxy.conf; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://127.0.0.1:8080; } } ; ; proxy.conf (nginx) proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 10m; client_body_buffer_size 128k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 500; proxy_buffers 32 4k;

    Read the article

  • How to stop a random ramp in FCGI Processes Killing the server

    - by Andy Main
    So got the below earlier to day... Around that time the logs show a ramp in processes(600) and associated memory (1.2g), cpu usage load average (80) untill the server gave out. Server had to be hard reset by host as there was no ssh or plesk panel access. Fast CGI is configured as below and is setup for one high use site. As I understand it FcgidMaxProcesses 20 should protect against what happen but has not. I've read many forums with differing answers and references to many different fcgi directives, but have found nothing conclusive. Any one got some definitive answers on how to stop this sort of server process ramping and subsequent server failure? If you need more info let me know. Cheers Andy  /var/log/apache2/error_log [Thu May 17 07:40:47 2012] [warn] mod_fcgid: process 17651 graceful kill fail, sending SIGKILL [Thu May 17 07:40:47 2012] [warn] mod_fcgid: process 17650 graceful kill fail, sending SIGKILL [Thu May 17 07:40:47 2012] [warn] mod_fcgid: process 17649 graceful kill fail, sending SIGKILL [Thu May 17 07:40:47 2012] [warn] mod_fcgid: process 17644 graceful kill fail, sending SIGKILL [Thu May 17 07:40:47 2012] [warn] mod_fcgid: process 17643 graceful kill fail, sending SIGKILL [Thu May 17 07:40:47 2012] [warn] mod_fcgid: process 17638 graceful kill fail, sending SIGKILL [Thu May 17 07:40:47 2012] [warn] mod_fcgid: process 17633 graceful kill fail, sending SIGKILL [Thu May 17 07:40:47 2012] [warn] mod_fcgid: process 17627 graceful kill fail, sending SIGKILL [Thu May 17 07:40:47 2012] [warn] mod_fcgid: process 17622 graceful kill fail, sending SIGKILL [Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17674 graceful kill fail, sending SIGKILL [Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17673 graceful kill fail, sending SIGKILL [Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17672 graceful kill fail, sending SIGKILL [Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17667 graceful kill fail, sending SIGKILL [Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17666 graceful kill fail, sending SIGKILL [Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17665 graceful kill fail, sending SIGKILL [Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17664 graceful kill fail, sending SIGKILL [Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17659 graceful kill fail, sending SIGKILL [Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17658 graceful kill fail, sending SIGKILL [Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17657 graceful kill fail, sending SIGKILL [Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17656 graceful kill fail, sending SIGKILL [Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17651 graceful kill fail, sending SIGKILL https://docs.google.com/a/thesugarrefinery.com/open?id=0B_XbpWChge0VRmFLWEZfR2VBb2M https://docs.google.com/a/thesugarrefinery.com/open?id=0B_XbpWChge0VWTcwZEhoV2Fqejg https://docs.google.com/a/thesugarrefinery.com/open?id=0B_XbpWChge0VUUtVWWFINHZjZ0U https://docs.google.com/a/thesugarrefinery.com/open?id=0B_XbpWChge0VZEVMclh6ZUdaOUE <IfModule mod_fcgid.c> <IfModule !mod_fastcgi.c> AddHandler fcgid-script fcg fcgi fpl </IfModule> FcgidIPCDir /var/lib/apache2/fcgid/sock FcgidProcessTableFile /var/lib/apache2/fcgid/shm FcgidIdleTimeout 40 FcgidProcessLifeTime 30 FcgidMaxProcesses 20 FcgidMaxProcessesPerClass 20 FcgidMinProcessesPerClass 0 FcgidConnectTimeout 30 FcgidIOTimeout 120 FcgidInitialEnv RAILS_ENV production FcgidIdleScanInterval 10 FcgidMaxRequestLen 1073741824 </IfModule>

    Read the article

  • First time installing Linux/Apache - uanble to connect

    - by bob
    I's my first time installing Linux/Apache. I loaded CentOS and LAMPP on a machine attached to a LAN. Turned off http and mysql (because I didn't want conflict with LLAMPP) chkconfig httpd off chkconfig mysqld off then successfully LAMPP started with /opt/lampp/lampp start Starting XAMPP for Linux 1.7.3a... XAMPP: Starting Apache with SSL (and PHP5)... XAMPP: Starting MySQL... XAMPP: Starting ProFTPD... XAMPP for Linux started. Problem: Unable to connect - Firefox can't establish a connection to the server at 179.16.51.36. I need some pointers as to where to look next. No errors in error_log file (just some warnings) I can ping server. httpd.conf looks like this: ServerRoot "/opt/lampp" Listen 80 ServerAdmin [email protected] ServerName 179.16.51.36 DocumentRoot "/opt/lampp/htdocs" <Directory /> Options FollowSymLinks AllowOverride None </Directory> <Directory "/opt/lampp/htdocs"> Options Indexes FollowSymLinks ExecCGI Includes Order allow,deny Allow from all </Directory> ErrorLog logs/error_log LogLevel warn <IfModule log_config_module> LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common <IfModule logio_module> LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio </IfModule> CustomLog logs/access_log common </IfModule> <IfModule alias_module> ScriptAlias /cgi-bin/ "/opt/lampp/cgi-bin/" </IfModule> <IfModule cgid_module> </IfModule> <Directory "/opt/lampp/cgi-bin"> AllowOverride None Options None Order allow,deny Allow from all </Directory> DefaultType text/plain <IfModule mime_module> TypesConfig etc/mime.types AddType application/x-compress .Z AddType application/x-gzip .gz .tgz AddHandler cgi-script .cgi .pl AddType text/html .shtml AddOutputFilter INCLUDES .shtml </IfModule> EnableMMAP off EnableSendfile off

    Read the article

  • Convert apache rewrite rules to nginx

    - by Shiyu Sekam
    I want to migrate an Apache setup to Nginx, but I can't get the rewrite rules working in Nginx. I had a look on the official nginx documentation, but still some trouble converting it. http://nginx.org/en/docs/http/converting_rewrite_rules.html I've used http://winginx.com/en/htaccess to convert my rules, but this just works partly. The / part looks okay, the /library part as well, but the /public part doesn't work at all. Apache part: ServerAdmin webmaster@localhost DocumentRoot /srv/www/Web Order allow,deny Allow from all RewriteEngine On RewriteRule ^$ public/ [L] RewriteRule (.*) public/$1 [L] Order Deny,Allow Deny from all RewriteEngine On RewriteCond %{QUERY_STRING} ^pid=([0-9]*)$ RewriteRule ^places(.*)$ index.php?url=places/view/%1 [PT,L] # Extract search query in /search?q={query}&l={location} RewriteCond %{QUERY_STRING} ^q=(.*)&l=(.*)$ RewriteRule ^(.*)$ index.php?url=search/index/%1/%2 [PT,L] # Extract search query in /search?q={query} RewriteCond %{QUERY_STRING} ^q=(.*)$ RewriteRule ^(.*)$ index.php?url=search/index/%1 [PT,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # Rewrite all other URLs to index.php/URL RewriteRule ^(.*)$ index.php?url=$1 [PT,L] Order deny,allow deny from all ErrorLog ${APACHE_LOG_DIR}/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn AddHandler php5-fcgi .php Action php5-fcgi /php5-fcgi Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -socket /var/run/php5-fpm.sock -pass-header Authorization CustomLog ${APACHE_LOG_DIR}/access.log combined Nginx config: server { #listen 80; ## listen for ipv4; this line is default and implied root /srv/www/Web; index index.html index.php; server_name localhost; location / { rewrite ^/$ /public/ break; rewrite ^(.*)$ /public/$1 break; } location /library { deny all; } location /public { if ($query_string ~ "^pid=([0-9]*)$"){ rewrite ^/places(.*)$ /index.php?url=places/view/%1 break; } if ($query_string ~ "^q=(.*)&l=(.*)$"){ rewrite ^(.*)$ /index.php?url=search/index/%1/%2 break; } if ($query_string ~ "^q=(.*)$"){ rewrite ^(.*)$ /index.php?url=search/index/%1 break; } if (!-e $request_filename){ rewrite ^(.*)$ /index.php?url=$1 break; } } location ~ \.php$ { fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; include fastcgi_params; } } I haven't written the original ruleset, so I've a hard time converting it. Would you mind giving me a hint how to do it easily or can you help me to convert it, please? I really want to switch over to php5-fpm and nginx :) Thanks

    Read the article

  • ReSharper C# Live Template for Read-Only Dependency Property and Routed Event Boilerplate

    - by Bart Read
    Following on from my previous post, where I shared a Live Template for quickly declaring a normal read-write dependency property and its associated property change event boilerplate, here's an unsurprisingly similar template for creating a read-only dependency property.        #region $PROPNAME$ Read-Only Property and Property Change Routed Event        private static readonly DependencyPropertyKey $PROPNAME$PropertyKey =                                             DependencyProperty.RegisterReadOnly(             "$PROPNAME$", typeof ( $PROPTYPE$ ), typeof ( $DECLARING_TYPE$ ),             new PropertyMetadata( $DEF_VALUE$ , On$PROPNAME$Changed ) );       public static readonly DependencyProperty $PROPNAME$Property =                                           $PROPNAME$PropertyKey.DependencyProperty;        public $PROPTYPE$ $PROPNAME$         {             get { return ( $PROPTYPE$ ) GetValue( $PROPNAME$Property ); }             private set { SetValue( $PROPNAME$PropertyKey, value ); }         }       public static readonly RoutedEvent $PROPNAME$ChangedEvent   =                                           EventManager.RegisterRoutedEvent(           "$PROPNAME$Changed",           RoutingStrategy.$ROUTINGSTRATEGY$,           typeof( RoutedPropertyChangedEventHandler< $PROPTYPE$ > ),           typeof( $DECLARING_TYPE$ ) );       public event RoutedPropertyChangedEventHandler< $PROPTYPE$ > $PROPNAME$Changed       {           add { AddHandler( $PROPNAME$ChangedEvent, value ); }           remove { RemoveHandler( $PROPNAME$ChangedEvent, value ); }       }        private static void On$PROPNAME$Changed(           DependencyObject d, DependencyPropertyChangedEventArgs e)         {             var $DECLARING_TYPE_var$ = d as $DECLARING_TYPE$;            var args = new RoutedPropertyChangedEventArgs< $PROPTYPE$ >(               ( $PROPTYPE$ ) e.OldValue,               ( $PROPTYPE$ ) e.NewValue );           args.RoutedEvent    = $DECLARING_TYPE$.$PROPNAME$ChangedEvent;           $DECLARING_TYPE_var$.RaiseEvent( args );$END$        }        #endregion The only real difference here is the addition of the DependencyPropertyKey, which allows your implementation to set the value of the dependency property without exposing the setter code to consumers of your type. You'll probably find that you create read-only dependency properties much less often than read-write properties, but this should still save you some typing when you do need to do so. Technorati Tags: resharper,live template,c#,dependency property,read-only,routed events,property change,boilerplate,wpf

    Read the article

  • How can I load style resources from a dynamically loaded Silverlight application (XAP)?

    - by Tom
    I've followed Tim Heuer's video for dynamically loading other XAP's (into a 'master' Silverlight application), as well as some other links to tweak the loading of resources and am stuck on the particular issue of loading style resources from within the dynamically loaded XAP (i.e. the contents of Assets\Styles.xaml). When I run the master/hosting applcation, it successfully streams the dynamic XAP and I can read the deployment info etc. and load the assembly parts. However, when I actuall try to create an instance of a form from the Dynamic XAP, it fails with Cannot find a Resource with the Name/Key LayoutRootGridStyle which is in it's Assets\Styles.xaml file (it works if I run it directly so I know it's OK). For some reason these don't show up as application resources - not sure if I've totally got the wrong end of the stick, or am just missing something? Code snippet below (apologies it's a bit messy - just trying to get it working first) ... '' # Here's the code that reads the dynamic XAP from the web server ... '' #... wCli = New WebClient AddHandler wCli.OpenReadCompleted, AddressOf OpenXAPCompleted wCli.OpenReadAsync(New Uri("MyTest.xap", UriKind.Relative)) '' #... '' #Here's the sub that's called when openread is completed '' #... Private Sub OpenXAPCompleted(ByVal sender As Object, ByVal e As System.Net.OpenReadCompletedEventArgs) Dim sManifest As String = New StreamReader(Application.GetResourceStream(New StreamResourceInfo(e.Result, Nothing), New Uri("AppManifest.xaml", UriKind.Relative)).Stream).ReadToEnd Dim deploymentRoot As XElement = XDocument.Parse(sManifest).Root Dim deploymentParts As List(Of XElement) = _ (From assemblyParts In deploymentRoot.Elements().Elements() Select assemblyParts).ToList() Dim oAssembly As Assembly = Nothing For Each xElement As XElement In deploymentParts Dim asmPart As AssemblyPart = New AssemblyPart() Dim source As String = xElement.Attribute("Source").Value Dim sInfo As StreamResourceInfo = Application.GetResourceStream(New StreamResourceInfo(e.Result, "application/binary"), New Uri(source, UriKind.Relative)) If source = "MyTest.dll" Then oAssembly = asmPart.Load(sInfo.Stream) Else asmPart.Load(sInfo.Stream) End If Next Dim t As Type() = oAssembly.GetTypes() Dim AppClass = (From parts In t Where parts.FullName.EndsWith(".App") Select parts).SingleOrDefault() Dim mykeys As Array If Not AppClass Is Nothing Then Dim a As Application = DirectCast(oAssembly.CreateInstance(AppClass.FullName), Application) For Each strKey As String In a.Resources.Keys If Not Application.Current.Resources.Contains(strKey) Then Application.Current.Resources.Add(strKey, a.Resources(strKey)) End If Next End If Dim objectType As Type = oAssembly.GetType("MyTest.MainPage") Dim ouiel = Activator.CreateInstance(objectType) Dim myData As UIElement = DirectCast(ouiel, UIElement) Me.splMain.Children.Add(myData) Me.splMain.UpdateLayout() End Sub '' #... '' # And here's the line that fails with "Cannot find a Resource with the Name/Key LayoutRootGridStyle" '' # ... System.Windows.Application.LoadComponent(Me, New System.Uri("/MyTest;component/MainPage.xaml", System.UriKind.Relative)) '' #... any thoughts?

    Read the article

  • Problems with CGI wrapper for PHP

    - by user205878
    I'm having a bugger of a time with a CGI wrapper for PHP. I know very little about CGI and PHP as CGI. Here's what I know about the system: Solaris 10 on a 386 Suhosin PHP normally running as CGI, with cgiwrap (http://cgiwrap.sourceforge.net/). I am not able to find an example wrapper.cgi on the server to look at. Shared hosting (virtual host), so I don't have access to Apache config. But the admins are not helpful. Switching hosts is not an option. Options directive cannot be overridden in .htaccess (ExecCGI, for example). .htaccess: AddHandler php-handler .php Action php-handler "/bin/test.cgi" ~/public_html/bin/test.cgi: #!/usr/bin/sh # Without these 2 lines, I get an Internal Server Error echo "Content-type: text/html" echo "" exec "/path/to/php-cgi" 'foo.php'; /bin/foo.php: <?php echo "this is foo.php!"; Output of http://mysite.com/bin/test.cgi: X-Powered-By: PHP/5.2.11 Content-type: text/html echo "Content-type: text/html" echo "" exec "/path/to//php-cgi" 'foo.php'; Output of http:/ /mysite.com/anypage.php: X-Powered-By: PHP/5.2.11 Content-type: text/html echo "Content-type: text/html" echo "" exec "/path/to//php-cgi" 'foo.php'; The things I note are: PHP is being executed, as noted by the X-Powered-By ... header. The source of /bin/test.cgi is output in the results. No matter what I put as the second argument of exec, it isn't passed to the php binary. I've tried '-i' to get phpinfo, '-v' to get the version... When I execute test.cgi via the shell, I get the expected results (the argument is passed to php, and it is reflected in the output). Any ideas about how to get this to work? UPDATE It appears that the reason the source of the test.cgi was appearing was due to errors. Anytime fatal error occurred, either within the cgi itself or with the command being executed by exec, it would cause the source of the cgi to appear. Within test.cgi, I can get the proper output with exec "/path/to/php-cgi" -h (I get the same thing as I would from CLI).

    Read the article

  • Crossthread exception and invokerequired solution doesn't change my control value

    - by Pilouk
    EDIT Solution : Here i'm setting my byref value in each object then i'm running a backgroundworker Private Sub TelechargeFichier() Dim DocManquant As Boolean = False Dim docName As String = "" Dim lg As String = "" Dim telechargementFini As Boolean = False lblMessage.Text = EasyDealChangeLanguage.Instance.GetStringFromResourceName("1478") prgBar.Maximum = m_listeFichiers.Count For i As Integer = 0 To m_listeFichiers.Count - 1 m_listeFichiers(i).Set_ByRefLabel(lblMessage) m_listeFichiers(i).Set_ByRefPrgbar(prgBar) m_listeThreads.Add(New Thread(AddressOf m_listeFichiers(i).DownloadMe)) Next m_bgWorker = New BackgroundWorker m_bgWorker.WorkerReportsProgress = True AddHandler m_bgWorker.DoWork, AddressOf DownloadFiles m_bgWorker.RunWorkerAsync() ''Completed 'lblMessage.Text = EasyDealChangeLanguage.Instance.GetStringFromResourceName("1383") 'Me.DialogResult = System.Windows.Forms.DialogResult.OK End Sub Here is my downloadFiles function : Note that each start will do the downloadMe function see below too Private Sub DownloadFiles(sender As Object, e As DoWorkEventArgs) For i As Integer = 0 To m_listeThreads.Count - 1 m_listeThreads(i).Start() Next For i As Integer = 0 To m_listeThreads.Count - 1 m_listeThreads(i).Join() Next End Sub I have multiple thread that each will download a ftp file. I would like that each file that have been completed will set a value to a progress bar and a label from my UI thread. For some reason invokerequired never change to false. Here is my little function that start all the thread Private Sub TelechargeFichier() Dim DocManquant As Boolean = False Dim docName As String = "" Dim lg As String = "" Dim telechargementFini As Boolean = False lblMessage.Text = EasyDealChangeLanguage.Instance.GetStringFromResourceName("1478") prgBar.Maximum = m_listeFichiers.Count For i As Integer = 0 To m_listeFichiers.Count - 1 m_listeFichiers(i).Set_ByRefLabel(lblMessage) m_listeFichiers(i).Set_ByRefPrgbar(prgBar) m_listeThreads.Add(New Thread(AddressOf m_listeFichiers(i).DownloadMe)) Next For i As Integer = 0 To m_listeThreads.Count - 1 m_listeThreads(i).Start() Next For i As Integer = 0 To m_listeThreads.Count - 1 m_listeThreads(i).Join() Next 'Completed lblMessage.Text = EasyDealChangeLanguage.Instance.GetStringFromResourceName("1383") Me.DialogResult = System.Windows.Forms.DialogResult.OK End Sub Here my property that hold the Byref control from the UI thread. This is in my object which content the addressof function that will download the file (DownloadMe) Public Sub Set_ByRefPrgbar(ByRef prgbar As ProgressBar) m_prgBar = prgbar End Sub Public Sub Set_ByRefLabel(ByRef lbl As EasyDeal.Controls.EasyDealLabel3D) m_lblMessage = lbl End Sub Here is the download function : Public Sub DownloadMe() Dim ftpReq As FtpWebRequest Dim ftpResp As FtpWebResponse = Nothing Dim streamInput As Stream Dim fileStreamOutput As FileStream Try ftpReq = CType(WebRequest.Create(EasyDeal.Controls.Common.FTP_CONNECTION & m_downloadFtpPath & m_filename), FtpWebRequest) ftpReq.Credentials = New NetworkCredential(FTP_USER, FTP_PASS) ftpReq.Method = WebRequestMethods.Ftp.DownloadFile ftpResp = ftpReq.GetResponse streamInput = ftpResp.GetResponseStream() fileStreamOutput = New FileStream(m_outputPath, FileMode.Create, FileAccess.ReadWrite) ReadWriteStream(streamInput, fileStreamOutput) Catch ex As Exception 'Au pire la fichier sera pas downloader Finally If ftpResp IsNot Nothing Then ftpResp.Close() End If Dim nomFichier As String = m_displaynameEN If EasyDealChangeLanguage.GetCurrentLanguageTypes = EasyDealChangeLanguage.EnumLanguageType.Francais Then nomFichier = m_displaynameFR End If If m_lblMessage IsNot Nothing Then EasyDealCommon.TH_SetControlText(m_lblMessage, String.Format(EasyDealChangeLanguage.Instance.GetStringFromResourceName("1479"), nomFichier)) End If If m_prgBar IsNot Nothing Then EasyDealCommon.TH_SetPrgValue(m_prgBar, 1) End If End Try End Sub Here is the crossthread invoke solution function : Public Sub TH_SetControlText(ByVal ctl As Control, ByVal text As String) If ctl.InvokeRequired Then ctl.BeginInvoke(New Action(Of Control, String)(AddressOf TH_SetControlText), ctl, text) Else ctl.Text = text End If End Sub Public Sub TH_SetPrgValue(ByVal prg As ProgressBar, ByVal value As Integer) If prg.InvokeRequired Then prg.BeginInvoke(New Action(Of ProgressBar, Integer)(AddressOf TH_SetPrgValue), prg, value) Else prg.Value += value End If End Sub The problem is the invokerequired never get to false it actually goes in to beginInvoke but never end in the Else section to set the value.

    Read the article

  • Key Promoter for NetBeans

    - by Geertjan
    Whenever a menu item or toolbar button is clicked, it would be handy if NetBeans were to tell you 'hey, did you know, you can actually do this via the following keyboard shortcut', if a keyboard shortcut exists for the invoked action. After all, ultimately, a lot of developers would like to do everything with the keyboard and a key promoter feature of this kind is a helpful tool in learning the keyboard shortcuts related to the menu items and toolbar buttons you're clicking with your mouse. Above, you see the balloon message that appears for each menu item and toolbar button that you click and, below, you can see a list of all the actions that have been logged in the Notifications window. That happens automatically when an action is invoked (assuming the plugin described in this blog entry is installed), showing the display name of the action, together with the keyboard shortcut, which is presented as a hyperlink which, when clicked, re-invokes the action (which might not always be relevant, especially for context-sensitive actions, though for others it is quite useful, e.g., reopen the New Project wizard). And here's all the code. Notice that I'm hooking into the 'uigestures' functionality, which was suggested by Tim Boudreau, and I have added my own handler, which was suggested by Jaroslav Tulach, which gets a specific parameter from each new log entry handled by the 'org.netbeans.ui.actions' logger, makes sure that the parameter actually is an action, and then gets the relevant info from the action, if the relevant info exists: @OnShowingpublic class Startable implements Runnable {    @Override    public void run() {        Logger logger = Logger.getLogger("org.netbeans.ui.actions");        logger.addHandler(new StreamHandler() {            @Override            public void publish(LogRecord record) {                Object[] parameters = record.getParameters();                if (parameters[2] instanceof Action) {                    Action a = (Action) parameters[2];                    JMenuItem menu = new JMenuItem();                    Mnemonics.setLocalizedText(                            menu,                             a.getValue(Action.NAME).toString());                    String name = menu.getText();                    if (a.getValue(Action.ACCELERATOR_KEY) != null) {                        String accelerator = a.getValue(Action.ACCELERATOR_KEY).toString();                        NotificationDisplayer.getDefault().notify(                                name,                                 new ImageIcon("/org/nb/kp/car.png"),                                 accelerator,                                 new ActionListener() {                            @Override                            public void actionPerformed(ActionEvent e) {                                a.actionPerformed(e);                            }                        });                    }                }            }        });    }} Indeed, inspired by the Key Promoter in IntelliJ IDEA. Interested in trying it out? If there's interest in it, I'll put it in the NetBeans Plugin Portal.

    Read the article

  • WPF TabItem Custom ContentTemplate

    - by lloydsparkes
    I have been strugging with this for a while, it would have been simple to do in WindowForms. I am making a IRC Client, there will be a number of Tabs one for each channel connect to. Each Tab needs to show a number of things, UserList, MessageHistory, Topic. In WindowForms i would just have inherited from TabItem, added some Custom Properties, and Controls, and done. In WPF i am having some slight issues with working out how to do it. I have tried many ways of doing it, and below is my current method, but i cannot get the TextBox to bind to the Topic Property. <Style TargetType="{x:Type t:IRCTabItem}" BasedOn="{StaticResource {x:Type TabItem}}" > <Setter Property="ContentTemplate"> <Setter.Value> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="540" /> <ColumnDefinition /> </Grid.ColumnDefinitions> <StackPanel Grid.Column="0"> <TextBox Text="{Binding Topic, RelativeSource={RelativeSource AncestorType={x:Type t:IRCTabItem}}}" /> </StackPanel> </Grid> </DataTemplate> </Setter.Value> </Setter> </Style> And the Codebehind public class IRCTabItem : TabItem { static IRCTabItem() { //This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class. //This style is defined in themes\generic.xaml //DefaultStyleKeyProperty.OverrideMetadata(typeof(IRCTabItem), // new FrameworkPropertyMetadata(typeof(IRCTabItem))); } public static readonly RoutedEvent CloseTabEvent = EventManager.RegisterRoutedEvent("CloseTab", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(IRCTabItem)); public event RoutedEventHandler CloseTab { add { AddHandler(CloseTabEvent, value); } remove { RemoveHandler(CloseTabEvent, value); } } public override void OnApplyTemplate() { base.OnApplyTemplate(); Button closeButton = base.GetTemplateChild("PART_Close") as Button; if (closeButton != null) closeButton.Click += new System.Windows.RoutedEventHandler(closeButton_Click); } void closeButton_Click(object sender, System.Windows.RoutedEventArgs e) { this.RaiseEvent(new RoutedEventArgs(CloseTabEvent, this)); } public bool Closeable { get; set; } public static readonly DependencyProperty CloseableProperty = DependencyProperty.Register("Closeable", typeof(bool), typeof(IRCTabItem), new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); public List<String> UserList { get; set; } public static readonly DependencyProperty UserListProperty = DependencyProperty.Register("UserList", typeof(List<String>), typeof(IRCTabItem), new FrameworkPropertyMetadata(new List<String>(), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); public String Topic { get; set; } public static readonly DependencyProperty TopicProperty = DependencyProperty.Register("Topic", typeof(String), typeof(IRCTabItem), new FrameworkPropertyMetadata("Not Connected", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); public bool HasAlerts { get; set; } public static readonly DependencyProperty HasAlertsProperty = DependencyProperty.Register("HasAlerts", typeof(bool), typeof(IRCTabItem), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); } So my questions are: Am i doing it the right way (best practices)? If so how can i bind DataTemplate to Properties? If not so, what is the correct way of achieve what i am trying to achieve?

    Read the article

  • Inconsistent responses from ISAPI DLL in mod_isapi.

    - by William Leader
    I have a ISAPI dll which I created with Delphi 2009, and I have been able to test that it functions as designed when I run it inside of IIS 5.1. However when I attempt to host the web service from within Apache on Windows XP using mod_isapi, I do not get consistent results. The ISAPI dll implements a very simple SOAP service with two methods. One method is a simple echo service that sends back the string sent to it. The second method is used to send a file to the server using a TSoapAttachement (Mutipart MIME). The interface can be descibes as follows IPdiSvc2 = interface(IInvokable) ['{532DCDD7-D66B-4D2C-924E-2F389D3E0A74}'] function Echo(data:string): string; stdcall; function SendFile(request:TFileDescription; attachment: TSOAPAttachment): TSendFileResponse; stdcall; end; What is interesting is if I only call the echo function Apache handles this without error every time. The webservice only returns an error after calling send File, but not every time. There are three outcomes to calling send file that I have observed: A normal result without an error (HTTP 200 OK). A Soap encoded exception with the message: 'Required white space was missing. Line: 11 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML.' (HTTP 500 Internal Error). This also generates a message in the Apache error.log 'Premature end of script headers: MYISAPI.dll' A Soap encoded exception with the message: 'Access violation at address 01A53D57 in module MYISAPI.dll. Read of address 00000000.' (HTTP 200 OK). What I find interesting is that the second third outcomes still occur if I call echo after calling send file. Calling SendFile, SendFile, SendFile, SendFile results in outcomes 1, 2, 3, 1. Calling Echo, SendFile, SendFile, SendFile results in outcomes 1, 1, 2, 3. Calling SendFile, Echo, Echo, SendFile results in outcomes 1, 2, 3, 1. The pattern I am seing is that after a Successful SendFile, the next to requests result in outcomes 2 and 3 regardless of what those two requests are. My guess is that because Apache uses multiple threads to handle multiple requests that each request is getting handled in a slightly different way, and that the DLL may not have been initialized in the same way for each worker thread. I do not think the problem exists in my code as when I attach the debugger to httpd.exe it does recognize the exceptions but it says the exceptions are in non-delphi code meaning that they are happening before the code inside my DLL has a chance to execute. I suspect it may have something to do with the way I have apache configured. My Apache configuration is the defaults created by the 2.2.15 installer for windows with the following addition: <IfModule isapi_module> AddHandler isapi-handler .dll ISAPILogNotSupported on ISAPIFakeAsync on ISAPIAppendLogToErrors on </IfModule> <IfModule alias_module> ScriptAlias /myisapi/ "C:/path/to/myisapi/" </IfModule> <Directory "C:/path/to/myisapi/"> AllowOverride None Options ExecCGI Order allow,deny Allow from all </Directory>

    Read the article

  • ASP.net FFMPEG video conversion receiving error: "Error number -2 occurred"

    - by Pete
    Hello, I am attempting to integrate FFMPEG into my asp.net website. The process I am trying to complete is to upload a video, check if it is .avi, .mov, or .wmv and then convert this video into an mp4 using x264 so my flash player can play it. I am using an http handler (ashx) file to handle my upload. This is where I am also putting my conversion code. I am not sure if this is the best place to put it, but I wanted to see if i could at least get it working. Additionally, I was able to complete the conversion manually through cmd line. The error -2 comes up when i output the standard error from the process I executed. This is the error i receive: FFmpeg version SVN-r23001, Copyright (c) 2000-2010 the FFmpeg developers built on May 1 2010 06:06:15 with gcc 4.4.2 configuration: --enable-memalign-hack --cross-prefix=i686-mingw32- --cc=ccache-i686-mingw32-gcc --arch=i686 --target-os=mingw32 --enable-runtime-cpudetect --enable-avisynth --enable-gpl --enable-version3 --enable-bzlib --enable-libgsm --enable-libfaad --enable-pthreads --enable-libvorbis --enable-libtheora --enable-libspeex --enable-libmp3lame --enable-libopenjpeg --enable-libxvid --enable-libschroedinger --enable-libx264 --enable-libopencore_amrwb --enable-libopencore_amrnb libavutil 50.15. 0 / 50.15. 0 libavcodec 52.66. 0 / 52.66. 0 libavformat 52.61. 0 / 52.61. 0 libavdevice 52. 2. 0 / 52. 2. 0 libswscale 0.10. 0 / 0.10. 0 532010_Robotica_720.wmv: Error number -2 occurred here is the code below: <%@ WebHandler Language="VB" Class="upload" %> Imports System Imports System.Web Imports System.IO Imports System.Diagnostics Imports System.Threading Public Class upload : Implements IHttpHandler Public currentTime As System.DateTime Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest currentTime = System.DateTime.Now If (Not context.Request.Files("Filedata") Is Nothing) Then Dim file As HttpPostedFile : file = context.Request.Files("Filedata") Dim targetDirectory As String : targetDirectory = HttpContext.Current.Server.MapPath(context.Request("folder")) Dim targetFilePath As String : targetFilePath = Path.Combine(targetDirectory, currentTime.Month & currentTime.Day & currentTime.Year & "_" & file.FileName) Dim fileNameArray As String() fileNameArray = Split(file.FileName, ".") If (System.IO.File.Exists(targetFilePath)) Then System.IO.File.Delete(targetFilePath) End If file.SaveAs(targetFilePath) Select Case fileNameArray(UBound(fileNameArray)) Case "avi", "mov", "wmv" Dim fileargs As String = fileargs = "-y -i " & currentTime.Month & currentTime.Day & currentTime.Year & "_" & file.FileName & " -ab 96k -vcodec libx264 -vpre normal -level 41 " fileargs += "-crf 25 -bufsize 20000k -maxrate 25000k -g 250 -r 20 -s 900x506 -coder 1 -flags +loop " fileargs += "-cmp +chroma -partitions +parti4x4+partp8x8+partb8x8 -subq 7 -me_range 16 -keyint_min 25 " fileargs += "-sc_threshold 40 -i_qfactor 0.71 -rc_eq 'blurCplx^(1-qComp)' -bf 16 -b_strategy 1 -bidir_refine 1 " fileargs += "-refs 6 -deblockalpha 0 -deblockbeta 0 -f mp4 " & currentTime.Month & currentTime.Day & currentTime.Year & "_" & file.FileName & ".mp4" Dim proc As New Diagnostics.Process() proc.StartInfo.FileName "ffmpeg.exe" proc.StartInfo.Arguments = fileargs proc.StartInfo.UseShellExecute = False proc.StartInfo.CreateNoWindow = True proc.StartInfo.RedirectStandardOutput = True proc.StartInfo.RedirectStandardError = True AddHandler proc.OutputDataReceived, AddressOf SaveTextToFile proc.Start() SaveTextToFile2(proc.StandardError.ReadToEnd()) proc.WaitForExit() proc.Close() End Select Catch ex As System.IO.IOException Thread.Sleep(2000) GoTo Conversion Finally context.Response.Write("1") End Try End If End Sub Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable Get Return False End Get End Property Private Shared Sub SaveTextToFile(ByVal sendingProcess As Object, ByVal strData As DataReceivedEventArgs) Dim FullPath As String = "text.txt" Dim Contents As String = "" Dim objReader As StreamWriter objReader = New StreamWriter(FullPath) If Not String.IsNullOrEmpty(strData.Data) Then objReader.Write(Environment.NewLine + strData.Data) End If objReader.Close() End Sub Private Sub SaveTextToFile2(ByVal strData As String) Dim FullPath As String = "texterror.txt" Dim Contents As String = "" Dim objReader As StreamWriter objReader = New StreamWriter(FullPath) objReader.Write(Environment.NewLine + strData) objReader.Close() End Sub End Class

    Read the article

  • validating cascading dropdownlist

    - by shruti
    i am working on MVC.Net. in that i have used cascading dropdownlist. I want to do validations for blank field. the view page coding is: Select Category: <%= Html.DropDownList("Makes", ViewData["Makes"] as SelectList,"Select Category")% Select Subcategory: <%= Html.CascadingDropDownList("Models", "Makes")% the code on controller: public ActionResult AddSubCategoryPage() { var makeList = new SelectList(entityObj.Category.ToList(), "Category_id", "Category_name"); ViewData["Makes"] = makeList; // Create Models view data var modelList = new CascadingSelectList(entityObj.Subcategory1.ToList(), "Category_id", "Subcategory_id", "Subcategory_name"); ViewData["Models"] = modelList; return View("AddSubCategoryPage"); } and for that i have made one class: public static class JavaScriptExtensions { public static string CascadingDropDownList(this HtmlHelper helper, string name, string associatedDropDownList) { var sb = new StringBuilder(); // render select tag sb.AppendFormat("<select name='{0}' id='{0}'></select>", name); sb.AppendLine(); // render data array sb.AppendLine("<script type='text/javascript'>"); var data = (CascadingSelectList)helper.ViewDataContainer.ViewData[name]; var listItems = data.GetListItems(); var colArray = new List<string>(); foreach (var item in listItems) colArray.Add(String.Format("{{key:'{0}',value:'{1}',text:'{2}'}}", item.Key, item.Value, item.Text)); var jsArray = String.Join(",", colArray.ToArray()); sb.AppendFormat("$get('{0}').allOptions=[{1}];", name, jsArray); sb.AppendLine(); sb.AppendFormat("$addHandler($get('{0}'), 'change', Function.createCallback(bindDropDownList, $get('{1}')));", associatedDropDownList, name); sb.AppendLine(); sb.AppendLine("</script>"); return sb.ToString(); } } public class CascadingSelectList { private IEnumerable _items; private string _dataKeyField; private string _dataValueField; private string _dataTextField; public CascadingSelectList(IEnumerable items, string dataKeyField, string dataValueField, string dataTextField) { _items = items; _dataKeyField = dataKeyField; _dataValueField = dataValueField; _dataTextField = dataTextField; } public List<CascadingListItem> GetListItems() { var listItems = new List<CascadingListItem>(); foreach (var item in _items) { var key = DataBinder.GetPropertyValue(item, _dataKeyField).ToString(); var value = DataBinder.GetPropertyValue(item, _dataValueField).ToString(); var text = DataBinder.GetPropertyValue(item, _dataTextField).ToString(); listItems.Add(new CascadingListItem(key, value, text)); } return listItems; } } public class CascadingListItem { public CascadingListItem(string key, string value, string text) { this.Key = key; this.Value = value; this.Text = text; } public string Key { get; set; } public string Value { get; set; } public string Text { get; set; } } but when i run the aaplication it gives me following error: Server Error in '/' Application. The parameters dictionary contains a null entry for parameter 'Models' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult AddSubCategoryPage(Int32, System.String, System.String)' in 'CMS.Controllers.HomeController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters . plz help me.

    Read the article

  • http request to cgi python script successful, but the script doesn't seem to run

    - by chipChocolate.py
    I have configured cgi scripts for my apache2 web server. Here is what I want to do: Client uploads the image to the server. (this already works) On success, I want to execute the python script to resize the image. I tried the following and the success function does execute but my python script does not seem to execute: Javascript code that sends the request: var input = document.getElementById('imageLoader'); imageName = input.value; var file = input.files[0]; if(file != undefined){ formData= new FormData(); console.log(formData.length); if(!!file.type.match(/image.*/)){ formData.append("image", file); $.ajax({ url: "upload.php", type: "POST", processData: false, contentType: false, success: function() { var input = document.getElementById('imageLoader'); imageName = input.value; var file = input.files[0]; formData = new FormData(); formData.append("filename", file); $.ajax({ url: "http://localhost/Main/cgi-bin/resize.py", type: "POST", data: formData, processData: false, contentType: false, success: function(data) { console.log(data); } }); // code continues... resize.py: #!/usr/bin/python import cgi import cgitb import Image cgitb.enable() data = cgi.FieldStorage() filename = data.getvalue("filename") im = Image.open("../JS/upload/" + filename) (width, height) = im.size maxWidth = 600 maxHeight = 400 if width > maxWidth: d = float(width) / maxWidth height = int(height / d) width = maxWidth if height > maxHeight: d = float(height) / maxHeight width = int(width / d) height = maxHeight size = (width, height) im = im.resize(size, Image.ANTIALIAS) im.save("../JS/upload/" + filename, quality=100) This is the apache2.conf: <Directory /var/www/html/Main/cgi-bin> AllowOverride None Options +ExecCGI SetHandler cgi-script AddHandler cgi-script .py .cgi Order allow,deny Allow from all </Directory> cgi-bin and python script file permissions: drwxrwxr-x 2 mou mou 4096 Aug 24 03:28 cgi-bin -rwxrwxrwx 1 mou mou 1673 Aug 24 03:28 resize.py Edit: Executing this code $.ajax({ url: "http://localhost/Main/cgi-bin/resize.py", type: "POST", data: formData, // formData = {"filename" : "the filename which was saved in a variable whie the image was uploaded"} processData: false, contentType: false, success: function(data) { alert(data); } }); it alerts the following: <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> --> </font> </font> </font> </script> </object> </blockquote> </pre> </table> </table> </table> </table> </table> </font> </font> </font><body bgcolor="#f0f0f8"> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="heading"> <tr bgcolor="#6622aa"> <td valign=bottom>&nbsp;<br> <font color="#ffffff" face="helvetica, arial">&nbsp;<br><big><big><strong>&lt;type 'exceptions.TypeError'&gt;</strong></big></big></font></td ><td align=right valign=bottom ><font color="#ffffff" face="helvetica, arial">Python 2.7.6: /usr/bin/python<br>Sun Aug 24 17:24:15 2014</font></td></tr></table> <p>A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred.</p> <table width="100%" cellspacing=0 cellpadding=0 border=0> <tr><td bgcolor="#d8bbff"><big>&nbsp;</big><a href="file:///var/www/html/Main/cgi-bin/resize.py">/var/www/html/Main/cgi-bin/resize.py</a> in <strong><module></strong>()</td></tr> <tr><td><font color="#909090"><tt>&nbsp;&nbsp;<small>&nbsp;&nbsp;&nbsp;10</small>&nbsp;<br> </tt></font></td></tr> <tr><td><font color="#909090"><tt>&nbsp;&nbsp;<small>&nbsp;&nbsp;&nbsp;11</small>&nbsp;filename&nbsp;=&nbsp;data.getvalue("filename")<br> </tt></font></td></tr> <tr><td bgcolor="#ffccee"><tt>=&gt;<small>&nbsp;&nbsp;&nbsp;12</small>&nbsp;im&nbsp;=&nbsp;Image.open("../JS/upload/"&nbsp;+&nbsp;filename)<br> </tt></td></tr> <tr><td><font color="#909090"><tt>&nbsp;&nbsp;<small>&nbsp;&nbsp;&nbsp;13</small>&nbsp;<br> </tt></font></td></tr> <tr><td><font color="#909090"><tt>&nbsp;&nbsp;<small>&nbsp;&nbsp;&nbsp;14</small>&nbsp;(width,&nbsp;height)&nbsp;=&nbsp;im.size<br> </tt></font></td></tr> <tr><td><small><font color="#909090">im <em>undefined</em>, <strong>Image</strong>&nbsp;= &lt;module 'Image' from '/usr/lib/python2.7/dist-packages/PILcompat/Image.pyc'&gt;, Image.<strong>open</strong>&nbsp;= &lt;function open&gt;, <strong>filename</strong>&nbsp;= '<font color="#c040c0">\xff\xd8\xff\xe0\x00\x10</font>JFIF<font color="#c040c0">\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00</font>C<font color="#c040c0">\x00\x06\x04\x05\x06\x05\x04\x06\x06\x05\x06\x07\x07\x06\x08\n\x10\n\n\t\t\n\x14\x0e</font>...<font color="#c040c0">\x94\r\x17\x11</font>b<font color="#c040c0">\xcd\xdc\x1a\xfe\xf1\x05\x1b\x15\xd1</font>R<font color="#c040c0">\xce\xe9</font>*<font color="#c040c0">\xb5\x8e</font>b<font color="#c040c0">\x97\x82\x87</font>R<font color="#c040c0">\xf4\xaa</font>K<font color="#c040c0">\x83</font>6<font color="#c040c0">\xbf\xfb</font>0<font color="#c040c0">\xa0\xb6</font>8<font color="#c040c0">\xa9</font>C<font color="#c040c0">\x86\x8d\x96</font>n+E<font color="#c040c0">\xd3\x7f\x99\xff\xd9</font>'</font></small></td></tr></table> <table width="100%" cellspacing=0 cellpadding=0 border=0> <tr><td bgcolor="#d8bbff"><big>&nbsp;</big><a href="file:///usr/lib/python2.7/dist-packages/PIL/Image.py">/usr/lib/python2.7/dist-packages/PIL/Image.py</a> in <strong>open</strong>(fp='../JS/upload/<font color="#c040c0">\xff\xd8\xff\xe0\x00\x10</font>JFIF<font color="#c040c0">\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00</font>C<font color="#c040c0">\x00\x06\x04\x05\x06\x05\x04\x06\x06\x05\x06</font>...<font color="#c040c0">\x94\r\x17\x11</font>b<font color="#c040c0">\xcd\xdc\x1a\xfe\xf1\x05\x1b\x15\xd1</font>R<font color="#c040c0">\xce\xe9</font>*<font color="#c040c0">\xb5\x8e</font>b<font color="#c040c0">\x97\x82\x87</font>R<font color="#c040c0">\xf4\xaa</font>K<font color="#c040c0">\x83</font>6<font color="#c040c0">\xbf\xfb</font>0<font color="#c040c0">\xa0\xb6</font>8<font color="#c040c0">\xa9</font>C<font color="#c040c0">\x86\x8d\x96</font>n+E<font color="#c040c0">\xd3\x7f\x99\xff\xd9</font>', mode='r')</td></tr> <tr><td><font color="#909090"><tt>&nbsp;&nbsp;<small>&nbsp;1994</small>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;isPath(fp):<br> </tt></font></td></tr> <tr><td><font color="#909090"><tt>&nbsp;&nbsp;<small>&nbsp;1995</small>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;filename&nbsp;=&nbsp;fp<br> </tt></font></td></tr> <tr><td bgcolor="#ffccee"><tt>=&gt;<small>&nbsp;1996</small>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;fp&nbsp;=&nbsp;builtins.open(fp,&nbsp;"rb")<br> </tt></td></tr> <tr><td><font color="#909090"><tt>&nbsp;&nbsp;<small>&nbsp;1997</small>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;else:<br> </tt></font></td></tr> <tr><td><font color="#909090"><tt>&nbsp;&nbsp;<small>&nbsp;1998</small>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;filename&nbsp;=&nbsp;""<br> </tt></font></td></tr> <tr><td><small><font color="#909090"><strong>fp</strong>&nbsp;= '../JS/upload/<font color="#c040c0">\xff\xd8\xff\xe0\x00\x10</font>JFIF<font color="#c040c0">\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00</font>C<font color="#c040c0">\x00\x06\x04\x05\x06\x05\x04\x06\x06\x05\x06</font>...<font color="#c040c0">\x94\r\x17\x11</font>b<font color="#c040c0">\xcd\xdc\x1a\xfe\xf1\x05\x1b\x15\xd1</font>R<font color="#c040c0">\xce\xe9</font>*<font color="#c040c0">\xb5\x8e</font>b<font color="#c040c0">\x97\x82\x87</font>R<font color="#c040c0">\xf4\xaa</font>K<font color="#c040c0">\x83</font>6<font color="#c040c0">\xbf\xfb</font>0<font color="#c040c0">\xa0\xb6</font>8<font color="#c040c0">\xa9</font>C<font color="#c040c0">\x86\x8d\x96</font>n+E<font color="#c040c0">\xd3\x7f\x99\xff\xd9</font>', <em>global</em> <strong>builtins</strong>&nbsp;= &lt;module '__builtin__' (built-in)&gt;, builtins.<strong>open</strong>&nbsp;= &lt;built-in function open&gt;</font></small></td></tr></table><p><strong>&lt;type 'exceptions.TypeError'&gt;</strong>: file() argument 1 must be encoded string without NULL bytes, not str <br><tt><small>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</small>&nbsp;</tt>args&nbsp;= ('file() argument 1 must be encoded string without NULL bytes, not str',) <br><tt><small>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</small>&nbsp;</tt>message&nbsp;= 'file() argument 1 must be encoded string without NULL bytes, not str' <!-- The above is a description of an error in a Python program, formatted for a Web browser because the 'cgitb' module was enabled. In case you are not reading this in a Web browser, here is the original traceback: Traceback (most recent call last): File "/var/www/html/Main/cgi-bin/resize.py", line 12, in &lt;module&gt; im = Image.open("../JS/upload/" + filename) File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1996, in open fp = builtins.open(fp, "rb") TypeError: file() argument 1 must be encoded string without NULL bytes, not str --> Does this mean that the formData I am sending over is empty?

    Read the article

  • Google and Bing Map APIs Compared

    - by SGWellens
    At one of the local golf courses I frequent, there is an open grass field next to the course. It is about eight acres in size and mowed regularly. It is permissible to hit golf balls there—you bring and shag our own balls. My golf colleagues and I spend hours there practicing, chatting and in general just wasting time. One of the guys brings Ginger, the amazing, incredible, wonder dog. Ginger is a Portuguese Pointer. She chases squirrels, begs for snacks and supervises us closely to make sure we don't misbehave.     Anyway, I decided to make a dedicated web page to measure distances on the field in yards using online mapping services. I started with Google maps and then did the same application with Bing maps. It is a good way to become familiar with the APIs. Here are images of the final two maps: Google:  Bing:   To start with online mapping services, you need to visit the respective websites and get a developers key. I pared the code down to the minimum to make it easier to compare the APIs. Google maps required this CSS (or it wouldn't work): <style type="text/css">     html     {         height: 100%;     }       body     {         height: 100%;         margin: 0;         padding: 0;     } Here is how the map scripts are included. Google requires the developer Key when loading the JavaScript, Bing requires it when the map object is created: Google: <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=XXXXXXX&libraries=geometry&sensor=false" > </script> Bing: <script  type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"> </script> Note: I use jQuery to manipulate the DOM elements which may be overkill, but I may add more stuff to this application and I didn't want to have to add it later. Plus, I really like jQuery. Here is how the maps are created: Common Code (the same for both Google and Bing Maps):     <script type="text/javascript">         var gTheMap;         var gMarker1;         var gMarker2;           $(document).ready(DocLoaded);           function DocLoaded()         {             // golf course coordinates             var StartLat = 44.924254;             var StartLng = -93.366859;               // what element to display the map in             var mapdiv = $("#map_div")[0];   Google:         // where on earth the map should display         var StartPoint = new google.maps.LatLng(StartLat, StartLng);           // create the map         gTheMap = new google.maps.Map(mapdiv,             {                 center: StartPoint,                 zoom: 18,                 mapTypeId: google.maps.MapTypeId.SATELLITE             });           // place two markers         marker1 = PlaceMarker(new google.maps.LatLng(StartLat, StartLng + .0001));         marker2 = PlaceMarker(new google.maps.LatLng(StartLat, StartLng - .0001));           DragEnd(null);     } Bing:         // where on earth the map should display         var StartPoint = new  Microsoft.Maps.Location(StartLat, StartLng);           // create the map         gTheMap = new Microsoft.Maps.Map(mapdiv,             {                 credentials: 'Asbsa_hzfHl69XF3wxBd_WbW0dLNTRUH3ZHQG9qcV5EFRLuWEaOP1hjWdZ0A0P17',                 center: StartPoint,                 zoom: 18,                 mapTypeId: Microsoft.Maps.MapTypeId.aerial             });             // place two markers         marker1 = PlaceMarker(new Microsoft.Maps.Location(StartLat, StartLng + .0001));         marker2 = PlaceMarker(new Microsoft.Maps.Location(StartLat, StartLng - .0001));           DragEnd(null);     } Note: In the Bing documentation, mapTypeId: was missing from the list of options even though the sample code included it. Note: When creating the Bing map, use the developer Key for the credentials property. I immediately place two markers/pins on the map which is simpler that creating them on the fly with mouse clicks (as I first tried). The markers/pins are draggable and I capture the DragEnd event to calculate and display the distance in yards and draw a line when the user finishes dragging. Here is the code to place a marker: Google: // ---- PlaceMarker ------------------------------------   function PlaceMarker(location) {     var marker = new google.maps.Marker(         {             position: location,             map: gTheMap,             draggable: true         });     marker.addListener('dragend', DragEnd);     return marker; }   Bing: // ---- PlaceMarker ------------------------------------   function PlaceMarker(location) {     var marker = new Microsoft.Maps.Pushpin(location,     {         draggable : true     });     Microsoft.Maps.Events.addHandler(marker, 'dragend', DragEnd);     gTheMap.entities.push(marker);     return marker; } Here is the code than runs when the user stops dragging a marker: Google: // ---- DragEnd -------------------------------------------   var gLine = null;   function DragEnd(Event) {     var meters = google.maps.geometry.spherical.computeDistanceBetween(marker1.position, marker2.position);     var yards = meters * 1.0936133;     $("#message").text(yards.toFixed(1) + ' yards');    // draw a line connecting the points     var Endpoints = [marker1.position, marker2.position];       if (gLine == null)     {         gLine = new google.maps.Polyline({             path: Endpoints,             strokeColor: "#FFFF00",             strokeOpacity: 1.0,             strokeWeight: 2,             map: gTheMap         });     }     else        gLine.setPath(Endpoints); } Bing: // ---- DragEnd -------------------------------------------   var gLine = null;   function DragEnd(Args) {    var Distance =  CalculateDistance(marker1._location, marker2._location);      $("#message").text(Distance.toFixed(1) + ' yards');       // draw a line connecting the points    var Endpoints = [marker1._location, marker2._location];           if (gLine == null)    {        gLine = new Microsoft.Maps.Polyline(Endpoints,            {                strokeColor: new Microsoft.Maps.Color(0xFF, 0xFF, 0xFF, 0),  // aRGB                strokeThickness : 2            });          gTheMap.entities.push(gLine);    }    else        gLine.setLocations(Endpoints);  }   Note: I couldn't find a function to calculate the distance between points in the Bing API, so I wrote my own (CalculateDistance). If you want to see the source for it, you can pick it off the web page. Note: I was able to verify the accuracy of the measurements by using the golf hole next to the field. I put a pin/marker on the center of the green, and then by zooming in, I was able to see the 150 markers on the fairway and put the other pin/marker on one of them. Final Notes: All in all, the APIs are very similar. Both made it easy to accomplish a lot with a minimum amount of code. In one aerial view, there are leaves on the tree, in the other, the trees are bare. I don't know which service has the newer data. Here are links to working pages: Bing Map Demo Google Map Demo I hope someone finds this useful. Steve Wellens   CodeProject

    Read the article

  • Google and Bing Map APIs Compared

    - by SGWellens
    At one of the local golf courses I frequent, there is an open grass field next to the course. It is about eight acres in size and mowed regularly. It is permissible to hit golf balls there—you bring and shag our own balls. My golf colleagues and I spend hours there practicing, chatting and in general just wasting time. One of the guys brings Ginger, the amazing, incredible, wonder dog. Ginger is a Hungarian Vizlas (or Hungarian pointer). She chases squirrels, begs for snacks and supervises us closely to make sure we don't misbehave. Anyway, I decided to make a dedicated web page to measure distances on the field in yards using online mapping services. I started with Google maps and then did the same application with Bing maps. It is a good way to become familiar with the APIs. Here are images of the final two maps: Google:  Bing:   To start with online mapping services, you need to visit the respective websites and get a developers key. I pared the code down to the minimum to make it easier to compare the APIs. Google maps required this CSS (or it wouldn't work): <style type="text/css">     html     {         height: 100%;     }       body     {         height: 100%;         margin: 0;         padding: 0;     } Here is how the map scripts are included. Google requires the developer Key when loading the JavaScript, Bing requires it when the map object is created: Google: <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=XXXXXXX&libraries=geometry&sensor=false" > </script> Bing: <script  type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"> </script> Note: I use jQuery to manipulate the DOM elements which may be overkill, but I may add more stuff to this application and I didn't want to have to add it later. Plus, I really like jQuery. Here is how the maps are created: Common Code (the same for both Google and Bing Maps):     <script type="text/javascript">         var gTheMap;         var gMarker1;         var gMarker2;           $(document).ready(DocLoaded);           function DocLoaded()         {             // golf course coordinates             var StartLat = 44.924254;             var StartLng = -93.366859;               // what element to display the map in             var mapdiv = $("#map_div")[0];   Google:         // where on earth the map should display         var StartPoint = new google.maps.LatLng(StartLat, StartLng);           // create the map         gTheMap = new google.maps.Map(mapdiv,             {                 center: StartPoint,                 zoom: 18,                 mapTypeId: google.maps.MapTypeId.SATELLITE             });           // place two markers         marker1 = PlaceMarker(new google.maps.LatLng(StartLat, StartLng + .0001));         marker2 = PlaceMarker(new google.maps.LatLng(StartLat, StartLng - .0001));           DragEnd(null);     } Bing:         // where on earth the map should display         var StartPoint = new  Microsoft.Maps.Location(StartLat, StartLng);           // create the map         gTheMap = new Microsoft.Maps.Map(mapdiv,             {                 credentials: 'XXXXXXXXXXXXXXXXXXX',                 center: StartPoint,                 zoom: 18,                 mapTypeId: Microsoft.Maps.MapTypeId.aerial             });           // place two markers         marker1 = PlaceMarker(new Microsoft.Maps.Location(StartLat, StartLng + .0001));         marker2 = PlaceMarker(new Microsoft.Maps.Location(StartLat, StartLng - .0001));           DragEnd(null);     } Note: In the Bing documentation, mapTypeId: was missing from the list of options even though the sample code included it. Note: When creating the Bing map, use the developer Key for the credentials property. I immediately place two markers/pins on the map which is simpler that creating them on the fly with mouse clicks (as I first tried). The markers/pins are draggable and I capture the DragEnd event to calculate and display the distance in yards and draw a line when the user finishes dragging. Here is the code to place a marker: Google: // ---- PlaceMarker ------------------------------------   function PlaceMarker(location) {     var marker = new google.maps.Marker(         {             position: location,             map: gTheMap,             draggable: true         });     marker.addListener('dragend', DragEnd);     return marker; } Bing: // ---- PlaceMarker ------------------------------------   function PlaceMarker(location) {     var marker = new Microsoft.Maps.Pushpin(location,     {         draggable : true     });     Microsoft.Maps.Events.addHandler(marker, 'dragend', DragEnd);     gTheMap.entities.push(marker);     return marker; } Here is the code than runs when the user stops dragging a marker: Google: // ---- DragEnd -------------------------------------------   var gLine = null;   function DragEnd(Event) {     var meters = google.maps.geometry.spherical.computeDistanceBetween(marker1.position, marker2.position);     var yards = meters * 1.0936133;     $("#message").text(yards.toFixed(1) + ' yards');    // draw a line connecting the points     var Endpoints = [marker1.position, marker2.position];       if (gLine == null)     {         gLine = new google.maps.Polyline({             path: Endpoints,             strokeColor: "#FFFF00",             strokeOpacity: 1.0,             strokeWeight: 2,             map: gTheMap         });     }     else        gLine.setPath(Endpoints); } Bing: // ---- DragEnd -------------------------------------------   var gLine = null;   function DragEnd(Args) {    var Distance =  CalculateDistance(marker1._location, marker2._location);      $("#message").text(Distance.toFixed(1) + ' yards');       // draw a line connecting the points    var Endpoints = [marker1._location, marker2._location];           if (gLine == null)    {        gLine = new Microsoft.Maps.Polyline(Endpoints,            {                strokeColor: new Microsoft.Maps.Color(0xFF, 0xFF, 0xFF, 0),  // aRGB                strokeThickness : 2            });          gTheMap.entities.push(gLine);    }    else        gLine.setLocations(Endpoints);  }  Note: I couldn't find a function to calculate the distance between points in the Bing API, so I wrote my own (CalculateDistance). If you want to see the source for it, you can pick it off the web page. Note: I was able to verify the accuracy of the measurements by using the golf hole next to the field. I put a pin/marker on the center of the green, and then by zooming in, I was able to see the 150 markers on the fairway and put the other pin/marker on one of them. Final Notes: All in all, the APIs are very similar. Both made it easy to accomplish a lot with a minimum amount of code. In one aerial view, there are leaves on the tree, in the other, the trees are bare. I don't know which service has the newer data. Here are links to working pages: Bing Map Demo Google Map Demo I hope someone finds this useful. Steve Wellens   CodeProject

    Read the article

  • Redmine install not working and displaying directory contents - Ubuntu 10.04

    - by Casey Flynn
    I've gone through the steps to set up and install the redmine project tracking web app on my VPS with Apache2 but I'm running into a situation where instead of displaying the redmine app, I just see the directory contents: Does anyone know what could be the problem? I'm not sure what other files might be of use to diagnose what's going on. Thanks! # # Based upon the NCSA server configuration files originally by Rob McCool. # # This is the main Apache server configuration file. It contains the # configuration directives that give the server its instructions. # See http://httpd.apache.org/docs/2.2/ for detailed information about # the directives. # # Do NOT simply read the instructions in here without understanding # what they do. They're here only as hints or reminders. If you are unsure # consult the online docs. You have been warned. # # The configuration directives are grouped into three basic sections: # 1. Directives that control the operation of the Apache server process as a # whole (the 'global environment'). # 2. Directives that define the parameters of the 'main' or 'default' server, # which responds to requests that aren't handled by a virtual host. # These directives also provide default values for the settings # of all virtual hosts. # 3. Settings for virtual hosts, which allow Web requests to be sent to # different IP addresses or hostnames and have them handled by the # same Apache server process. # # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" for Win32), the # server will use that explicit path. If the filenames do *not* begin # with "/", the value of ServerRoot is prepended -- so "/var/log/apache2/foo.log" # with ServerRoot set to "" will be interpreted by the # server as "//var/log/apache2/foo.log". # ### Section 1: Global Environment # # The directives in this section affect the overall operation of Apache, # such as the number of concurrent requests it can handle or where it # can find its configuration files. # # # ServerRoot: The top of the directory tree under which the server's # configuration, error, and log files are kept. # # NOTE! If you intend to place this on an NFS (or otherwise network) # mounted filesystem then please read the LockFile documentation (available # at <URL:http://httpd.apache.org/docs-2.1/mod/mpm_common.html#lockfile>); # you will save yourself a lot of trouble. # # Do NOT add a slash at the end of the directory path. # ServerRoot "/etc/apache2" # # The accept serialization lock file MUST BE STORED ON A LOCAL DISK. # #<IfModule !mpm_winnt.c> #<IfModule !mpm_netware.c> LockFile /var/lock/apache2/accept.lock #</IfModule> #</IfModule> # # PidFile: The file in which the server should record its process # identification number when it starts. # This needs to be set in /etc/apache2/envvars # PidFile ${APACHE_PID_FILE} # # Timeout: The number of seconds before receives and sends time out. # Timeout 300 # # KeepAlive: Whether or not to allow persistent connections (more than # one request per connection). Set to "Off" to deactivate. # KeepAlive On # # MaxKeepAliveRequests: The maximum number of requests to allow # during a persistent connection. Set to 0 to allow an unlimited amount. # We recommend you leave this number high, for maximum performance. # MaxKeepAliveRequests 100 # # KeepAliveTimeout: Number of seconds to wait for the next request from the # same client on the same connection. # KeepAliveTimeout 15 ## ## Server-Pool Size Regulation (MPM specific) ## # prefork MPM # StartServers: number of server processes to start # MinSpareServers: minimum number of server processes which are kept spare # MaxSpareServers: maximum number of server processes which are kept spare # MaxClients: maximum number of server processes allowed to start # MaxRequestsPerChild: maximum number of requests a server process serves <IfModule mpm_prefork_module> StartServers 5 MinSpareServers 5 MaxSpareServers 10 MaxClients 150 MaxRequestsPerChild 0 </IfModule> # worker MPM # StartServers: initial number of server processes to start # MaxClients: maximum number of simultaneous client connections # MinSpareThreads: minimum number of worker threads which are kept spare # MaxSpareThreads: maximum number of worker threads which are kept spare # ThreadsPerChild: constant number of worker threads in each server process # MaxRequestsPerChild: maximum number of requests a server process serves <IfModule mpm_worker_module> StartServers 2 MinSpareThreads 25 MaxSpareThreads 75 ThreadLimit 64 ThreadsPerChild 25 MaxClients 150 MaxRequestsPerChild 0 </IfModule> # event MPM # StartServers: initial number of server processes to start # MaxClients: maximum number of simultaneous client connections # MinSpareThreads: minimum number of worker threads which are kept spare # MaxSpareThreads: maximum number of worker threads which are kept spare # ThreadsPerChild: constant number of worker threads in each server process # MaxRequestsPerChild: maximum number of requests a server process serves <IfModule mpm_event_module> StartServers 2 MaxClients 150 MinSpareThreads 25 MaxSpareThreads 75 ThreadLimit 64 ThreadsPerChild 25 MaxRequestsPerChild 0 </IfModule> # These need to be set in /etc/apache2/envvars User ${APACHE_RUN_USER} Group ${APACHE_RUN_GROUP} # # AccessFileName: The name of the file to look for in each directory # for additional configuration directives. See also the AllowOverride # directive. # AccessFileName .htaccess # # The following lines prevent .htaccess and .htpasswd files from being # viewed by Web clients. # <Files ~ "^\.ht"> Order allow,deny Deny from all Satisfy all </Files> # # DefaultType is the default MIME type the server will use for a document # if it cannot otherwise determine one, such as from filename extensions. # If your server contains mostly text or HTML documents, "text/plain" is # a good value. If most of your content is binary, such as applications # or images, you may want to use "application/octet-stream" instead to # keep browsers from trying to display binary files as though they are # text. # DefaultType text/plain # # HostnameLookups: Log the names of clients or just their IP addresses # e.g., www.apache.org (on) or 204.62.129.132 (off). # The default is off because it'd be overall better for the net if people # had to knowingly turn this feature on, since enabling it means that # each client request will result in AT LEAST one lookup request to the # nameserver. # HostnameLookups Off # ErrorLog: The location of the error log file. # If you do not specify an ErrorLog directive within a <VirtualHost> # container, error messages relating to that virtual host will be # logged here. If you *do* define an error logfile for a <VirtualHost> # container, that host's errors will be logged there and not here. # ErrorLog /var/log/apache2/error.log # # LogLevel: Control the number of messages logged to the error_log. # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. # LogLevel warn # Include module configuration: Include /etc/apache2/mods-enabled/*.load Include /etc/apache2/mods-enabled/*.conf # Include all the user configurations: Include /etc/apache2/httpd.conf # Include ports listing Include /etc/apache2/ports.conf # # The following directives define some format nicknames for use with # a CustomLog directive (see below). # If you are behind a reverse proxy, you might want to change %h into %{X-Forwarded-For}i # LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %O" common LogFormat "%{Referer}i -> %U" referer LogFormat "%{User-agent}i" agent # # Define an access log for VirtualHosts that don't define their own logfile CustomLog /var/log/apache2/other_vhosts_access.log vhost_combined # Include of directories ignores editors' and dpkg's backup files, # see README.Debian for details. # Include generic snippets of statements Include /etc/apache2/conf.d/ # Include the virtual host configurations: Include /etc/apache2/sites-enabled/ # Enable fastcgi for .fcgi files # (If you're using a distro package for mod_fcgi, something like # this is probably already present) #<IfModule mod_fcgid.c> # AddHandler fastcgi-script .fcgi # FastCgiIpcDir /var/lib/apache2/fastcgi #</IfModule> LoadModule fcgid_module /usr/lib/apache2/modules/mod_fcgid.so LoadModule passenger_module /var/lib/gems/1.8/gems/passenger-3.0.7/ext/apache2/mod_passenger.so PassengerRoot /var/lib/gems/1.8/gems/passenger-3.0.7 PassengerRuby /usr/bin/ruby1.8 ServerName demo and my vhosts file #No DNS server, default ip address v-host #domain: none #public: /home/casey/public_html/app/ <VirtualHost *:80> ServerAdmin webmaster@localhost # ScriptAlias /redmine /home/casey/public_html/app/redmine/dispatch.fcgi DirectoryIndex index.html DocumentRoot /home/casey/public_html/app/public <Directory "/home/casey/trac/htdocs"> Order allow,deny Allow from all </Directory> <Directory /var/www/redmine> RailsBaseURI /redmine PassengerResolveSymlinksInDocumentRoot on </Directory> # <Directory /> # Options FollowSymLinks # AllowOverride None # </Directory> # <Directory /var/www/> # Options Indexes FollowSymLinks MultiViews # AllowOverride None # Order allow,deny # allow from all # </Directory> ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ <Directory "/usr/lib/cgi-bin"> AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all </Directory> ErrorLog /home/casey/public_html/app/log/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel debug CustomLog /home/casey/public_html/app/log/access.log combined # Alias /doc/ "/usr/share/doc/" # <Directory "/usr/share/doc/"> # Options Indexes MultiViews FollowSymLinks # AllowOverride None # Order deny,allow # Deny from all # Allow from 127.0.0.0/255.0.0.0 ::1/128 # </Directory> </VirtualHost>

    Read the article

  • HTTP Builder/Groovy - lost 302 (redirect) handling?

    - by Misha Koshelev
    Dear All: I am reading here http://groovy.codehaus.org/modules/http-builder/doc/handlers.html "In cases where a response sends a redirect status code, this is handled internally by Apache HttpClient, which by default will simply follow the redirect by re-sending the request to the new URL. You do not need to do anything special in order to follow 302 responses." This seems to work fine when I simply use the get() or post() methods without a closure. However, when I use a closure, I seem to lose 302 handling. Is there some way I can handle this myself? Thank you p.s. Here is my log output showing it is a 302 response [java] FINER: resp.statusLine: "HTTP/1.1 302 Found" Here is the relevant code: // Copyright (C) 2010 Misha Koshelev. All Rights Reserved. package com.mksoft.fbbday.main import groovyx.net.http.ContentType import java.util.logging.Level import java.util.logging.Logger class HTTPBuilder { def dataDirectory HTTPBuilder(dataDirectory) { this.dataDirectory=dataDirectory } // Main logic def logger=Logger.getLogger(this.class.name) def closure={resp,reader-> logger.finer("resp.statusLine: \"${resp.statusLine}\"") if (logger.isLoggable(Level.FINEST)) { def respHeadersString='Headers:'; resp.headers.each() { header->respHeadersString+="\n\t${header.name}=\"${header.value}\"" } logger.finest(respHeadersString) } def text=reader.text def lastHtml=new File("${dataDirectory}${File.separator}last.html") if (lastHtml.exists()) { lastHtml.delete() } lastHtml<<text new XmlSlurper(new org.cyberneko.html.parsers.SAXParser()).parseText(text) } def processArgs(args) { if (logger.isLoggable(Level.FINER)) { def argsString='Args:'; args.each() { arg->argsString+="\n\t${arg.key}=\"${arg.value}\"" } logger.finer(argsString) } args.contentType=groovyx.net.http.ContentType.TEXT args } // HTTPBuilder methods def httpBuilder=new groovyx.net.http.HTTPBuilder () def get(args) { httpBuilder.get(processArgs(args),closure) } def post(args) { args.contentType=groovyx.net.http.ContentType.TEXT httpBuilder.post(processArgs(args),closure) } } Here is a specific tester: #!/usr/bin/env groovy import groovyx.net.http.HTTPBuilder import groovyx.net.http.Method import static groovyx.net.http.ContentType.URLENC import java.util.logging.ConsoleHandler import java.util.logging.Level import java.util.logging.Logger // MUST ENTER VALID FACEBOOK EMAIL AND PASSWORD BELOW !!! def email='' def pass='' // Remove default loggers def logger=Logger.getLogger('') def handlers=logger.handlers handlers.each() { handler->logger.removeHandler(handler) } // Log ALL to Console logger.setLevel Level.ALL def consoleHandler=new ConsoleHandler() consoleHandler.setLevel Level.ALL logger.addHandler(consoleHandler) // Facebook - need to get main page to capture cookies def http = new HTTPBuilder() http.get(uri:'http://www.facebook.com') // Login def html=http.post(uri:'https://login.facebook.com/login.php?login_attempt=1',body:[email:email,pass:pass]) assert html==null // Why null? html=http.post(uri:'https://login.facebook.com/login.php?login_attempt=1',body:[email:email,pass:pass]) { resp,reader-> assert resp.statusLine.statusCode==302 // Shouldn't we be redirected??? // http://groovy.codehaus.org/modules/http-builder/doc/handlers.html // "In cases where a response sends a redirect status code, this is handled internally by Apache HttpClient, which by default will simply follow the redirect by re-sending the request to the new URL. You do not need to do anything special in order to follow 302 responses. " } Here are relevant logs: FINE: Receiving response: HTTP/1.1 302 Found Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << HTTP/1.1 302 Found Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << Cache-Control: private, no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << Expires: Sat, 01 Jan 2000 00:00:00 GMT Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << Location: http://www.facebook.com/home.php? Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << P3P: CP="DSP LAW" Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << Pragma: no-cache Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << Set-Cookie: datr=1275687438-9ff6ae60a89d444d0fd9917abf56e085d370277a6e9ed50c1ba79; expires=Sun, 03-Jun-2012 21:37:24 GMT; path=/; domain=.facebook.com Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << Set-Cookie: lxe=koshelev%40post.harvard.edu; expires=Tue, 28-Sep-2010 15:24:04 GMT; path=/; domain=.facebook.com; httponly Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << Set-Cookie: lxr=deleted; expires=Thu, 04-Jun-2009 21:37:23 GMT; path=/; domain=.facebook.com; httponly Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << Set-Cookie: pk=183883c0a9afab1608e95d59164cc7dd; path=/; domain=.facebook.com; httponly Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << Content-Type: text/html; charset=utf-8 Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << X-Cnection: close Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << Date: Fri, 04 Jun 2010 21:37:24 GMT Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << Content-Length: 0 Jun 4, 2010 4:37:22 PM org.apache.http.client.protocol.ResponseProcessCookies processCookies FINE: Cookie accepted: "[version: 0][name: datr][value: 1275687438-9ff6ae60a89d444d0fd9917abf56e085d370277a6e9ed50c1ba79][domain: .facebook.com][path: /][expiry: Sun Jun 03 16:37:24 CDT 2012]". Jun 4, 2010 4:37:22 PM org.apache.http.client.protocol.ResponseProcessCookies processCookies FINE: Cookie accepted: "[version: 0][name: lxe][value: koshelev%40post.harvard.edu][domain: .facebook.com][path: /][expiry: Tue Sep 28 10:24:04 CDT 2010]". Jun 4, 2010 4:37:22 PM org.apache.http.client.protocol.ResponseProcessCookies processCookies FINE: Cookie accepted: "[version: 0][name: lxr][value: deleted][domain: .facebook.com][path: /][expiry: Thu Jun 04 16:37:23 CDT 2009]". Jun 4, 2010 4:37:22 PM org.apache.http.client.protocol.ResponseProcessCookies processCookies FINE: Cookie accepted: "[version: 0][name: pk][value: 183883c0a9afab1608e95d59164cc7dd][domain: .facebook.com][path: /][expiry: null]". Jun 4, 2010 4:37:22 PM org.apache.http.impl.client.DefaultRequestDirector execute FINE: Connection can be kept alive indefinitely Jun 4, 2010 4:37:22 PM groovyx.net.http.HTTPBuilder doRequest FINE: Response code: 302; found handler: post302$_run_closure2@7023d08b Jun 4, 2010 4:37:22 PM groovyx.net.http.HTTPBuilder doRequest FINEST: response handler result: null Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.SingleClientConnManager releaseConnection FINE: Releasing connection org.apache.http.impl.conn.SingleClientConnManager$ConnAdapter@605b28c9 You can see there is clearly a location argument. Thank you Misha

    Read the article

  • .htaccess not working (mod_rewrite)

    - by Mike Curry
    Edit: I am pretty sure my .htaccess file is NOT being executed, and the problem is NOT with my rewrite rules. I have not having any luck getting my .htaccess with mod_rewrite working. Basically all I am trying to do is remove 'www' from "http://www.site.com" and "https://www.site.com". If there is anything I am missing (conf files, etc let me know I willl update this) I jsut can't see whats wrong here... I am using a 1&1 VPS III Virtual private server... anyone ever have this issue? I am using Ubuntu 8.04 Server LTS. Here is my .htaccess file (located @ /var/www/site/trunk/html/) Options +FollowSymLinks RewriteEngine on RewriteCond %{HTTP_HOST} ^www\.(.*) [NC] RewriteRule (.*) //%1/$1 [L,R=301] My mod_rewrite is enabled: The auto regenerated sym link is there in mods-available and /usr/lib/apache2/modules/ contains mod_rewrite.so root@s15348441:/etc/apache2/mods-available# more rewrite.load LoadModule rewrite_module /usr/lib/apache2/modules/mod_rewrite.so root@s15348441:/var/log# apache2ctl -t -D DUMP_MODULES Loaded Modules: core_module (static) log_config_module (static) logio_module (static) mpm_prefork_module (static) http_module (static) so_module (static) alias_module (shared) auth_basic_module (shared) authn_file_module (shared) authz_default_module (shared) authz_groupfile_module (shared) authz_host_module (shared) authz_user_module (shared) autoindex_module (shared) cgi_module (shared) dir_module (shared) env_module (shared) mime_module (shared) negotiation_module (shared) php5_module (shared) rewrite_module (shared) setenvif_module (shared) ssl_module (shared) status_module (shared) Syntax OK My apache config files: apache2.conf # # Based upon the NCSA server configuration files originally by Rob McCool. # # This is the main Apache server configuration file. It contains the # configuration directives that give the server its instructions. # See http://httpd.apache.org/docs/2.2/ for detailed information about # the directives. # # Do NOT simply read the instructions in here without understanding # what they do. They're here only as hints or reminders. If you are unsure # consult the online docs. You have been warned. # # The configuration directives are grouped into three basic sections: # 1. Directives that control the operation of the Apache server process as a # whole (the 'global environment'). # 2. Directives that define the parameters of the 'main' or 'default' server, # which responds to requests that aren't handled by a virtual host. # These directives also provide default values for the settings # of all virtual hosts. # 3. Settings for virtual hosts, which allow Web requests to be sent to # different IP addresses or hostnames and have them handled by the # same Apache server process. # # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" for Win32), the # server will use that explicit path. If the filenames do *not* begin # with "/", the value of ServerRoot is prepended -- so "/var/log/apache2/foo.log" # with ServerRoot set to "" will be interpreted by the # server as "//var/log/apache2/foo.log". # ### Section 1: Global Environment # # The directives in this section affect the overall operation of Apache, # such as the number of concurrent requests it can handle or where it # can find its configuration files. # # # ServerRoot: The top of the directory tree under which the server's # configuration, error, and log files are kept. # # NOTE! If you intend to place this on an NFS (or otherwise network) # mounted filesystem then please read the LockFile documentation (available # at <URL:http://httpd.apache.org/docs-2.1/mod/mpm_common.html#lockfile>); # you will save yourself a lot of trouble. # # Do NOT add a slash at the end of the directory path. # ServerRoot "/etc/apache2" # # The accept serialization lock file MUST BE STORED ON A LOCAL DISK. # #<IfModule !mpm_winnt.c> #<IfModule !mpm_netware.c> LockFile /var/lock/apache2/accept.lock #</IfModule> #</IfModule> # # PidFile: The file in which the server should record its process # identification number when it starts. # This needs to be set in /etc/apache2/envvars # PidFile ${APACHE_PID_FILE} # # Timeout: The number of seconds before receives and sends time out. # Timeout 300 # # KeepAlive: Whether or not to allow persistent connections (more than # one request per connection). Set to "Off" to deactivate. # KeepAlive On # # MaxKeepAliveRequests: The maximum number of requests to allow # during a persistent connection. Set to 0 to allow an unlimited amount. # We recommend you leave this number high, for maximum performance. # MaxKeepAliveRequests 100 # # KeepAliveTimeout: Number of seconds to wait for the next request from the # same client on the same connection. # KeepAliveTimeout 15 ## ## Server-Pool Size Regulation (MPM specific) ## # prefork MPM # StartServers: number of server processes to start # MinSpareServers: minimum number of server processes which are kept spare # MaxSpareServers: maximum number of server processes which are kept spare # MaxClients: maximum number of server processes allowed to start # MaxRequestsPerChild: maximum number of requests a server process serves <IfModule mpm_prefork_module> StartServers 5 MinSpareServers 5 MaxSpareServers 10 MaxClients 150 MaxRequestsPerChild 0 </IfModule> # worker MPM # StartServers: initial number of server processes to start # MaxClients: maximum number of simultaneous client connections # MinSpareThreads: minimum number of worker threads which are kept spare # MaxSpareThreads: maximum number of worker threads which are kept spare # ThreadsPerChild: constant number of worker threads in each server process # MaxRequestsPerChild: maximum number of requests a server process serves <IfModule mpm_worker_module> StartServers 2 MaxClients 150 MinSpareThreads 25 MaxSpareThreads 75 ThreadsPerChild 25 MaxRequestsPerChild 0 </IfModule> # These need to be set in /etc/apache2/envvars User ${APACHE_RUN_USER} Group ${APACHE_RUN_GROUP} # # AccessFileName: The name of the file to look for in each directory # for additional configuration directives. See also the AllowOverride # directive. # AccessFileName .htaccess # # The following lines prevent .htaccess and .htpasswd files from being # viewed by Web clients. # <Files ~ "^\.ht"> Order allow,deny Deny from all </Files> # # DefaultType is the default MIME type the server will use for a document # if it cannot otherwise determine one, such as from filename extensions. # If your server contains mostly text or HTML documents, "text/plain" is # a good value. If most of your content is binary, such as applications # or images, you may want to use "application/octet-stream" instead to # keep browsers from trying to display binary files as though they are # text. # DefaultType text/plain # # HostnameLookups: Log the names of clients or just their IP addresses # e.g., www.apache.org (on) or 204.62.129.132 (off). # The default is off because it'd be overall better for the net if people # had to knowingly turn this feature on, since enabling it means that # each client request will result in AT LEAST one lookup request to the # nameserver. # HostnameLookups Off # ErrorLog: The location of the error log file. # If you do not specify an ErrorLog directive within a <VirtualHost> # container, error messages relating to that virtual host will be # logged here. If you *do* define an error logfile for a <VirtualHost> # container, that host's errors will be logged there and not here. # ErrorLog /var/log/apache2/error.log # # LogLevel: Control the number of messages logged to the error_log. # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. # LogLevel warn # Include module configuration: Include /etc/apache2/mods-enabled/*.load Include /etc/apache2/mods-enabled/*.conf # Include all the user configurations: Include /etc/apache2/httpd.conf # Include ports listing Include /etc/apache2/ports.conf # # The following directives define some format nicknames for use with # a CustomLog directive (see below). # If you are behind a reverse proxy, you might want to change %h into %{X-Forwarded-For}i # LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common LogFormat "%{Referer}i -> %U" referer LogFormat "%{User-agent}i" agent # # ServerTokens # This directive configures what you return as the Server HTTP response # Header. The default is 'Full' which sends information about the OS-Type # and compiled in modules. # Set to one of: Full | OS | Minor | Minimal | Major | Prod # where Full conveys the most information, and Prod the least. # ServerTokens Full # # Optionally add a line containing the server version and virtual host # name to server-generated pages (internal error documents, FTP directory # listings, mod_status and mod_info output etc., but not CGI generated # documents or custom error documents). # Set to "EMail" to also include a mailto: link to the ServerAdmin. # Set to one of: On | Off | EMail # ServerSignature On # # Customizable error responses come in three flavors: # 1) plain text 2) local redirects 3) external redirects # # Some examples: #ErrorDocument 500 "The server made a boo boo." #ErrorDocument 404 /missing.html #ErrorDocument 404 "/cgi-bin/missing_handler.pl" #ErrorDocument 402 http://www.example.com/subscription_info.html # # # Putting this all together, we can internationalize error responses. # # We use Alias to redirect any /error/HTTP_<error>.html.var response to # our collection of by-error message multi-language collections. We use # includes to substitute the appropriate text. # # You can modify the messages' appearance without changing any of the # default HTTP_<error>.html.var files by adding the line: # # Alias /error/include/ "/your/include/path/" # # which allows you to create your own set of files by starting with the # /usr/share/apache2/error/include/ files and copying them to /your/include/path/, # even on a per-VirtualHost basis. The default include files will display # your Apache version number and your ServerAdmin email address regardless # of the setting of ServerSignature. # # The internationalized error documents require mod_alias, mod_include # and mod_negotiation. To activate them, uncomment the following 30 lines. # Alias /error/ "/usr/share/apache2/error/" # # <Directory "/usr/share/apache2/error"> # AllowOverride None # Options IncludesNoExec # AddOutputFilter Includes html # AddHandler type-map var # Order allow,deny # Allow from all # LanguagePriority en cs de es fr it nl sv pt-br ro # ForceLanguagePriority Prefer Fallback # </Directory> # # ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var # ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var # ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var # ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var # ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var # ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var # ErrorDocument 410 /error/HTTP_GONE.html.var # ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var # ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var # ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var # ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var # ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var # ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var # ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var # ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var # ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var # ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var # Include of directories ignores editors' and dpkg's backup files, # see README.Debian for details. # Include generic snippets of statements Include /etc/apache2/conf.d/ # Include the virtual host configurations: Include /etc/apache2/sites-enabled/ My default config file for www on apache NameVirtualHost *:80 <VirtualHost *:80> ServerAdmin [email protected] #SSLEnable #SSLVerifyClient none #SSLCertificateFile /usr/local/ssl/crt/public.crt #SSLCertificateKeyFile /usr/local/ssl/private/private.key DocumentRoot /var/www/site/trunk/html <Directory /> Options FollowSymLinks AllowOverride all </Directory> <Directory /var/www/site/trunk/html> Options Indexes FollowSymLinks MultiViews AllowOverride all Order allow,deny allow from all </Directory> ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ <Directory "/usr/lib/cgi-bin"> AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all </Directory> ErrorLog /var/log/apache2/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog /var/log/apache2/access.log combined ServerSignature On Alias /doc/ "/usr/share/doc/" <Directory "/usr/share/doc/"> Options Indexes MultiViews FollowSymLinks AllowOverride None Order deny,allow Deny from all Allow from 127.0.0.0/255.0.0.0 ::1/128 </Directory> </VirtualHost> My ssl config file NameVirtualHost *:443 <VirtualHost *:443> ServerAdmin [email protected] #SSLEnable #SSLVerifyClient none #SSLCertificateFile /usr/local/ssl/crt/public.crt #SSLCertificateKeyFile /usr/local/ssl/private/private.key DocumentRoot /var/www/site/trunk/html <Directory /> Options FollowSymLinks AllowOverride all </Directory> <Directory /var/www/site/trunk/html> Options Indexes FollowSymLinks MultiViews AllowOverride all Order allow,deny allow from all </Directory> ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ <Directory "/usr/lib/cgi-bin"> AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all </Directory> ErrorLog /var/log/apache2/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn SSLEngine On SSLCertificateFile /usr/local/ssl/crt/public.crt SSLCertificateKeyFile /usr/local/ssl/private/private.key CustomLog /var/log/apache2/access.log combined ServerSignature On Alias /doc/ "/usr/share/doc/" <Directory "/usr/share/doc/"> Options Indexes MultiViews FollowSymLinks AllowOverride None Order deny,allow Deny from all Allow from 127.0.0.0/255.0.0.0 ::1/128 </Directory> </VirtualHost> My /etc/apache2/httpd.conf is blank The directory /etc/apache2/conf.d has nothing in it but one file (charset) contents of /etc/apache2/conf.dcharset # Read the documentation before enabling AddDefaultCharset. # In general, it is only a good idea if you know that all your files # have this encoding. It will override any encoding given in the files # in meta http-equiv or xml encoding tags. #AddDefaultCharset UTF-8 My apache error.log [Wed Jun 03 00:12:31 2009] [error] [client 216.168.43.234] client sent HTTP/1.1 request without hostname (see RFC2616 section 14.23): /w00tw00t.at.ISC.SANS.DFind:) [Wed Jun 03 05:03:51 2009] [error] [client 99.247.237.46] File does not exist: /var/www/site/trunk/html/favicon.ico [Wed Jun 03 05:03:54 2009] [error] [client 99.247.237.46] File does not exist: /var/www/site/trunk/html/favicon.ico [Wed Jun 03 05:13:48 2009] [error] [client 99.247.237.46] File does not exist: /var/www/site/trunk/html/favicon.ico [Wed Jun 03 05:13:51 2009] [error] [client 99.247.237.46] File does not exist: /var/www/site/trunk/html/favicon.ico [Wed Jun 03 05:13:54 2009] [error] [client 99.247.237.46] File does not exist: /var/www/site/trunk/html/favicon.ico [Wed Jun 03 05:13:57 2009] [error] [client 99.247.237.46] File does not exist: /var/www/site/trunk/html/favicon.ico [Wed Jun 03 05:17:28 2009] [error] [client 99.247.237.46] File does not exist: /var/www/site/trunk/html/favicon.ico [Wed Jun 03 05:26:23 2009] [notice] caught SIGWINCH, shutting down gracefully [Wed Jun 03 05:26:34 2009] [notice] Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.6 with Suhosin-Patch mod_ssl/2.2.8 OpenSSL/0.9.8g configured -- resuming normal operations [Wed Jun 03 06:03:41 2009] [notice] caught SIGWINCH, shutting down gracefully [Wed Jun 03 06:03:51 2009] [notice] Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.6 with Suhosin-Patch mod_ssl/2.2.8 OpenSSL/0.9.8g configured -- resuming normal operations [Wed Jun 03 06:25:07 2009] [notice] caught SIGWINCH, shutting down gracefully [Wed Jun 03 06:25:17 2009] [notice] Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.6 with Suhosin-Patch mod_ssl/2.2.8 OpenSSL/0.9.8g configured -- resuming normal operations [Wed Jun 03 12:09:25 2009] [error] [client 61.139.105.163] File does not exist: /var/www/site/trunk/html/fastenv [Wed Jun 03 15:04:42 2009] [notice] Graceful restart requested, doing restart [Wed Jun 03 15:04:43 2009] [notice] Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.6 with Suhosin-Patch mod_ssl/2.2.8 OpenSSL/0.9.8g configured -- resuming normal operations [Wed Jun 03 15:29:51 2009] [error] [client 99.247.237.46] File does not exist: /var/www/site/trunk/html/favicon.ico [Wed Jun 03 15:29:54 2009] [error] [client 99.247.237.46] File does not exist: /var/www/site/trunk/html/favicon.ico [Wed Jun 03 15:30:32 2009] [error] [client 99.247.237.46] File does not exist: /var/www/site/trunk/html/favicon.ico [Wed Jun 03 15:45:54 2009] [notice] caught SIGWINCH, shutting down gracefully [Wed Jun 03 15:46:05 2009] [notice] Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.6 with Suhosin-Patch mod_ssl/2.2.8 OpenSSL/0.9.8g configured -- resuming normal operations

    Read the article

  • Python script is exiting with no output and I have no idea why

    - by Adam Tuttle
    I'm attempting to debug a Subversion post-commit hook that calls some python scripts. What I've been able to determine so far is that when I run post-commit.bat manually (I've created a wrapper for it to make it easier) everything succeeds, but when SVN runs it one particular step doesn't work. We're using CollabNet SVNServe, which I know from the documentation removes all environment variables. This had caused some problems earlier, but shouldn't be an issue now. Before Subversion calls a hook script, it removes all variables - including $PATH on Unix, and %PATH% on Windows - from the environment. Therefore, your script can only run another program if you spell out that program's absolute name. The relevant portion of post-commit.bat is: echo -------------------------- >> c:\svn-repos\company\hooks\svn2ftp.out.log set SITENAME=staging set SVNPATH=branches/staging/wwwroot/ "C:\Python3\python.exe" C:\svn-repos\company\hooks\svn2ftp.py ^ --svnUser="svnusername" ^ --svnPass="svnpassword" ^ --ftp-user=ftpuser ^ --ftp-password=ftppassword ^ --ftp-remote-dir=/ ^ --access-url=svn://10.0.100.6/company ^ --status-file="C:\svn-repos\company\hooks\svn2ftp-%SITENAME%.dat" ^ --project-directory=%SVNPATH% "staging.company.com" %1 %2 >> c:\svn-repos\company\hooks\svn2ftp.out.log echo -------------------------- >> c:\svn-repos\company\hooks\svn2ftp.out.log When I run post-commit.bat manually, for example: post-commit c:\svn-repos\company 12345, I see output like the following in svn2ftp.out.log: -------------------------- args1: c:\svn-repos\company args0: staging.company.com abspath: c:\svn-repos\company project_dir: branches/staging/wwwroot/ local_repos_path: c:\svn-repos\company getting youngest revision... done, up-to-date -------------------------- However, when I commit something to the repo and it runs automatically, the output is: -------------------------- -------------------------- svn2ftp.py is a bit long, so I apologize but here goes. I'll have some notes/disclaimers about its contents below it. #!/usr/bin/env python """Usage: svn2ftp.py [OPTION...] FTP-HOST REPOS-PATH Upload to FTP-HOST changes committed to the Subversion repository at REPOS-PATH. Uses svn diff --summarize to only propagate the changed files Options: -?, --help Show this help message. -u, --ftp-user=USER The username for the FTP server. Default: 'anonymous' -p, --ftp-password=P The password for the FTP server. Default: '@' -P, --ftp-port=X Port number for the FTP server. Default: 21 -r, --ftp-remote-dir=DIR The remote directory that is expected to resemble the repository project directory -a, --access-url=URL This is the URL that should be used when trying to SVN export files so that they can be uploaded to the FTP server -s, --status-file=PATH Required. This script needs to store the last successful revision that was transferred to the server. PATH is the location of this file. -d, --project-directory=DIR If the project you are interested in sending to the FTP server is not under the root of the repository (/), set this parameter. Example: -d 'project1/trunk/' This should NOT start with a '/'. 2008.5.2 CKS Fixed possible Windows-related bug with tempfile, where the script didn't have permission to write to the tempfile. Replaced this with a open()-created file created in the CWD. 2008.5.13 CKS Added error logging. Added exception for file-not-found errors when deleting files. 2008.5.14 CKS Change file open to 'rb' mode, to prevent Python's universal newline support from stripping CR characters, causing later comparisons between FTP and SVN to report changes. """ try: import sys, os import logging logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename='svn2ftp.debug.log', filemode='a' ) console = logging.StreamHandler() console.setLevel(logging.ERROR) logging.getLogger('').addHandler(console) import getopt, tempfile, smtplib, traceback, subprocess from io import StringIO import pysvn import ftplib import inspect except Exception as e: logging.error(e) #capture the location of the error frame = inspect.currentframe() stack_trace = traceback.format_stack(frame) logging.debug(stack_trace) print(stack_trace) #end capture sys.exit(1) #defaults host = "" user = "anonymous" password = "@" port = 21 repo_path = "" local_repos_path = "" status_file = "" project_directory = "" remote_base_directory = "" toAddrs = "[email protected]" youngest_revision = "" def email(toAddrs, message, subject, fromAddr='[email protected]'): headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (fromAddr, toAddrs, subject) message = headers + message logging.info('sending email to %s...' % toAddrs) server = smtplib.SMTP('smtp.company.com') server.set_debuglevel(1) server.sendmail(fromAddr, toAddrs, message) server.quit() logging.info('email sent') def captureErrorMessage(e): sout = StringIO() traceback.print_exc(file=sout) errorMessage = '\n'+('*'*80)+('\n%s'%e)+('\n%s\n'%sout.getvalue())+('*'*80) return errorMessage def usage_and_exit(errmsg): """Print a usage message, plus an ERRMSG (if provided), then exit. If ERRMSG is provided, the usage message is printed to stderr and the script exits with a non-zero error code. Otherwise, the usage message goes to stdout, and the script exits with a zero errorcode.""" if errmsg is None: stream = sys.stdout else: stream = sys.stderr print(__doc__, file=stream) if errmsg: print("\nError: %s" % (errmsg), file=stream) sys.exit(2) sys.exit(0) def read_args(): global host global user global password global port global repo_path global local_repos_path global status_file global project_directory global remote_base_directory global youngest_revision try: opts, args = getopt.gnu_getopt(sys.argv[1:], "?u:p:P:r:a:s:d:SU:SP:", ["help", "ftp-user=", "ftp-password=", "ftp-port=", "ftp-remote-dir=", "access-url=", "status-file=", "project-directory=", "svnUser=", "svnPass=" ]) except getopt.GetoptError as msg: usage_and_exit(msg) for opt, arg in opts: if opt in ("-?", "--help"): usage_and_exit() elif opt in ("-u", "--ftp-user"): user = arg elif opt in ("-p", "--ftp-password"): password = arg elif opt in ("-SU", "--svnUser"): svnUser = arg elif opt in ("-SP", "--svnPass"): svnPass = arg elif opt in ("-P", "--ftp-port"): try: port = int(arg) except ValueError as msg: usage_and_exit("Invalid value '%s' for --ftp-port." % (arg)) if port < 1 or port > 65535: usage_and_exit("Value for --ftp-port must be a positive integer less than 65536.") elif opt in ("-r", "--ftp-remote-dir"): remote_base_directory = arg elif opt in ("-a", "--access-url"): repo_path = arg elif opt in ("-s", "--status-file"): status_file = os.path.abspath(arg) elif opt in ("-d", "--project-directory"): project_directory = arg if len(args) != 3: print(str(args)) usage_and_exit("host and/or local_repos_path not specified (" + len(args) + ")") host = args[0] print("args1: " + args[1]) print("args0: " + args[0]) print("abspath: " + os.path.abspath(args[1])) local_repos_path = os.path.abspath(args[1]) print('project_dir:',project_directory) youngest_revision = int(args[2]) if status_file == "" : usage_and_exit("No status file specified") def main(): global host global user global password global port global repo_path global local_repos_path global status_file global project_directory global remote_base_directory global youngest_revision read_args() #repository,fs_ptr #get youngest revision print("local_repos_path: " + local_repos_path) print('getting youngest revision...') #youngest_revision = fs.youngest_rev(fs_ptr) assert youngest_revision, "Unable to lookup youngest revision." last_sent_revision = get_last_revision() if youngest_revision == last_sent_revision: # no need to continue. we should be up to date. print('done, up-to-date') return if last_sent_revision or youngest_revision < 10: # Only compare revisions if the DAT file contains a valid # revision number. Otherwise we risk waiting forever while # we parse and uploading every revision in the repo in the case # where a repository is retroactively configured to sync with ftp. pysvn_client = pysvn.Client() pysvn_client.callback_get_login = get_login rev1 = pysvn.Revision(pysvn.opt_revision_kind.number, last_sent_revision) rev2 = pysvn.Revision(pysvn.opt_revision_kind.number, youngest_revision) summary = pysvn_client.diff_summarize(repo_path, rev1, repo_path, rev2, True, False) print('summary len:',len(summary)) if len(summary) > 0 : print('connecting to %s...' % host) ftp = FTPClient(host, user, password) print('connected to %s' % host) ftp.base_path = remote_base_directory print('set remote base directory to %s' % remote_base_directory) #iterate through all the differences between revisions for change in summary : #determine whether the path of the change is relevant to the path that is being sent, and modify the path as appropriate. print('change path:',change.path) ftp_relative_path = apply_basedir(change.path) print('ftp rel path:',ftp_relative_path) #only try to sync path if the path is in our project_directory if ftp_relative_path != "" : is_file = (change.node_kind == pysvn.node_kind.file) if str(change.summarize_kind) == "delete" : print("deleting: " + ftp_relative_path) try: ftp.delete_path("/" + ftp_relative_path, is_file) except ftplib.error_perm as e: if 'cannot find the' in str(e) or 'not found' in str(e): # Log, but otherwise ignore path-not-found errors # when deleting, since it's not a disaster if the file # we want to delete is already gone. logging.error(captureErrorMessage(e)) else: raise elif str(change.summarize_kind) == "added" or str(change.summarize_kind) == "modified" : local_file = "" if is_file : local_file = svn_export_temp(pysvn_client, repo_path, rev2, change.path) print("uploading file: " + ftp_relative_path) ftp.upload_path("/" + ftp_relative_path, is_file, local_file) if is_file : os.remove(local_file) elif str(change.summarize_kind) == "normal" : print("skipping 'normal' element: " + ftp_relative_path) else : raise str("Unknown change summarize kind: " + str(change.summarize_kind) + ", path: " + ftp_relative_path) ftp.close() #write back the last revision that was synced print("writing last revision: " + str(youngest_revision)) set_last_revision(youngest_revision) # todo: undo def get_login(a,b,c,d): #arguments don't matter, we're always going to return the same thing try: return True, "svnUsername", "svnPassword", True except Exception as e: logging.error(e) #capture the location of the error frame = inspect.currentframe() stack_trace = traceback.format_stack(frame) logging.debug(stack_trace) #end capture sys.exit(1) #functions for persisting the last successfully synced revision def get_last_revision(): if os.path.isfile(status_file) : f=open(status_file, 'r') line = f.readline() f.close() try: i = int(line) except ValueError: i = 0 else: i = 0 f = open(status_file, 'w') f.write(str(i)) f.close() return i def set_last_revision(rev) : f = open(status_file, 'w') f.write(str(rev)) f.close() #augmented ftp client class that can work off a base directory class FTPClient(ftplib.FTP) : def __init__(self, host, username, password) : self.base_path = "" self.current_path = "" ftplib.FTP.__init__(self, host, username, password) def cwd(self, path) : debug_path = path if self.current_path == "" : self.current_path = self.pwd() print("pwd: " + self.current_path) if not os.path.isabs(path) : debug_path = self.base_path + "<" + path path = os.path.join(self.current_path, path) elif self.base_path != "" : debug_path = self.base_path + ">" + path.lstrip("/") path = os.path.join(self.base_path, path.lstrip("/")) path = os.path.normpath(path) #by this point the path should be absolute. if path != self.current_path : print("change from " + self.current_path + " to " + debug_path) ftplib.FTP.cwd(self, path) self.current_path = path else : print("staying put : " + self.current_path) def cd_or_create(self, path) : assert os.path.isabs(path), "absolute path expected (" + path + ")" try: self.cwd(path) except ftplib.error_perm as e: for folder in path.split('/'): if folder == "" : self.cwd("/") continue try: self.cwd(folder) except: print("mkd: (" + path + "):" + folder) self.mkd(folder) self.cwd(folder) def upload_path(self, path, is_file, local_path) : if is_file: (path, filename) = os.path.split(path) self.cd_or_create(path) # Use read-binary to avoid universal newline support from stripping CR characters. f = open(local_path, 'rb') self.storbinary("STOR " + filename, f) f.close() else: self.cd_or_create(path) def delete_path(self, path, is_file) : (path, filename) = os.path.split(path) print("trying to delete: " + path + ", " + filename) self.cwd(path) try: if is_file : self.delete(filename) else: self.delete_path_recursive(filename) except ftplib.error_perm as e: if 'The system cannot find the' in str(e) or '550 File not found' in str(e): # Log, but otherwise ignore path-not-found errors # when deleting, since it's not a disaster if the file # we want to delete is already gone. logging.error(captureErrorMessage(e)) else: raise def delete_path_recursive(self, path): if path == "/" : raise "WARNING: trying to delete '/'!" for node in self.nlst(path) : if node == path : #it's a file. delete and return self.delete(path) return if node != "." and node != ".." : self.delete_path_recursive(os.path.join(path, node)) try: self.rmd(path) except ftplib.error_perm as msg : sys.stderr.write("Error deleting directory " + os.path.join(self.current_path, path) + " : " + str(msg)) # apply the project_directory setting def apply_basedir(path) : #remove any leading stuff (in this case, "trunk/") and decide whether file should be propagated if not path.startswith(project_directory) : return "" return path.replace(project_directory, "", 1) def svn_export_temp(pysvn_client, base_path, rev, path) : # Causes access denied error. Couldn't deduce Windows-perm issue. # It's possible Python isn't garbage-collecting the open file-handle in time for pysvn to re-open it. # Regardless, just generating a simple filename seems to work. #(fd, dest_path) = tempfile.mkstemp() dest_path = tmpName = '%s.tmp' % __file__ exportPath = os.path.join(base_path, path).replace('\\','/') print('exporting %s to %s' % (exportPath, dest_path)) pysvn_client.export( exportPath, dest_path, force=False, revision=rev, native_eol=None, ignore_externals=False, recurse=True, peg_revision=rev ) return dest_path if __name__ == "__main__": logging.info('svnftp.start') try: main() logging.info('svnftp.done') except Exception as e: # capture the location of the error for debug purposes frame = inspect.currentframe() stack_trace = traceback.format_stack(frame) logging.debug(stack_trace[:-1]) print(stack_trace) # end capture error_text = '\nFATAL EXCEPTION!!!\n'+captureErrorMessage(e) subject = "ALERT: SVN2FTP Error" message = """An Error occurred while trying to FTP an SVN commit. repo_path = %(repo_path)s\n local_repos_path = %(local_repos_path)s\n project_directory = %(project_directory)s\n remote_base_directory = %(remote_base_directory)s\n error_text = %(error_text)s """ % globals() email(toAddrs, message, subject) logging.error(e) Notes/Disclaimers: I have basically no python training so I'm learning as I go and spending lots of time reading docs to figure stuff out. The body of get_login is in a try block because I was getting strange errors saying there was an unhandled exception in callback_get_login. Never figured out why, but it seems fine now. Let sleeping dogs lie, right? The username and password for get_login are currently hard-coded (but correct) just to eliminate variables and try to change as little as possible at once. (I added the svnuser and svnpass arguments to the existing argument parsing.) So that's where I am. I can't figure out why on earth it's not printing anything into svn2ftp.out.log. If you're wondering, the output for one of these failed attempts in svn2ftp.debug.log is: 2012-09-06 15:18:12,496 INFO svnftp.start 2012-09-06 15:18:12,496 INFO svnftp.done And it's no different on a successful run. So there's nothing useful being logged. I'm lost. I've gone way down the rabbit hole on this one, and don't know where to go from here. Any ideas?

    Read the article

< Previous Page | 6 7 8 9 10