Search Results

Search found 10841 results on 434 pages for 'air native extension'.

Page 122/434 | < Previous Page | 118 119 120 121 122 123 124 125 126 127 128 129  | Next Page >

  • Restrict allowed file upload types PHP

    - by clang1234
    Right now I have a function which takes my uploaded file, checks the extension, and if it matches an array of valid extensions it's processed. It's a contact list importer. What I need to figure out is how to be sure that file (in this case a .csv) is actually what it says it is (ex. not an excel file that just got renamed as a .csv). Our servers run PHP 5.2.13 Here's the current validation function I have public static function validateExtension($file_name,$ext_array) { $extension = strtolower(strrchr($file_name,".")); $valid_extension="FALSE"; if (!$file_name) { return false; } else { if (!$ext_array) { return true; } else { foreach ($ext_array as $value) { $first_char = substr($value,0,1); if ($first_char <> ".") { $extensions[] = ".".strtolower($value); } else { $extensions[] = strtolower($value); } } foreach ($extensions as $value) { if ($value == $extension) { $valid_extension = "TRUE"; } } if ($valid_extension==="TRUE") { return true; } else { return false; } } } }

    Read the article

  • Jython & Mysql - what is the current practice for connection?

    - by Sector7B
    Just trying jython for the first time, because something came up at work that would fit for this perfect for it. I assume jython can make mysql jdbc connection using the mysql jdbc driver. After googling and reading, however I am having problems and it seems jython specific and probably simple. so i do jython: Jython 2.5.1 (Release_2_5_1:6813, Sep 26 2009, 13:47:54) [Java HotSpot(TM) 64-Bit Server VM (Apple Inc.)] on java1.6.0_17 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> print sys.path ['', '/JYTHONPATH/mysql-connector-java-5.1.10-bin.jar', '/WorkArea/Apps/jython/jython2.5.1/Lib', '__classpath__', '__pyclasspath__/', '/WorkArea/Apps/jython/jython2.5.1/Lib/site-packages'] >>> code i'm running from java.lang import * from java.sql import * driverName="com.mysql.jdbc.Driver" Class.forName(driverName) url = "jdbc:mysql://localhost/test?user=jgreenaw&password=" con = DriverManager.getConnection(url) stmt = con.createStatement() output riux:Desktop$ jython pymysql.py Traceback (most recent call last): File "pymysql.py", line 7, in <module> Class.forName(driverName) at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:315) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:330) at java.lang.ClassLoader.loadClass(ClassLoader.java:250) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:398) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:169) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) java.lang.ClassNotFoundException: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver any advice? thanks

    Read the article

  • read files from directory and filter files from Java

    - by Adnan
    The following codes goes through all directories and sub-directories and outputs just .java files; import java.io.File; public class DirectoryReader { private static String extension = "none"; private static String fileName; public static void main(String[] args ){ String dir = "C:/tmp"; File aFile = new File(dir); ReadDirectory(aFile); } private static void ReadDirectory(File aFile) { File[] listOfFiles = aFile.listFiles(); if (aFile.isDirectory()) { listOfFiles = aFile.listFiles(); if(listOfFiles!=null) { for(int i=0; i < listOfFiles.length; i++ ) { if (listOfFiles[i].isFile()) { fileName = listOfFiles[i].toString(); int dotPos = fileName.lastIndexOf("."); if (dotPos > 0) { extension = fileName.substring(dotPos); } if (extension.equals(".java")) { System.out.println("FILE:" + listOfFiles[i] ); } } if(listOfFiles[i].isDirectory()) { ReadDirectory(listOfFiles[i]); } } } } } } Is this efficient? What could be done to increase the speed? All ideas are welcome.

    Read the article

  • Why does VS2005 skip execution of lines when debugging managed C++ without optimizations?

    - by Sakin
    I ran into a rather odd behavior that I don't even know how to start describing. I wrote a piece of managed C++ code that makes calls to native methods. A (very) simplified version of the code would look like this (I know it looks like a full native function, just assume there is managed stuff being done all over the place): int somefunction(ptrHolder x) { // the accessptr method returns a native pointer if (x.accessptr() != nullptr) // I tried this with nullptr, NULL, 0) { try { x->doSomeNativeVeryImportantStuff(); // or whatever, doesn't matter } catch (SomeCustomExceptionClass &) { return 0; } } SomeOtherNativeClass::doStaticMagic(); return 1; } I compiled this code without optimizations using the /clr flag (VS.NET 2005, SP2) and when running it in the debugger I get to the if statement, since the pointer is actually null, I don't enter the if, but surprisingly, the cursor jumps directly to the return 1 statement, ignoring the doStaticMagic() method completely!!! When looking at the assembly code, I see that it really jumps directly to that line. If I force the debugger to enter the if block, I also jump to the return 1 statement after I press F10. Any ideas why this is happening? Thanks, Ariel

    Read the article

  • cython setup.py gives .o instead of .dll

    - by alok1974
    Hi, I am a newbie to cython, so pardon me if I am missing something obvious here. I am trying to build c extensions to be used in python for enhanced performance. I have fc.py module with a bunch of function and trying to generate a .dll through cython using dsutils and running on win64: c:\python26\python c:\cythontest\setup.py build_ext --inplace I have the dsutils.cfg in C:\Python26\Lib\distutils. As required the disutils.cfg has the following config settings: [build] compiler = mingw32 My startup.py looks like this: from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext ext_modules = [Extension('fc', [r'C:\cythonTest\fc.pyx'])] setup( name = 'FC Extensions', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules ) I have latest version mingw for target/host amdwin64 type builds. I have the latest version of cython for python26 for win64. Cython does give me an fc.c without errors, only a few warning for type conversions, which I will handle once I have it right. Further it produces fc.def an fc.o files Instead of giving a .dll. I get no errors. I find on threads that it will create the .so or .dll automatically as required, which is not happening.

    Read the article

  • Reference properteries declared in a protocol and implemented in the anonymous category?

    - by Heath Borders
    I have the following protocol: @protocol MyProtocol @property (nonatomic, retain) NSObject *myProtocolProperty; -(void) myProtocolMethod; @end and I have the following class: @interface MyClass : NSObject { } @end I have a class extension declared, I have to redeclare my protocol properties here or else I can't implement them with the rest of my class. @interface()<MyProtocol> @property (nonatomic, retain) NSObject *myExtensionProperty; /* * This redeclaration is required or my @synthesize myProtocolProperty fails */ @property (nonatomic, retain) NSObject *myProtocolProperty; - (void) myExtensionMethod; @end @implementation MyClass @synthesize myProtocolProperty = _myProtocolProperty; @synthesize myExtensionProperty = _myExtensionProperty; - (void) myProtocolMethod { } - (void) myExtensionMethod { } @end In a consumer method, I can call my protocol methods and properties just fine. Calling my extension methods and properties produces a warning and an error respectively. - (void) consumeMyClassWithMyProtocol: (MyClass<MyProtocol> *) myClassWithMyProtocol { myClassWithMyProtocol.myProtocolProperty; // works, yay! [myClassWithMyProtocol myProtocolMethod]; // works, yay! myClassWithMyProtocol.myExtensionProperty; // compiler error, yay! [myClassWithMyProtocol myExtensionMethod]; // compiler warning, yay! } Is there any way I can avoid redeclaring the properties in MyProtocol within my class extension in order to implement MyProtocol privately?

    Read the article

  • Creating a dynamic, extensible C# Expando Object

    - by Rick Strahl
    I love dynamic functionality in a strongly typed language because it offers us the best of both worlds. In C# (or any of the main .NET languages) we now have the dynamic type that provides a host of dynamic features for the static C# language. One place where I've found dynamic to be incredibly useful is in building extensible types or types that expose traditionally non-object data (like dictionaries) in easier to use and more readable syntax. I wrote about a couple of these for accessing old school ADO.NET DataRows and DataReaders more easily for example. These classes are dynamic wrappers that provide easier syntax and auto-type conversions which greatly simplifies code clutter and increases clarity in existing code. ExpandoObject in .NET 4.0 Another great use case for dynamic objects is the ability to create extensible objects - objects that start out with a set of static members and then can add additional properties and even methods dynamically. The .NET 4.0 framework actually includes an ExpandoObject class which provides a very dynamic object that allows you to add properties and methods on the fly and then access them again. For example with ExpandoObject you can do stuff like this:dynamic expand = new ExpandoObject(); expand.Name = "Rick"; expand.HelloWorld = (Func<string, string>) ((string name) => { return "Hello " + name; }); Console.WriteLine(expand.Name); Console.WriteLine(expand.HelloWorld("Dufus")); Internally ExpandoObject uses a Dictionary like structure and interface to store properties and methods and then allows you to add and access properties and methods easily. As cool as ExpandoObject is it has a few shortcomings too: It's a sealed type so you can't use it as a base class It only works off 'properties' in the internal Dictionary - you can't expose existing type data It doesn't serialize to XML or with DataContractSerializer/DataContractJsonSerializer Expando - A truly extensible Object ExpandoObject is nice if you just need a dynamic container for a dictionary like structure. However, if you want to build an extensible object that starts out with a set of strongly typed properties and then allows you to extend it, ExpandoObject does not work because it's a sealed class that can't be inherited. I started thinking about this very scenario for one of my applications I'm building for a customer. In this system we are connecting to various different user stores. Each user store has the same basic requirements for username, password, name etc. But then each store also has a number of extended properties that is available to each application. In the real world scenario the data is loaded from the database in a data reader and the known properties are assigned from the known fields in the database. All unknown fields are then 'added' to the expando object dynamically. In the past I've done this very thing with a separate property - Properties - just like I do for this class. But the property and dictionary syntax is not ideal and tedious to work with. I started thinking about how to represent these extra property structures. One way certainly would be to add a Dictionary, or an ExpandoObject to hold all those extra properties. But wouldn't it be nice if the application could actually extend an existing object that looks something like this as you can with the Expando object:public class User : Westwind.Utilities.Dynamic.Expando { public string Email { get; set; } public string Password { get; set; } public string Name { get; set; } public bool Active { get; set; } public DateTime? ExpiresOn { get; set; } } and then simply start extending the properties of this object dynamically? Using the Expando object I describe later you can now do the following:[TestMethod] public void UserExampleTest() { var user = new User(); // Set strongly typed properties user.Email = "[email protected]"; user.Password = "nonya123"; user.Name = "Rickochet"; user.Active = true; // Now add dynamic properties dynamic duser = user; duser.Entered = DateTime.Now; duser.Accesses = 1; // you can also add dynamic props via indexer user["NickName"] = "AntiSocialX"; duser["WebSite"] = "http://www.west-wind.com/weblog"; // Access strong type through dynamic ref Assert.AreEqual(user.Name,duser.Name); // Access strong type through indexer Assert.AreEqual(user.Password,user["Password"]); // access dyanmically added value through indexer Assert.AreEqual(duser.Entered,user["Entered"]); // access index added value through dynamic Assert.AreEqual(user["NickName"],duser.NickName); // loop through all properties dynamic AND strong type properties (true) foreach (var prop in user.GetProperties(true)) { object val = prop.Value; if (val == null) val = "null"; Console.WriteLine(prop.Key + ": " + val.ToString()); } } As you can see this code somewhat blurs the line between a static and dynamic type. You start with a strongly typed object that has a fixed set of properties. You can then cast the object to dynamic (as I discussed in my last post) and add additional properties to the object. You can also use an indexer to add dynamic properties to the object. To access the strongly typed properties you can use either the strongly typed instance, the indexer or the dynamic cast of the object. Personally I think it's kinda cool to have an easy way to access strongly typed properties by string which can make some data scenarios much easier. To access the 'dynamically added' properties you can use either the indexer on the strongly typed object, or property syntax on the dynamic cast. Using the dynamic type allows all three modes to work on both strongly typed and dynamic properties. Finally you can iterate over all properties, both dynamic and strongly typed if you chose. Lots of flexibility. Note also that by default the Expando object works against the (this) instance meaning it extends the current object. You can also pass in a separate instance to the constructor in which case that object will be used to iterate over to find properties rather than this. Using this approach provides some really interesting functionality when use the dynamic type. To use this we have to add an explicit constructor to the Expando subclass:public class User : Westwind.Utilities.Dynamic.Expando { public string Email { get; set; } public string Password { get; set; } public string Name { get; set; } public bool Active { get; set; } public DateTime? ExpiresOn { get; set; } public User() : base() { } // only required if you want to mix in seperate instance public User(object instance) : base(instance) { } } to allow the instance to be passed. When you do you can now do:[TestMethod] public void ExpandoMixinTest() { // have Expando work on Addresses var user = new User( new Address() ); // cast to dynamicAccessToPropertyTest dynamic duser = user; // Set strongly typed properties duser.Email = "[email protected]"; user.Password = "nonya123"; // Set properties on address object duser.Address = "32 Kaiea"; //duser.Phone = "808-123-2131"; // set dynamic properties duser.NonExistantProperty = "This works too"; // shows default value Address.Phone value Console.WriteLine(duser.Phone); } Using the dynamic cast in this case allows you to access *three* different 'objects': The strong type properties, the dynamically added properties in the dictionary and the properties of the instance passed in! Effectively this gives you a way to simulate multiple inheritance (which is scary - so be very careful with this, but you can do it). How Expando works Behind the scenes Expando is a DynamicObject subclass as I discussed in my last post. By implementing a few of DynamicObject's methods you can basically create a type that can trap 'property missing' and 'method missing' operations. When you access a non-existant property a known method is fired that our code can intercept and provide a value for. Internally Expando uses a custom dictionary implementation to hold the dynamic properties you might add to your expandable object. Let's look at code first. The code for the Expando type is straight forward and given what it provides relatively short. Here it is.using System; using System.Collections.Generic; using System.Linq; using System.Dynamic; using System.Reflection; namespace Westwind.Utilities.Dynamic { /// <summary> /// Class that provides extensible properties and methods. This /// dynamic object stores 'extra' properties in a dictionary or /// checks the actual properties of the instance. /// /// This means you can subclass this expando and retrieve either /// native properties or properties from values in the dictionary. /// /// This type allows you three ways to access its properties: /// /// Directly: any explicitly declared properties are accessible /// Dynamic: dynamic cast allows access to dictionary and native properties/methods /// Dictionary: Any of the extended properties are accessible via IDictionary interface /// </summary> [Serializable] public class Expando : DynamicObject, IDynamicMetaObjectProvider { /// <summary> /// Instance of object passed in /// </summary> object Instance; /// <summary> /// Cached type of the instance /// </summary> Type InstanceType; PropertyInfo[] InstancePropertyInfo { get { if (_InstancePropertyInfo == null && Instance != null) _InstancePropertyInfo = Instance.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly); return _InstancePropertyInfo; } } PropertyInfo[] _InstancePropertyInfo; /// <summary> /// String Dictionary that contains the extra dynamic values /// stored on this object/instance /// </summary> /// <remarks>Using PropertyBag to support XML Serialization of the dictionary</remarks> public PropertyBag Properties = new PropertyBag(); //public Dictionary<string,object> Properties = new Dictionary<string, object>(); /// <summary> /// This constructor just works off the internal dictionary and any /// public properties of this object. /// /// Note you can subclass Expando. /// </summary> public Expando() { Initialize(this); } /// <summary> /// Allows passing in an existing instance variable to 'extend'. /// </summary> /// <remarks> /// You can pass in null here if you don't want to /// check native properties and only check the Dictionary! /// </remarks> /// <param name="instance"></param> public Expando(object instance) { Initialize(instance); } protected virtual void Initialize(object instance) { Instance = instance; if (instance != null) InstanceType = instance.GetType(); } /// <summary> /// Try to retrieve a member by name first from instance properties /// followed by the collection entries. /// </summary> /// <param name="binder"></param> /// <param name="result"></param> /// <returns></returns> public override bool TryGetMember(GetMemberBinder binder, out object result) { result = null; // first check the Properties collection for member if (Properties.Keys.Contains(binder.Name)) { result = Properties[binder.Name]; return true; } // Next check for Public properties via Reflection if (Instance != null) { try { return GetProperty(Instance, binder.Name, out result); } catch { } } // failed to retrieve a property result = null; return false; } /// <summary> /// Property setter implementation tries to retrieve value from instance /// first then into this object /// </summary> /// <param name="binder"></param> /// <param name="value"></param> /// <returns></returns> public override bool TrySetMember(SetMemberBinder binder, object value) { // first check to see if there's a native property to set if (Instance != null) { try { bool result = SetProperty(Instance, binder.Name, value); if (result) return true; } catch { } } // no match - set or add to dictionary Properties[binder.Name] = value; return true; } /// <summary> /// Dynamic invocation method. Currently allows only for Reflection based /// operation (no ability to add methods dynamically). /// </summary> /// <param name="binder"></param> /// <param name="args"></param> /// <param name="result"></param> /// <returns></returns> public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { if (Instance != null) { try { // check instance passed in for methods to invoke if (InvokeMethod(Instance, binder.Name, args, out result)) return true; } catch { } } result = null; return false; } /// <summary> /// Reflection Helper method to retrieve a property /// </summary> /// <param name="instance"></param> /// <param name="name"></param> /// <param name="result"></param> /// <returns></returns> protected bool GetProperty(object instance, string name, out object result) { if (instance == null) instance = this; var miArray = InstanceType.GetMember(name, BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance); if (miArray != null && miArray.Length > 0) { var mi = miArray[0]; if (mi.MemberType == MemberTypes.Property) { result = ((PropertyInfo)mi).GetValue(instance,null); return true; } } result = null; return false; } /// <summary> /// Reflection helper method to set a property value /// </summary> /// <param name="instance"></param> /// <param name="name"></param> /// <param name="value"></param> /// <returns></returns> protected bool SetProperty(object instance, string name, object value) { if (instance == null) instance = this; var miArray = InstanceType.GetMember(name, BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance); if (miArray != null && miArray.Length > 0) { var mi = miArray[0]; if (mi.MemberType == MemberTypes.Property) { ((PropertyInfo)mi).SetValue(Instance, value, null); return true; } } return false; } /// <summary> /// Reflection helper method to invoke a method /// </summary> /// <param name="instance"></param> /// <param name="name"></param> /// <param name="args"></param> /// <param name="result"></param> /// <returns></returns> protected bool InvokeMethod(object instance, string name, object[] args, out object result) { if (instance == null) instance = this; // Look at the instanceType var miArray = InstanceType.GetMember(name, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance); if (miArray != null && miArray.Length > 0) { var mi = miArray[0] as MethodInfo; result = mi.Invoke(Instance, args); return true; } result = null; return false; } /// <summary> /// Convenience method that provides a string Indexer /// to the Properties collection AND the strongly typed /// properties of the object by name. /// /// // dynamic /// exp["Address"] = "112 nowhere lane"; /// // strong /// var name = exp["StronglyTypedProperty"] as string; /// </summary> /// <remarks> /// The getter checks the Properties dictionary first /// then looks in PropertyInfo for properties. /// The setter checks the instance properties before /// checking the Properties dictionary. /// </remarks> /// <param name="key"></param> /// /// <returns></returns> public object this[string key] { get { try { // try to get from properties collection first return Properties[key]; } catch (KeyNotFoundException ex) { // try reflection on instanceType object result = null; if (GetProperty(Instance, key, out result)) return result; // nope doesn't exist throw; } } set { if (Properties.ContainsKey(key)) { Properties[key] = value; return; } // check instance for existance of type first var miArray = InstanceType.GetMember(key, BindingFlags.Public | BindingFlags.GetProperty); if (miArray != null && miArray.Length > 0) SetProperty(Instance, key, value); else Properties[key] = value; } } /// <summary> /// Returns and the properties of /// </summary> /// <param name="includeProperties"></param> /// <returns></returns> public IEnumerable<KeyValuePair<string,object>> GetProperties(bool includeInstanceProperties = false) { if (includeInstanceProperties && Instance != null) { foreach (var prop in this.InstancePropertyInfo) yield return new KeyValuePair<string, object>(prop.Name, prop.GetValue(Instance, null)); } foreach (var key in this.Properties.Keys) yield return new KeyValuePair<string, object>(key, this.Properties[key]); } /// <summary> /// Checks whether a property exists in the Property collection /// or as a property on the instance /// </summary> /// <param name="item"></param> /// <returns></returns> public bool Contains(KeyValuePair<string, object> item, bool includeInstanceProperties = false) { bool res = Properties.ContainsKey(item.Key); if (res) return true; if (includeInstanceProperties && Instance != null) { foreach (var prop in this.InstancePropertyInfo) { if (prop.Name == item.Key) return true; } } return false; } } } Although the Expando class supports an indexer, it doesn't actually implement IDictionary or even IEnumerable. It only provides the indexer and Contains() and GetProperties() methods, that work against the Properties dictionary AND the internal instance. The reason for not implementing IDictionary is that a) it doesn't add much value since you can access the Properties dictionary directly and that b) I wanted to keep the interface to class very lean so that it can serve as an entity type if desired. Implementing these IDictionary (or even IEnumerable) causes LINQ extension methods to pop up on the type which obscures the property interface and would only confuse the purpose of the type. IDictionary and IEnumerable are also problematic for XML and JSON Serialization - the XML Serializer doesn't serialize IDictionary<string,object>, nor does the DataContractSerializer. The JavaScriptSerializer does serialize, but it treats the entire object like a dictionary and doesn't serialize the strongly typed properties of the type, only the dictionary values which is also not desirable. Hence the decision to stick with only implementing the indexer to support the user["CustomProperty"] functionality and leaving iteration functions to the publicly exposed Properties dictionary. Note that the Dictionary used here is a custom PropertyBag class I created to allow for serialization to work. One important aspect for my apps is that whatever custom properties get added they have to be accessible to AJAX clients since the particular app I'm working on is a SIngle Page Web app where most of the Web access is through JSON AJAX calls. PropertyBag can serialize to XML and one way serialize to JSON using the JavaScript serializer (not the DCS serializers though). The key components that make Expando work in this code are the Properties Dictionary and the TryGetMember() and TrySetMember() methods. The Properties collection is public so if you choose you can explicitly access the collection to get better performance or to manipulate the members in internal code (like loading up dynamic values form a database). Notice that TryGetMember() and TrySetMember() both work against the dictionary AND the internal instance to retrieve and set properties. This means that user["Name"] works against native properties of the object as does user["Name"] = "RogaDugDog". What's your Use Case? This is still an early prototype but I've plugged it into one of my customer's applications and so far it's working very well. The key features for me were the ability to easily extend the type with values coming from a database and exposing those values in a nice and easy to use manner. I'm also finding that using this type of object for ViewModels works very well to add custom properties to view models. I suspect there will be lots of uses for this - I've been using the extra dictionary approach to extensibility for years - using a dynamic type to make the syntax cleaner is just a bonus here. What can you think of to use this for? Resources Source Code and Tests (GitHub) Also integrated in Westwind.Utilities of the West Wind Web Toolkit West Wind Utilities NuGet© Rick Strahl, West Wind Technologies, 2005-2012Posted in CSharp  .NET  Dynamic Types   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Using jQuery to POST Form Data to an ASP.NET ASMX AJAX Web Service

    - by Rick Strahl
    The other day I got a question about how to call an ASP.NET ASMX Web Service or PageMethods with the POST data from a Web Form (or any HTML form for that matter). The idea is that you should be able to call an endpoint URL, send it regular urlencoded POST data and then use Request.Form[] to retrieve the posted data as needed. My first reaction was that you can’t do it, because ASP.NET ASMX AJAX services (as well as Page Methods and WCF REST AJAX Services) require that the content POSTed to the server is posted as JSON and sent with an application/json or application/x-javascript content type. IOW, you can’t directly call an ASP.NET AJAX service with regular urlencoded data. Note that there are other ways to accomplish this. You can use ASP.NET MVC and a custom route, an HTTP Handler or separate ASPX page, or even a WCF REST service that’s configured to use non-JSON inputs. However if you want to use an ASP.NET AJAX service (or Page Methods) with a little bit of setup work it’s actually quite easy to capture all the form variables on the client and ship them up to the server. The basic steps needed to make this happen are: Capture form variables into an array on the client with jQuery’s .serializeArray() function Use $.ajax() or my ServiceProxy class to make an AJAX call to the server to send this array On the server create a custom type that matches the .serializeArray() name/value structure Create extension methods on NameValue[] to easily extract form variables Create a [WebMethod] that accepts this name/value type as an array (NameValue[]) This seems like a lot of work but realize that steps 3 and 4 are a one time setup step that can be reused in your entire site or multiple applications. Let’s look at a short example that looks like this as a base form of fields to ship to the server: The HTML for this form looks something like this: <div id="divMessage" class="errordisplay" style="display: none"> </div> <div> <div class="label">Name:</div> <div><asp:TextBox runat="server" ID="txtName" /></div> </div> <div> <div class="label">Company:</div> <div><asp:TextBox runat="server" ID="txtCompany"/></div> </div> <div> <div class="label" ></div> <div> <asp:DropDownList runat="server" ID="lstAttending"> <asp:ListItem Text="Attending" Value="Attending"/> <asp:ListItem Text="Not Attending" Value="NotAttending" /> <asp:ListItem Text="Maybe Attending" Value="MaybeAttending" /> <asp:ListItem Text="Not Sure Yet" Value="NotSureYet" /> </asp:DropDownList> </div> </div> <div> <div class="label">Special Needs:<br /> <small>(check all that apply)</small></div> <div> <asp:ListBox runat="server" ID="lstSpecialNeeds" SelectionMode="Multiple"> <asp:ListItem Text="Vegitarian" Value="Vegitarian" /> <asp:ListItem Text="Vegan" Value="Vegan" /> <asp:ListItem Text="Kosher" Value="Kosher" /> <asp:ListItem Text="Special Access" Value="SpecialAccess" /> <asp:ListItem Text="No Binder" Value="NoBinder" /> </asp:ListBox> </div> </div> <div> <div class="label"></div> <div> <asp:CheckBox ID="chkAdditionalGuests" Text="Additional Guests" runat="server" /> </div> </div> <hr /> <input type="button" id="btnSubmit" value="Send Registration" /> The form includes a few different kinds of form fields including a multi-selection listbox to demonstrate retrieving multiple values. Setting up the Server Side [WebMethod] The [WebMethod] on the server we’re going to call is going to be very simple and just capture the content of these values and echo then back as a formatted HTML string. Obviously this is overly simplistic but it serves to demonstrate the simple point of capturing the POST data on the server in an AJAX callback. public class PageMethodsService : System.Web.Services.WebService { [WebMethod] public string SendRegistration(NameValue[] formVars) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("Thank you {0}, <br/><br/>", HttpUtility.HtmlEncode(formVars.Form("txtName"))); sb.AppendLine("You've entered the following: <hr/>"); foreach (NameValue nv in formVars) { // strip out ASP.NET form vars like _ViewState/_EventValidation if (!nv.name.StartsWith("__")) { if (nv.name.StartsWith("txt") || nv.name.StartsWith("lst") || nv.name.StartsWith("chk")) sb.Append(nv.name.Substring(3)); else sb.Append(nv.name); sb.AppendLine(": " + HttpUtility.HtmlEncode(nv.value) + "<br/>"); } } sb.AppendLine("<hr/>"); string[] needs = formVars.FormMultiple("lstSpecialNeeds"); if (needs == null) sb.AppendLine("No Special Needs"); else { sb.AppendLine("Special Needs: <br/>"); foreach (string need in needs) { sb.AppendLine("&nbsp;&nbsp;" + need + "<br/>"); } } return sb.ToString(); } } The key feature of this method is that it receives a custom type called NameValue[] which is an array of NameValue objects that map the structure that the jQuery .serializeArray() function generates. There are two custom types involved in this: The actual NameValue type and a NameValueExtensions class that defines a couple of extension methods for the NameValue[] array type to allow for single (.Form()) and multiple (.FormMultiple()) value retrieval by name. The NameValue class is as simple as this and simply maps the structure of the array elements of .serializeArray(): public class NameValue { public string name { get; set; } public string value { get; set; } } The extension method class defines the .Form() and .FormMultiple() methods to allow easy retrieval of form variables from the returned array: /// <summary> /// Simple NameValue class that maps name and value /// properties that can be used with jQuery's /// $.serializeArray() function and JSON requests /// </summary> public static class NameValueExtensionMethods { /// <summary> /// Retrieves a single form variable from the list of /// form variables stored /// </summary> /// <param name="formVars"></param> /// <param name="name">formvar to retrieve</param> /// <returns>value or string.Empty if not found</returns> public static string Form(this NameValue[] formVars, string name) { var matches = formVars.Where(nv => nv.name.ToLower() == name.ToLower()).FirstOrDefault(); if (matches != null) return matches.value; return string.Empty; } /// <summary> /// Retrieves multiple selection form variables from the list of /// form variables stored. /// </summary> /// <param name="formVars"></param> /// <param name="name">The name of the form var to retrieve</param> /// <returns>values as string[] or null if no match is found</returns> public static string[] FormMultiple(this NameValue[] formVars, string name) { var matches = formVars.Where(nv => nv.name.ToLower() == name.ToLower()).Select(nv => nv.value).ToArray(); if (matches.Length == 0) return null; return matches; } } Using these extension methods it’s easy to retrieve individual values from the array: string name = formVars.Form("txtName"); or multiple values: string[] needs = formVars.FormMultiple("lstSpecialNeeds"); if (needs != null) { // do something with matches } Using these functions in the SendRegistration method it’s easy to retrieve a few form variables directly (txtName and the multiple selections of lstSpecialNeeds) or to iterate over the whole list of values. Of course this is an overly simple example – in typical app you’d probably want to validate the input data and save it to the database and then return some sort of confirmation or possibly an updated data list back to the client. Since this is a full AJAX service callback realize that you don’t have to return simple string values – you can return any of the supported result types (which are most serializable types) including complex hierarchical objects and arrays that make sense to your client code. POSTing Form Variables from the Client to the AJAX Service To call the AJAX service method on the client is straight forward and requires only use of little native jQuery plus JSON serialization functionality. To start add jQuery and the json2.js library to your page: <script src="Scripts/jquery.min.js" type="text/javascript"></script> <script src="Scripts/json2.js" type="text/javascript"></script> json2.js can be found here (be sure to remove the first line from the file): http://www.json.org/json2.js It’s required to handle JSON serialization for those browsers that don’t support it natively. With those script references in the document let’s hookup the button click handler and call the service: $(document).ready(function () { $("#btnSubmit").click(sendRegistration); }); function sendRegistration() { var arForm = $("#form1").serializeArray(); $.ajax({ url: "PageMethodsService.asmx/SendRegistration", type: "POST", contentType: "application/json", data: JSON.stringify({ formVars: arForm }), dataType: "json", success: function (result) { var jEl = $("#divMessage"); jEl.html(result.d).fadeIn(1000); setTimeout(function () { jEl.fadeOut(1000) }, 5000); }, error: function (xhr, status) { alert("An error occurred: " + status); } }); } The key feature in this code is the $("#form1").serializeArray();  call which serializes all the form fields of form1 into an array. Each form var is represented as an object with a name/value property. This array is then serialized into JSON with: JSON.stringify({ formVars: arForm }) The format for the parameter list in AJAX service calls is an object with one property for each parameter of the method. In this case its a single parameter called formVars and we’re assigning the array of form variables to it. The URL to call on the server is the name of the Service (or ASPX Page for Page Methods) plus the name of the method to call. On return the success callback receives the result from the AJAX callback which in this case is the formatted string which is simply assigned to an element in the form and displayed. Remember the result type is whatever the method returns – it doesn’t have to be a string. Note that ASP.NET AJAX and WCF REST return JSON data as a wrapped object so the result has a ‘d’ property that holds the actual response: jEl.html(result.d).fadeIn(1000); Slightly simpler: Using ServiceProxy.js If you want things slightly cleaner you can use the ServiceProxy.js class I’ve mentioned here before. The ServiceProxy class handles a few things for calling ASP.NET and WCF services more cleanly: Automatic JSON encoding Automatic fix up of ‘d’ wrapper property Automatic Date conversion on the client Simplified error handling Reusable and abstracted To add the service proxy add: <script src="Scripts/ServiceProxy.js" type="text/javascript"></script> and then change the code to this slightly simpler version: <script type="text/javascript"> proxy = new ServiceProxy("PageMethodsService.asmx/"); $(document).ready(function () { $("#btnSubmit").click(sendRegistration); }); function sendRegistration() { var arForm = $("#form1").serializeArray(); proxy.invoke("SendRegistration", { formVars: arForm }, function (result) { var jEl = $("#divMessage"); jEl.html(result).fadeIn(1000); setTimeout(function () { jEl.fadeOut(1000) }, 5000); }, function (error) { alert(error.message); } ); } The code is not very different but it makes the call as simple as specifying the method to call, the parameters to pass and the actions to take on success and error. No more remembering which content type and data types to use and manually serializing to JSON. This code also removes the “d” property processing in the response and provides more consistent error handling in that the call always returns an error object regardless of a server error or a communication error unlike the native $.ajax() call. Either approach works and both are pretty easy. The ServiceProxy really pays off if you use lots of service calls and especially if you need to deal with date values returned from the server  on the client. Summary Making Web Service calls and getting POST data to the server is not always the best option – ASP.NET and WCF AJAX services are meant to work with data in objects. However, in some situations it’s simply easier to POST all the captured form data to the server instead of mapping all properties from the input fields to some sort of message object first. For this approach the above POST mechanism is useful as it puts the parsing of the data on the server and leaves the client code lean and mean. It’s even easy to build a custom model binder on the server that can map the array values to properties on an object generically with some relatively simple Reflection code and without having to manually map form vars to properties and do string conversions. Keep in mind though that other approaches also abound. ASP.NET MVC makes it pretty easy to create custom routes to data and the built in model binder makes it very easy to deal with inbound form POST data in its original urlencoded format. The West Wind West Wind Web Toolkit also includes functionality for AJAX callbacks using plain POST values. All that’s needed is a Method parameter to query/form value to specify the method to be called on the server. After that the content type is completely optional and up to the consumer. It’d be nice if the ASP.NET AJAX Service and WCF AJAX Services weren’t so tightly bound to the content type so that you could more easily create open access service endpoints that can take advantage of urlencoded data that is everywhere in existing pages. It would make it much easier to create basic REST endpoints without complicated service configuration. Ah one can dream! In the meantime I hope this article has given you some ideas on how you can transfer POST data from the client to the server using JSON – it might be useful in other scenarios beyond ASP.NET AJAX services as well. Additional Resources ServiceProxy.js A small JavaScript library that wraps $.ajax() to call ASP.NET AJAX and WCF AJAX Services. Includes date parsing extensions to the JSON object, a global dataFilter for processing dates on all jQuery JSON requests, provides cleanup for the .NET wrapped message format and handles errors in a consistent fashion. Making jQuery Calls to WCF/ASMX with a ServiceProxy Client More information on calling ASMX and WCF AJAX services with jQuery and some more background on ServiceProxy.js. Note the implementation has slightly changed since the article was written. ww.jquery.js The West Wind West Wind Web Toolkit also includes ServiceProxy.js in the West Wind jQuery extension library. This version is slightly different and includes embedded json encoding/decoding based on json2.js.© Rick Strahl, West Wind Technologies, 2005-2010Posted in jQuery  ASP.NET  AJAX  

    Read the article

  • Why datacenter water cooling is not widespread?

    - by MainMa
    From what I read and hear about datacenters, there are not too many server rooms which use water cooling, and none of the largerst datacenters use water cooling (correct me if I'm wrong). Also, it's relatively easy to buy an ordinary PC components using water cooling, while water cooled rack servers are nearly nonexistent. On the other hand, using water can possibly (IMO): Reduce the power consumption of large datacenters, especially if it is possible to create direct cooled facilities (i.e. the facility is located near a river or the sea). Reduce noise, making it less painful for humans to work in datacenters. Reduce space needed for the servers: On server level, I imagine that in both rack and blade servers, it's easier to pass the water cooling tubes than to waste space to allow the air to pass inside, On datacenter level, if it's still required to keep the alleys between servers for maintenance access to servers, the empty space under the floor and at the ceiling level used for the air can be removed. So why water cooling systems are not widespread, neither on datacenter level, nor on rack/blade servers level? Is it because: The water cooling is hardly redundant on server level? The direct cost of water cooled facility is too high compared to an ordinary datacenter? It is difficult to maintain such system (regularly cleaning the water cooling system which uses water from a river is of course much more complicated and expensive than just vacuum cleaning the fans)?

    Read the article

  • How to write files in specific order?

    - by Bernie
    Okay, here's a weird problem -- My wife just bought a 2014 Nissan Altima. So, I took her iTunes library and converted the .m4a files to .mp3, since the car audio system only supports .mp3 and .wma. So far so good. Then I copied the files to a DOS FAT-32 formatted USB thumb drive, and connected the drive to the car's USB port, only to find all of the tracks were out of sequence. All tracks begin with a two digit numeric prefix, i.e., 01, 02, 03, etc. So you would think they would be in order. So I called Nissan Connect support and the rep told me that there is a known problem with reading files in the correct order. He said the files are read in the same order they are written. So, I manually copied a few albums with the tracks in a predetermined order, and sure enough he was correct. So I copied about 6 albums for testing, then changed to the top level directory and did a "find . music.txt". Then I passed this file to rsync like this: rsync -av --files-from=music.txt . ../Marys\ Music\ Sequenced/ The files looked like they were copied in order, but when I listed the files in order of modified time, they were in the same sequence as the original files: ../Marys Music Sequenced/Air Supply/Air Supply Greatest Hits ls -1rt 01 Lost In Love.mp3 04 Every Woman In The World.mp3 03 Chances.mp3 02 All Out Of Love.mp3 06 Here I Am (Just When I Thought I Was Over You).mp3 05 The One That You Love.mp3 08 I Want To Give It All.mp3 07 Sweet Dreams.mp3 11 Young Love.mp3 So the question is, how can I copy files listed in a file named music.txt, and copy them to a destination, and ensure the modification times are in the same sequence as the files are listed?

    Read the article

  • AMD FX8350 CPU - CoolerMaster Silencio 650 Case - New Water Cooling System

    - by fat_mike
    Lately after a use of 6 months of my AMD FX8350 CPU I'm experiencing high temperatures and loud noise coming from the CPU fan(I set that in order to keep it cooler). I decided to replace the stock fan with a water cooling system in order to keep my CPU quite and cool and add one or two more case fans too. Here is my case's airflow diagram: http://www.coolermaster.com/microsite/silencio_650/Airflow.html My configuration now is: 2x120mm intake front(stock with case) 1x120mm exhaust rear(stock with case) 1 CPU stock I'm planning to buy Corsair Hydro Series H100i(www.corsair.com/en-us/hydro-series-h100i-extreme-performance-liquid-cpu-cooler) and place the radiator in the front of my case(intake) and add an 120mm bottom intake and/or an 140mm top exhaust fan. My CPU lies near the top of the MO. Is it a good practice to have a water-cooling system that takes air in? As you can see here the front of the case is made of aluminum. Can the fresh air go in? Does it even fit? If not, is it wiser to get Corsair Hydro Series H80i (www.corsair.com/en-us/hydro-series-h80i-high-performance-liquid-cpu-cooler) and place the radiator on top of my case(exhaust) and keep the front 2x120mm stock and add one more as intake on bottom. If you have any other idea let me know. Thank you. EDIT: The CPU fan running ~3000rpm and temp is around 40~43C on idle and save energy. When temp is going over 55C when running multiple programs and servers on localhost(tomcat, wamp) rpm is around 5500 and loud! I'm running Win8.1 CPU not overclocked PS: Due to my reputation i couldn't post the links that was necessary. I will edit ASAP.

    Read the article

  • Looking for software to create a personal hotspot on Mac OS X (not using the built-in ability)

    - by Fred
    I got my nifty little MacBook Air today. Since I will be going on travel I was hoping to use my iPad 3G as screen extension with Air Display. It works being in a shared WiFi network. Sadly Apple is a bit restrictive on the tethering with their mobile devices such as the iPad. Now I read iOS 4.3 will enable the iPad to use tethered networks. But the feature will not be working for iPad 3G. I assume their big partner telecom companies fear everyone will quit their internet contract with them. So I want to create a personal hotspot on my MacBook and use it on my iPad. But the iPad is not able to use this network. The network is visible but not usable. On Windows there is this connectify program which lets the PC act as wireless router. Does anybody know a similar program for Mac which would turn it into a wireless router? Or is there something I don't see with Mac OS X's builtin features?

    Read the article

  • Running a VM off a USB 2.0 Flash Drive - Mac/Parallels/XP

    - by geerlingguy
    I use a MacBook Air as my primary machine, and the 128GB SSD means space is precious. To save about 10 GB, I've been running Parallels with a Windows XP VM off an external USB hard drive, which performs as well in everyday use as running the VM off the internal SSD. So, I bought a tiny 32GB USB 2.0 flash drive, plugged it into the MacBook Air, formatted it first as ExFAT (which was slow), then as Mac OS Extended (Journaled) (which was also slow), and copied over my VM file, and ran Parallels off it. My full experience is documented here: http://www.midwesternmac.com/blogs/jeff-geerling/running-windows-xp-vm Straight file copies are really fast — 30 MB/sec read (solid the whole time), and 10-11 MB/sec write (solid the whole time). But I noticed that once XP started running, the disk access rates were in the low KB ranges. Are USB flash drives really that poor at random access, or could I possibly be missing something (the format of the flash drive, etc.?)? Of note, I've tried the following, to no great effect: Formatting the drive as either ExFAT or Mac OS Extended (Journaled) Unplugging all other USB devices and turning off Bluetooth (which runs on the right-side-port USB bus). Plugging in the flash drive either direct in the right side port, or the left side port, or into a USB 2.0 hub

    Read the article

  • Mac creating files w/ wrong perms on samba share

    - by geoffjentry
    In my group, which is very heterogeneous in terms of machines, we use a samba share to collaborate on files and such. In all but one case, it works as expected (or at least close enough). The one exception is my boss' laptop, a snow leopard macbook air. On his desktop (also snow leopard), if he creates a file it ends up serverside with perms of 774, but when he creates it with the Air, the perms are 644. The key problem is the lack of group write permission on the laptop created files. What's really confusing is that everything that I've looked at on the two machines are identical - same version of OS X, same version of samba (3.0.25b-apple), same settings for the same software, etc. I can't imagine why one machine would be different than the other, but it is. To try to be complete w/ the description, here is the relevant portion of my smb.conf file: comment = my Share path = /path/to/share public = no writeable = yes printable = no force group = myshare directory mask = 0770 create mask = 0770 force create mode = 0770 force directory mode = 0770 EDIT: I looked at three more Macs and all of them worked as expected which leaves this one laptop the true oddball. This wasn't as good as a test as the others though, as they were all leopard.

    Read the article

  • Mac updated just now, postgres now broken

    - by Dave
    I run postgres 9.1 / ruby 1.9.2 / rails 3.1.0 on a maxbook air for local dev. It's all been running smoothly for months, (though this is the first time I've done development on a mac.) It's a macbook air from last year, and today I got the mac osx software update message as I have a few times before, and my system downloaded approx 450mb of updates and restarted. It now says it's on OSX 10.7.3. Point is, postgres has stopped working, when I start my thin server (mirror heroku cedar) as normal, and then browse to my rails app I get: PG::Error could not connect to server: Permission denied Is the server running locally and accepting connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"? What happened? After browsing around a few questions I'm still confused, but here's some extra info: Running psql from command line gives same error I can run pgadmin 3 and connect via it and run SQL no problems Running which psql shows the version as /usr/bin/psql I created a PostgreSQL user back when I got the mac (it's always been on lion) I've no idea why, almost certainly I was following a tutorial which I neglected to store in my notes. Point is I am aware there is a _postgres user as well. I know it's rubbish, but apart from a note on passwords, I don't have any extra info on how I configured postgres - though the obvious implication is that I did not use the _postgres user. Anyone have suggestions or information on what might have changed / what I can try to debug and fix? Thanks. Edit: Playing around based on this question and answer: http://stackoverflow.com/questions/7975414/check-status-of-postgresql-server-mac-os-x, see this string of commands: $ sudo su postgreSQL bash-3.2$ /Library/PostgreSQL/9.1/bin/pg_ctl start -D /Library/PostgreSQL/9.1/data pg_ctl: another server might be running; trying to start server anyway server starting bash-3.2$ 2012-04-08 19:03:39 GMT FATAL: lock file "postmaster.pid" already exists 2012-04-08 19:03:39 GMT HINT: Is another postmaster (PID 68) running in data directory "/Library/PostgreSQL/9.1/data"? bash-3.2$ exit

    Read the article

  • Motherboard running rather hot while gaming

    - by I take Drukqs
    Case: Antec 1200 Mobo: Gigabyte GA-X58A-UD3R CPU: Intel i7 950 (stock cooler) GPU: EVGA GeForce 570 GTX RAM: 2x 2 GB (4 GB total) DDR3 dual-channel Corsair OS: Windows 7 Home Premium 64-bit This is my first build and it's brand new. I had no problems putting it all together in a few hours one evening and I consider myself to be pretty good with computers. Not to brag or anything like that! Just saying I've been fiddling with them since I was in diapers and I have a good amount of experience under my belt, just not with certain things yet. Recently while playing many of the latest games maxed out without a hitch my motherboard has been running hot and like anyone who's ever built a computer it scares the life out of me. I checked HWMonitor and saw that my motherboard sometimes reached temperatures of around 52 - 78c (the number 78 obviously being what's scaring me). I was wondering if such a temperature is normal and if not what the problem could be. Air flow in my case is phenomenal and besides having to ship back a faulty GPU and reseat my CPU my first build has been a very large success which I am enjoying tremendously. There is literally almost no dust in my case due to it being very new as previously mentioned and my RAM sticks are in the correct slots for dual-channel mode. My cable management is pretty great in my opinion with only cables from my PSU lingering in the bottom of the case. At any given opportunity I ran my cables behind my mobo. Air flow should definitely not be a problem because my CPU only goes up to about 60c and my GPU only goes up to about 80c. Thank you very much in advance.

    Read the article

  • Windows 7 notebook turn off by itself, how to check if it is due to CPU being too hot?

    - by Jian Lin
    I have a Dell Studio 15 notebook, and it just started turning off by itself yesterday. Could it be that the CPU is too hot? I have had several notebooks before and every one of them I can put them on the bed without any problem. This Dell Studio Notebook, however, seems like have the air / fan outlet pointed outward from the bottom back of the notebook, so I suspect that the air is partially blocked when it is on the bed. Are there Win 7 tools that can monitor the CPU temperature, or will some 3rd party tool be needed? (I try to stick to official tools nowadays). Also, it is running Win 7 Ulitmate, there is actually no utility or background service from Win 7 or from Dell that detects when the temperature is too hot (or 95% near the max), pop out a message box giving a warning and say that the computer will go into sleep mode in 1 minute, but instead just turn off the computer by brute force (cutting out the power) right then and there? Update: it turned off right in front of my eyes -- it is not doing any windows update or anything. just normal use and jooooop, it turned off.

    Read the article

  • Mac updated just now, postgres now broken

    - by user52224
    I run postgres 9.1 / ruby 1.9.2 / rails 3.1.0 on a maxbook air for local dev. It's all been running smoothly for months, (though this is the first time I've done development on a mac.) It's a macbook air from last year, and today I got the mac osx software update message as I have a few times before, and my system downloaded approx 450mb of updates and restarted. It now says it's on OSX 10.7.3. Point is, postgres has stopped working, when I start my thin server (mirror heroku cedar) as normal, and then browse to my rails app I get: PG::Error could not connect to server: Permission denied Is the server running locally and accepting connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"? What happened? After browsing around a few questions I'm still confused, but here's some extra info: Running psql from command line gives same error I can run pgadmin 3 and connect via it and run SQL no problems Running which psql shows the version as /usr/bin/psql I created a PostgreSQL user back when I got the mac (it's always been on lion) I've no idea why, almost certainly I was following a tutorial which I neglected to store in my notes. Point is I am aware there is a _postgres user as well. I know it's rubbish, but apart from a note on passwords, I don't have any extra info on how I configured postgres - though the obvious implication is that I did not use the _postgres user. Anyone have suggestions or information on what might have changed / what I can try to debug and fix? Thanks. Edit: Playing around based on this question and answer: http://stackoverflow.com/questions/7975414/check-status-of-postgresql-server-mac-os-x, see this string of commands: $ sudo su postgreSQL bash-3.2$ /Library/PostgreSQL/9.1/bin/pg_ctl start -D /Library/PostgreSQL/9.1/data pg_ctl: another server might be running; trying to start server anyway server starting bash-3.2$ 2012-04-08 19:03:39 GMT FATAL: lock file "postmaster.pid" already exists 2012-04-08 19:03:39 GMT HINT: Is another postmaster (PID 68) running in data directory "/Library/PostgreSQL/9.1/data"? bash-3.2$ exit

    Read the article

  • RouterLess, house-wired network using multiple powerline adapters

    - by Cliff Arnell
    related to the 'old days' of one ethernet cable tapped with Ts for each monitor.... my question might be very simple... or not. I have an over-the-air internet provider with a wire dish with a powered transceiver and cat5 cable out of the providers supplied modem. I'm presently connecting the output of the modem into my wireless router which sends the internet signal all over the house. Standard stuff, I believe. My Question. Can I just connect the output of the modem into 1 powerline adapter and tie all my equipment such as computer, printer, laptop, Tivo recorder, etc. into 1-each local powerline adapters located near each devices resulting in a 'house-wired' network and no router? I'm bothered by the idea that my over-the-air provider might be using something in my router to establish and keep my IP connection alive. I did have to configure the router for my IP, a router which, in my proposed scenario, would no longer exist. Thank you for your help.

    Read the article

  • 404 with serving static files in a custom nginx configuration

    - by code90
    In my nginx configuration, I have the following: location /admin/ { alias /usr/share/php/wtlib_4/apps/admin/; location ~* .*\.php$ { try_files $uri $uri/ @php_admin; } location ~* \.(js|css|png|jpg|jpeg|gif|ico|pdf|zip|rar|air)$ { expires 7d; access_log off; } } location ~ ^/admin/modules/([^/]+)(.*\.(html|js|json|css|png|jpg|jpeg|gif|ico|pdf|zip|rar|air))$ { alias /usr/share/php/wtlib_4/modules/$1/admin/$2; } location ~ ^/admin/modules/([^/]+)(.*)$ { try_files $uri @php_admin_modules; } location @php_admin { if ($fastcgi_script_name ~ /admin(/.*\.php)$) { set $valid_fastcgi_script_name $1; } fastcgi_pass $byr_pass; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /usr/share/php/wtlib_4/apps/admin$valid_fastcgi_script_name; fastcgi_param REDIRECT_STATUS 200; include /etc/nginx/fastcgi_params; } location @php_admin_modules { if ($fastcgi_script_name ~ /admin/modules/([^/]+)(.*)$) { set $byr_module $1; set $byr_rest $2; } fastcgi_pass $byr_pass; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /usr/share/php/wtlib_4/modules/$byr_module/admin$byr_rest; fastcgi_param REDIRECT_STATUS 200; include /etc/nginx/fastcgi_params; } Following is the requested url which ends up with "404": http://www.{domainname}.com/admin/modules/cms/styles/cms.css Following is the error log: [error] 19551#0: *28 open() "/usr/share/php/wtlib_4/apps/admin/modules/cms/styles/cms.css" failed (2: No such file or directory), client: xxx.xxx.xxx.xxx, server: {domainname}.com, request: "GET /admin/modules/cms/styles/cms.css HTTP/1.1", host: "www.{domainname}.com" Following urls works fine: http://www.{domainname}.com/admin/modules/store/?a=manage http://www.{domainname}.com/admin/modules/cms/?a=cms.load Can anyone see what the problem could be? Thanks. PS. I am trying to migrate existing sites from apache to nginx.

    Read the article

  • Locate devices within a building

    - by ams0
    The situation: Our company is spread between two floors in a building. Every employee has a laptop (macbook Air or MacbookPro) and an iPhone. We have static DHCP mappings and DNS resolution so every mobile gets a name like employeeiphone.example.com, every macbook air gets a employeelaptop.example.com and every macbook pro gets a employeelaptop.example.com on the Ethernet interface (the wifi gets a dynamic IP from a small range dedicated for the purpose). We know each and every MAC address of phones and laptops, since we do DHCP static mapping (ISC DHCP server runs on linux). At each floor we have a Netgear stack of two switches, connected via 10GB fiber to each other. No VLANs so far. At every floor there are 4 Airport Extreme making a single SSID network with WPA2 authentication. The request: Our CTO wants to know who is present at which floor. My solution (so far): Every switch contains an table listing MAC address and originating port. On each switch stack, all the MAC addresses coming from the other floor are listed as coming on port 48 (the fiber link). So I came up with: 1) Get the table from each switch via SNMP 2) Filter out the ones associated with port 48 3) Grep dhcpd.conf, removing all entries not *laptop and not *iphone 4) Match the two lists for each switch, output in JSON or XML 5) present the results on a dashboard for all to see I wrote it in bash with a lot of awk and sed, it kinda works but I always have for some reason stale entries in the switch lookup tables, making it unreliable; some people may have put their laptop to sleep, their iphones drop connections after a while, if not woken up and so on..I searched left and right, we are prepared to spend a little on the project too (RFIDs?), does anybody do something similar? I can provide with the script if needed (although it's really specific to our switches and naming scheme). Thanks! p.s. perhaps is this a question for stackoverflow? please move if it so.

    Read the article

  • MacMini transmit rate stuck at 11, every other device can connect at full 54Mbit/s?

    - by chum of chance
    I have a MacMini circa 2007 that's getting very low transmit rates via wifi, 8-11. I have other devices that are getting full 54, including a MacBook Air. With everything else off, the MacMini doesn't want to seem to go any faster. Since it has been previously connected to ethernet its entire life, I was wondering if there were some settings I can change to speed up the connection. Option-clicking the network icon gives this read out: PHY Mode: 802.11g Channel: 1 (2.4 Ghz) Security: WPA2 Personal RSSI: -73 Transmit Rate: 11 My new MacBook Air has the following readout: PHY Mode: 802.11n Channel: 1 (2.4 Ghz) Security: WPA2 Personal RSSI: -66 Transmit Rate: 79 Both have full bars and the wireless router is in the same room to eliminate any obstructions from the equation. Could the MacMini be connecting at an older protocol, like 802.11b and be reporting erroneously that it is connected at 802.11g? This would explain why I haven't seen a transmit rate above 11. Any further trouble shooting I can try before buying a new USB 802.11n device? The WiFi router is a DLink DIR-615. I can see other devices, and none, even the other g connected devices, are getting below 30-40 MBit/s. What's going on here?

    Read the article

  • Update php 5.2.0 to 5.2.4 with aptitude

    - by Kiva
    Hi guy, I would like to update my php 5 in my server. At this moment, I use php 5.2.0 so I want to update it to php 5.2.4 (not php 5.3). I tried to do this: aptitude update aptitude upgrade 63 packets were updated but not php which is always in 5.0 How can I update my php please ? Here is the output of commands asked by David in another post: aptitude search php5 p libapache-mod-php5 - server-side, HTML-embedded scripting langu i A libapache2-mod-php5 - server-side, HTML-embedded scripting langu i php5 - server-side, HTML-embedded scripting langu p php5-apache2-mod-bt - PHP bindings for mod_bt p php5-auth-pam - A PHP5 extension for PAM authentication i php5-cgi - server-side, HTML-embedded scripting langu p php5-clamavlib - PHP ClamAV Lib - ClamAV Interface for PHP5 p php5-cli - command-line interpreter for the php5 scri i A php5-common - Common files for packages built from the p i php5-curl - CURL module for php5 p php5-dev - Files for PHP5 module development i A php5-gd - GD module for php5 p php5-idn - PHP api for the IDNA library p php5-imagick - ImageMagick module for php5 p php5-imap - IMAP module for php5 p php5-interbase - interbase/firebird module for php5 p php5-json - JSON serialiser for PHP5 p php5-ldap - LDAP module for php5 p php5-mapscript - module for php5-cgi to use mapserver p php5-maxdb - PHP extension to access MaxDB databases fo i A php5-mcrypt - MCrypt module for php5 p php5-memcache - memcache extension module for PHP5 p php5-mhash - MHASH module for php5 p php5-ming - Ming module for php5 i A php5-mysql - MySQL module for php5 p php5-odbc - ODBC module for php5 p php5-pgsql - PostgreSQL module for php5 p php5-ps - ps module for PHP 5 p php5-pspell - pspell module for php5 p php5-radius - PECL radius module for PHP 5 p php5-recode - recode module for php5 p php5-snmp - SNMP module for php5 p php5-sqlite - SQLite module for php5 p php5-sqlite3 - SQLite3 module for php5 p php5-sqlrelay - SQL Relay PHP API p php5-suhosin - advanced protection module for php5 p php5-sybase - Sybase / MS SQL Server module for php5 p php5-tidy - tidy module for php5 p php5-uuid - OSSP uuid module for php5 p php5-xapian - Xapian search engine interface for PHP5 p php5-xcache - Fast, stable PHP opcode cacher p php5-xmlrpc - XML-RPC module for php5 p php5-xsl - XSL module for php5 aptitude show php5 | grep Version Version : 5.2.0-8+etch13 aptitude show php5-cgi | grep Version Version : 5.2.0-8+etch13 php5 --version -bash: php5: command not found php-cgi --version PHP 5.2.0-8+etch13 (cgi-fcgi) (built: Oct 2 2008 08:21:17) Copyright (c) 1997-2006 The PHP Group Zend Engine v2.2.0, Copyright (c) 1998-2006 Zend Technologies

    Read the article

  • Unable to start Tomcat6 with HTTPS enabled

    - by ram
    I have the following server.xml settings for my tomcat6 server <!-- COMMENTED <Connector port="8080" maxThreads="150" enableLookups="false" acceptCount="100" scheme="http" redirectPort="8443"/> --> <!-- COMMENTED <Connector port="80" maxThreads="150" enableLookups="false" acceptCount="100" scheme="http" redirectPort="443"/> --> <Connector port="443" maxHttpHeaderSize="8192" maxThreads="150" enableLookups="false" disableUploadTimeout="true" acceptCount="100" scheme="https" secure="true" SSLEnabled="true" SSLCertificateFile="%SSL_CERT%" SSLCertificateKeyFile="%SSL_KEY%" SSLCipherSuite="ALL:!ADH:!kEDH:!SSLv2:!EXPORT40:!EXP:!LOW" compression="on" compressableMimeType="text/html,text/xml,text/plain,application/javascript,application/json,text/javascript"/> Complete server.xml is here but when I try to start the application I get the following error in catalina.*.log file INFO: Initializing Coyote HTTP/1.1 on http-80 Apr 7, 2013 8:38:38 PM org.apache.coyote.http11.Http11AprProtocol init SEVERE: Error initializing endpoint java.lang.Exception: Invalid Server SSL Protocol (error:00000000:lib(0):func(0):reason(0)) at org.apache.tomcat.jni.SSLContext.make(Native Method) at org.apache.tomcat.util.net.AprEndpoint.init(AprEndpoint.java:729) at org.apache.coyote.http11.Http11AprProtocol.init(Http11AprProtocol.java:107) at org.apache.catalina.connector.Connector.initialize(Connector.java:1049) at org.apache.catalina.core.StandardService.initialize(StandardService.java:703) at org.apache.catalina.core.StandardServer.initialize(StandardServer.java:838) at org.apache.catalina.startup.Catalina.load(Catalina.java:538) at org.apache.catalina.startup.Catalina.load(Catalina.java:562) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:261) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413) Apr 7, 2013 8:38:38 PM org.apache.catalina.core.StandardService initialize SEVERE: Failed to initialize connector [Connector[HTTP/1.1-443]] LifecycleException: Protocol handler initialization failed: java.lang.Exception: Invalid Server SSL Protocol (error:00000000:lib(0):func(0):reason(0)) at org.apache.catalina.connector.Connector.initialize(Connector.java:1051) at org.apache.catalina.core.StandardService.initialize(StandardService.java:703) at org.apache.catalina.core.StandardServer.initialize(StandardServer.java:838) at org.apache.catalina.startup.Catalina.load(Catalina.java:538) at org.apache.catalina.startup.Catalina.load(Catalina.java:562) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:261) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413) I've checked the following things already I have given read permissions for everyone for .crt and .key files I copied server.xml to a different working tomcat6 server and it works there, server.xml from the mentioned working tomcat5 webserver doesn't work here and it fails with the same error Works well with just HTTP enabled explicitly mentioning protocol in the Connector i.e. protocol="org.apache.coyote.http11.Http11AprProtocol" results in the same exception Please help me if I am missing something. Thanks in advance

    Read the article

  • Nasty mono bug with F#

    - by Aurimas Anskaitis
    Hi, I have this monstrous f# 2.0 program My mono version is Mono JIT compiler version 2.9 (master/f593354 Sun Dec 26 03:15:55 EET 2010) Copyright (C) 2002-2010 Novell, Inc and Contributors. www.mono-project.com TLS: __thread SIGSEGV: altstack Notifications: epoll Architecture: x86 Disabled: none Misc: softdebug LLVM: supported, not enabled. GC: Included Boehm (with typed GC and Parallel Mark) //--------------------------------------------- module Main let rec gcd x y = if y = 0 then x else gcd y (x%y) let main = printfn "%i" (gcd 4 2) main //----------------------------------------------- And the problem is that output from running the program is as follows: Stacktrace: at (wrapper managed-to-native) System.Reflection.MonoMethodInfo.get_parameter_info (intptr,System.Reflection.MemberInfo) <0xffffffff at System.Reflection.MonoMethodInfo.GetParametersInfo (intptr,System.Reflection.MemberInfo) <0x00013 at System.Reflection.MonoCMethod.GetParameters () <0x00015 at System.Reflection.MonoCMethod.Invoke (object,System.Reflection.BindingFlags,System.Reflection.Binder,object[],System.Globalization.CultureInfo) <0x00035 at System.Reflection.MonoCMethod.Invoke (System.Reflection.BindingFlags,System.Reflection.Binder,object[],System.Globalization.CultureInfo) <0x00024 at System.Reflection.ConstructorInfo.Invoke (object[]) <0x0003f at System.Activator.CreateInstance (System.Type,bool) <0x0017c at System.Activator.CreateInstance (System.Type) <0x00012 at Microsoft.FSharp.Reflection.FSharpValue.MakeFunction (System.Type,Microsoft.FSharp.Core.FSharpFunc2<object, object>) <0x00145> at Microsoft.FSharp.Core.PrintfImpl.capture@529<b, c, d> (Microsoft.FSharp.Core.FSharpFunc2, Microsoft.FSharp.Core.FSharpFunc`2<char, Microsoft.FSharp.Core.Unit>, Microsoft.FSharp.Core.FSharpFunc`2,string,int,Microsoft.FSharp.Collections.FSharpList1<object>,System.Type,int) <0x00147> at Microsoft.FSharp.Core.PrintfImpl.gprintf<b, c, d, a> (Microsoft.FSharp.Core.FSharpFunc2, Microsoft.FSharp.Core.FSharpFunc`2<char, Microsoft.FSharp.Core.Unit>, Microsoft.FSharp.Core.FSharpFunc`2,Microsoft.FSharp.Core.PrintfFormat4<a, b, c, d>) <0x000dd> at Microsoft.FSharp.Core.PrintfModule.kprintf_imperative<a, b, c> (Microsoft.FSharp.Core.FSharpFunc2,b,Microsoft.FSharp.Core.FSharpFunc2<char, Microsoft.FSharp.Core.Unit>,Microsoft.FSharp.Core.PrintfFormat4) <0x00058 at Microsoft.FSharp.Core.PrintfModule.PrintFormatToTextWriterThen (Microsoft.FSharp.Core.FSharpFunc2<Microsoft.FSharp.Core.Unit, TResult>,System.IO.TextWriter,Microsoft.FSharp.Core.PrintfFormat4) <0x0004d at Microsoft.FSharp.Core.PrintfModule.PrintFormatLineToTextWriter (System.IO.TextWriter,Microsoft.FSharp.Core.PrintfFormat`4) <0x0004d at .$Main.main@ () <0x00042 Native stacktrace: mono() [0x80dc13b] mono() [0x811c65b] mono() [0x8059a11] [0x7af40c] mono() [0x8228214] mono() [0x8228214] mono() [0x8228214] mono() [0x8228214] mono() [0x8228214] mono() [0x8228214] mono() [0x8228214] mono() [0x8228214] mono() [0x8228282] mono() [0x822991e] mono() [0x822aa9d] mono(mono_array_new_specific+0xea) [0x813ba9a] mono() [0x81c63a1] mono() [0x8149ac8] [0xc04328] [0xc042e4] [0xc042be] [0xc0455e] [0xc0451d] [0xc044d8] [0xc0349d] [0xc0330b] [0xc02f9e] [0xbfe960] [0xbfe6c6] [0xbfe571] [0xbfe4de] [0xbfe44e] [0xbf9d2b] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] [0x9bf0724] Debug info from gdb: Could not attach to process. If your uid matches the uid of the target process, check the setting of /proc/sys/kernel/yama/ptrace_scope, or try again as the root user. For more details, see /etc/sysctl.d/10-ptrace.conf ptrace: Operation not permitted. ================================================================= Got a SIGSEGV while executing native code. This usually indicates a fatal error in the mono runtime or one of the native libraries used by your application. Aborted It is a huge problem with mono or f#? By the way, the same function works when using pattern matching instead of "if".

    Read the article

< Previous Page | 118 119 120 121 122 123 124 125 126 127 128 129  | Next Page >