prompt
stringlengths
5
14.5k
chosen
stringlengths
3
19.7k
rejected
stringlengths
1
9.05k
Flutter Launcher icon not getting changed?
Add flutter_launcher_icons: ^0.7.3 code Plugin to pubspec.yaml in pubspec.yaml : <code>flutter_icons: image_path_android: "images/logoapp.png" image_path_ios: "images/logoapp.png" android: true ios: true </code> run command : flutter pub get run command : flutter pub pub run flutter_launcher_icons:main run command : flutter clean run command : flutter run it worked for me
Able to change Now after following below Steps. Add flutter_launcher_icons code Plugin to pubspec.yaml as mentioned in question In Command prompt run below commands flutter pub get flutter pub pub run flutter_launcher_icons:main And it worked Launcher Icons I generated using external website https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html
How to test method that is called with DispatchQueue.main.async?
I think the best approach to test this is to mock the <code>DispatchQueue</code>. You can create a protocol that defines the functionality that you want to use: <code>protocol DispatchQueueType { func async(execute work: @escaping @convention(block) () -> Void) } </code> Now extend <code>DispatchQueue</code> to conform to your protocol, like: <code>extension DispatchQueue: DispatchQueueType { func async(execute work: @escaping @convention(block) () -> Void) { async(group: nil, qos: .unspecified, flags: [], execute: work) } } </code> Note I had to omit from the protocol the parameters you didn't use in your code, like <code>group</code>, <code>qos</code>, and <code>flags</code>, since protocol don't allow default values. And that's why the extension had to explicitly implement the protocol function. Now, in your tests, create a mocked <code>DispatchQueue</code> that conforms to that protocol and calls the closure synchronously, like: <code>final class DispatchQueueMock: DispatchQueueType { func async(execute work: @escaping @convention(block) () -> Void) { work() } } </code> Now, all you need to do is inject the queue accordingly, perhaps in the view controller's <code>init</code>, like: <code>final class ViewController: UIViewController { let mainDispatchQueue: DispatchQueueType init(mainDispatchQueue: DispatchQueueType = DispatchQueue.main) { self.mainDispatchQueue = mainDispatchQueue super.init(nibName: nil, bundle: nil) } func foo() { mainDispatchQueue.async { *perform asynchronous work* } } } </code> Finally, in your tests, you need to create your view controller using the mocked dispatch queue, like: <code>func testFooSucceeds() { let controller = ViewController(mainDispatchQueue: DispatchQueueMock()) controller.foo() *assert work was performed successfully* } </code> Since you used the mocked queue in your test, the code will be executed synchronously, and you don't need to frustratingly wait for expectations.
You don't need to call the code in the <code>updateBadgeValuesForTabBarItems</code> method on the main queue. But if you really need it, you can do something like this: <code>func testViewDidAppear() { let view = TabBarView() let model = MockTabBarViewModel() let center = NotificationCenter() let controller = TabBarController(view: view, viewModel: model, notificationCenter: center) controller.viewDidLoad() XCTAssertFalse(model.numberOfActiveTasksWasCalled) XCTAssertFalse(model.numberOfUnreadMessagesWasCalled) XCTAssertFalse(model.numberOfUnreadNotificationsWasCalled) XCTAssertFalse(model.indexForTypeWasCalled) controller.viewDidAppear(false) let expectation = self.expectation(description: "Test") DispatchQueue.main.async { expectation.fullfill() } self.waitForExpectations(timeout: 1, handler: nil) XCTAssertTrue(model.numberOfActiveTasksWasCalled) XCTAssertTrue(model.numberOfUnreadMessagesWasCalled) XCTAssertTrue(model.numberOfUnreadNotificationsWasCalled) XCTAssertTrue(model.indexForTypeWasCalled) } </code> But this is not good practice.
How to check if value is enum?
As of late 2021, all enums extend <code>Enum</code> You can now finally use <code>is Enum</code> directly: <code>enum MyEnum {one, two, three} var x = "a"; var y = MyEnum.one; print(x is Enum); // false print(y is Enum); // true </code> Which also means you can now create extensions for enums: <code>extension EnumExtension on Enum { ... } </code>
If you need to check is <code>dynamic</code> value enum type. You can use the next approach. The main idea is quite similar to @Oniya Daniel's answer. <code> enum Fruit { banana, apple, orange, } </code> Next method to check <code>isEnum</code> condition <code> bool isEnum(dynamic data) { final split = data.toString().split('.'); return split.length > 1 && split[0] == data.runtimeType.toString(); } </code> Test result below <code> test('check enum runtime', () { expect(isEnum(Fruit.banana), true); expect(isEnum(null), false); expect(isEnum(''), false); expect(isEnum('banana'), false); }); </code> P.S.: to get enum String value good to use <code>describeEnum(<enum_value>)</code> from the <code>package:flutter/foundation.dart</code>
How to log requests in ktor http client?
You can achieve this with the <code>Logging</code> feature. First add the dependency: <code>implementation "io.ktor:ktor-client-logging-native:$ktor_version" </code> Then install the feature: <code>private val client = HttpClient { install(Logging) { logger = Logger.DEFAULT level = LogLevel.ALL } } </code> Bonus: If you need to have multiple <code>HttpClient</code> instances throughout your application and you want to reuse some of the configuration, then you can create an extension function and add the common logic in there. For example: <code>fun HttpClientConfig<*>.default() { install(Logging) { logger = Logger.DEFAULT level = LogLevel.ALL } // Add all the common configuration here. } </code> And then initialize your <code>HttpClient</code> like this: <code>private val client = HttpClient { default() } </code>
I ran into this as well. I switched to using the Ktor OkHttp client as I'm familiar with the logging mechanism there. Update your <code>pom.xml</code> or <code>gradle.build</code> to include that client (copy/paste from the Ktor site) and also add the OkHttp Logging Interceptor (again, copy/paste from that site). Current version is <code>3.12.0</code>. Now configure the client with <code>val client = HttpClient(OkHttp) { engine { val loggingInterceptor = HttpLoggingInterceptor() loggingInterceptor.level = Level.BODY addInterceptor(loggingInterceptor) } } </code>
How to Import Security group from another stack using #AWS-CDK?
You can directly refer the cross-stack resources in an app. Below is a code snippet, <code>export class InfraCdkStack extends cdk.Stack { // Create a readonly property to reference on an instance. readonly vpc: ec2.IVpc; constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); // The code that defines your stack goes here. // Assign your vpc to your previously created property. // Creates a vpc in two AZs. this.vpc = new ec2.Vpc(this, 'MyVPC'); } } // Create an interface to hold the vpc information. interface ECSStackProps extends cdk.StackProps { vpc: ec2.IVpc; } // Have your class constructor accept the interface. export class ECSCdkStack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props: ECSStackProps) { super(scope, id, props); } const app = new cdk.App(); const infraStack = new InfraCdkStack(app, 'InfraCdkStack'); // Pass the infraStack.vpc property to the ECSCdkStack class. const gameECSStack = new ECSCdkStack(app, 'ECSCdkStack', { vpc: infraStack.vpc }); </code> There is an example in official doc to demonstrate how sharing s3 bucket.
Assuming that the Stacks in question are both under your CDK Application, you can use Stack Outputs to share resources. Docs here: https://docs.aws.amazon.com/cdk/api/latest/docs/core-readme.html#stack-outputs I found this blog post to be useful as an example (not written by me) It should work for any resource you might want to reference between stacks. EDIT: This is what I'm working with at the moment. <code>// I have a resource which is a cloudfront dist id in StackA new cdk.CfnOutput(this, 'cloudfront-dist-id-output', { description: 'cloudfront-dist-id-output', exportName: 'cloudfront-dist-id-output', value: cloudFrontDistribution.distributionId }); // Stack B needs the DistributionId (it's dynamic), so I pass it in as a parameter. new StackB(app, 'StackB', Fn.importValue('cloudfront-dist-id-output')); </code> The only 'known' thing ahead of time is the name of the parameter that you're outputting. This is effectively the same thing you've provided in your other answer, but the CDK writes the <code>Fn.importValue</code> for you. Warning: Does not work with resources in stacks that are in different regions. The limitation is imposed by CloudFormation and will also happen in @Kane's answer.
How to change the y axis to display percent (%) in Python Plotnine barplot?
similar question raised here: https://github.com/has2k1/plotnine/issues/152 <code>from plotnine import * from plotnine.data import mpg from mizani.formatters import percent_format p = ggplot(mpg) + geom_bar(aes(x='manufacturer', fill='class'), position='fill') p = p + scale_y_continuous(labels=percent_format()) print(p) </code> other predefined filters can be found here: https://mizani.readthedocs.io/en/stable/formatters.html
The <code>labels</code> parameter accepts a callable that takes the list of break points as input. All you have to do is to convert each item in the list manually: <code>scale_y_continuous(labels=lambda l: ["%d%%" % (v * 100) for v in l]) </code>
How to hide lacking phpmyadmin warnings?
The best way to turn off Phpmyadmin errors is to go go config.inc.php and set (or comment out ie removing the // lines in front of the value, which is set to "ask" by default.) <code>$cfg['SendErrorReports'] = 'never'; </code> Hit save and that's it. More info https://docs.phpmyadmin.net/en/latest/config.html#cfg_SendErrorReports
This is a common error on this phpMyAdmin version. To solve this open this file <blockquote> sudo pico /usr/share/phpmyadmin/libraries/sql.lib.php </blockquote> Find this line: <blockquote> || (count($analyzed_sql_results['select_expr'] == 1) </blockquote> and replace with: <blockquote> || (count($analyzed_sql_results['select_expr']) == 1 </blockquote>
How to convert Milliseconds to "X mins, x seconds" in Java?
Using the java.time package in Java 8: <code>Instant start = Instant.now(); Thread.sleep(63553); Instant end = Instant.now(); System.out.println(Duration.between(start, end)); </code> Output is in ISO 8601 Duration format: <code>PT1M3.553S</code> (1 minute and 3.553 seconds).
Uhm... how many milliseconds are in a second? And in a minute? Division is not that hard. <code>int seconds = (int) ((milliseconds / 1000) % 60); int minutes = (int) ((milliseconds / 1000) / 60); </code> Continue like that for hours, days, weeks, months, year, decades, whatever.
How to build a query string for a URL in C#?
Curious that no one has mentioned QueryBuilder from AspNet.Core. It's helpful when you have a query with duplicate key like <code>?filter=a&filter=b</code> <code>var qb = new QueryBuilder(); qb.Add("filter", new string[] {"A", "B"}); </code> Then you'll just add qb to the URI, it is converted automatically to string. https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.extensions.querybuilder?view=aspnetcore-5.0
I needed to solve the same problem for a portable class library (PCL) that I'm working on. In this case, I don't have access to System.Web so I can't use ParseQueryString. Instead I used <code>System.Net.Http.FormUrlEncodedContent</code> like so: <code>var url = new UriBuilder("http://example.com"); url.Query = new FormUrlEncodedContent(new Dictionary<string,string>() { {"param1", "val1"}, {"param2", "val2"}, {"param3", "val3"}, }).ReadAsStringAsync().Result; </code>
A generic list of anonymous class <sep> In C# 3.0 you can create anonymous class with the following syntax <code>var o = new { Id = 1, Name = "Foo" }; </code> Is there a way to add these anonymous class to a generic list?
If you are using C# 7 or above, you can use tuple types instead of anonymous types. <code>var myList = new List<(int IntProp, string StrProp)>(); myList.Add((IntProp: 123, StrProp: "XYZ")); </code>
I usually use the following; mainly because you then "start" with a list that's empty. <code>var list = Enumerable.Range(0, 0).Select(e => new { ID = 1, Name = ""}).ToList(); list.Add(new {ID = 753159, Name = "Lamont Cranston"} ); //etc. </code> Lately, I've been writing it like this instead: <code>var list = Enumerable.Repeat(new { ID = 1, Name = "" }, 0).ToList(); list.Add(new {ID = 753159, Name = "Lamont Cranston"} ); </code> Using the repeat method would also allow you to do: <code>var myObj = new { ID = 1, Name = "John" }; var list = Enumerable.Repeat(myObj, 1).ToList(); list.Add(new { ID = 2, Name = "Liana" }); </code> ..which gives you the initial list with the first item already added.
Do I need to explicitly call the base virtual destructor?
Destructors in C++ automatically gets called in the order of their constructions (Derived then Base) only when the Base class destructor is declared <code>virtual</code>. If not, then only the base class destructor is invoked at the time of object deletion. Example: Without virtual Destructor <code>#include <iostream> using namespace std; class Base{ public: Base(){ cout << "Base Constructor \n"; } ~Base(){ cout << "Base Destructor \n"; } }; class Derived: public Base{ public: int *n; Derived(){ cout << "Derived Constructor \n"; n = new int(10); } void display(){ cout<< "Value: "<< *n << endl; } ~Derived(){ cout << "Derived Destructor \n"; } }; int main() { Base *obj = new Derived(); //Derived object with base pointer delete(obj); //Deleting object return 0; } </code> Output <code>Base Constructor Derived Constructor Base Destructor </code> Example: With Base virtual Destructor <code>#include <iostream> using namespace std; class Base{ public: Base(){ cout << "Base Constructor \n"; } //virtual destructor virtual ~Base(){ cout << "Base Destructor \n"; } }; class Derived: public Base{ public: int *n; Derived(){ cout << "Derived Constructor \n"; n = new int(10); } void display(){ cout<< "Value: "<< *n << endl; } ~Derived(){ cout << "Derived Destructor \n"; delete(n); //deleting the memory used by pointer } }; int main() { Base *obj = new Derived(); //Derived object with base pointer delete(obj); //Deleting object return 0; } </code> Output <code>Base Constructor Derived Constructor Derived Destructor Base Destructor </code> It is recommended to declare base class destructor as <code>virtual</code> otherwise, it causes undefined behavior. Reference: Virtual Destructor
No, you never call the base class destructor, it is always called automatically like others have pointed out but here is proof of concept with results: <code>class base { public: base() { cout << __FUNCTION__ << endl; } ~base() { cout << __FUNCTION__ << endl; } }; class derived : public base { public: derived() { cout << __FUNCTION__ << endl; } ~derived() { cout << __FUNCTION__ << endl; } // adding call to base::~base() here results in double call to base destructor }; int main() { cout << "case 1, declared as local variable on stack" << endl << endl; { derived d1; } cout << endl << endl; cout << "case 2, created using new, assigned to derive class" << endl << endl; derived * d2 = new derived; delete d2; cout << endl << endl; cout << "case 3, created with new, assigned to base class" << endl << endl; base * d3 = new derived; delete d3; cout << endl; return 0; } </code> The output is: <code>case 1, declared as local variable on stack base::base derived::derived derived::~derived base::~base case 2, created using new, assigned to derive class base::base derived::derived derived::~derived base::~base case 3, created with new, assigned to base class base::base derived::derived base::~base Press any key to continue . . . </code> If you set the base class destructor as virtual which one should, then case 3 results would be same as case 1 & 2.
Best way to format integer as string with leading zeros?
Python 3.6 f-strings allows us to add leading zeros easily: <code>number = 5 print(f' now we have leading zeros in {number:02d}') </code> Have a look at this good post about this feature.
For Python 3 and beyond: str.zfill() is still the most readable option But it is a good idea to look into the new and powerful str.format(), what if you want to pad something that is not 0? <code> # if we want to pad 22 with zeros in front, to be 5 digits in length: str_output = '{:0>5}'.format(22) print(str_output) # >>> 00022 # {:0>5} meaning: ":0" means: pad with 0, ">" means move 22 to right most, "5" means the total length is 5 # another example for comparision str_output = '{:#<4}'.format(11) print(str_output) # >>> 11## # to put it in a less hard-coded format: int_inputArg = 22 int_desiredLength = 5 str_output = '{str_0:0>{str_1}}'.format(str_0=int_inputArg, str_1=int_desiredLength) print(str_output) # >>> 00022 </code>
Is #pragma once a safe include guard?
I use it and I'm happy with it, as I have to type much less to make a new header. It worked fine for me in three platforms: Windows, Mac and Linux. I don't have any performance information but I believe that the difference between #pragma and the include guard will be nothing comparing to the slowness of parsing the C++ grammar. That's the real problem. Try to compile the same number of files and lines with a C# compiler for example, to see the difference. In the end, using the guard or the pragma, won't matter at all.
Using '<code>#pragma once</code>' might not have any effect (it is not supported everywhere - though it is increasingly widely supported), so you need to use the conditional compilation code anyway, in which case, why bother with '<code>#pragma once</code>'? The compiler probably optimizes it anyway. It does depend on your target platforms, though. If all your targets support it, then go ahead and use it - but it should be a conscious decision because all hell will break loose if you only use the pragma and then port to a compiler that does not support it.
How can I ssh directly to a particular directory?
My preferred approach is using the SSH config file (described below), but there are a few possible solutions depending on your usages. Command Line Arguments I think the best answer for this approach is christianbundy's reply to the accepted answer: <code>ssh -t example.com "cd /foo/bar; exec \$SHELL -l" </code> Using double quotes will allow you to use variables from your local machine, unless they are escaped (as <code>$SHELL</code> is here). Alternatively, you can use single quotes, and all of the variables you use will be the ones from the target machine: <code>ssh -t example.com 'cd /foo/bar; exec $SHELL -l' </code> Bash Function You can simplify the command by wrapping it in a bash function. Let's say you just want to type this: <code>sshcd example.com /foo/bar </code> You can make this work by adding this to your <code>~/.bashrc</code>: <code>sshcd () { ssh -t "$1" "cd \"$2\"; exec \$SHELL -l"; } </code> If you are using a variable that exists on the remote machine for the directory, be sure to escape it or put it in single quotes. For example, this will cd to the directory that is stored in the <code>JBOSS_HOME</code> variable on the remote machine: <code>sshcd example.com \$JBOSS_HOME </code> SSH Config File If you'd like to see this behavior all the time for specific (or any) hosts with the normal ssh command without having to use extra command line arguments, you can set the <code>RequestTTY</code> and <code>RemoteCommand</code> options in your ssh config file. For example, I'd like to type only this command: <code>ssh qaapps18 </code> but want it to always behave like this command: <code>ssh -t qaapps18 'cd $JBOSS_HOME; exec $SHELL' </code> So I added this to my <code>~/.ssh/config</code> file: <code>Host *apps* RequestTTY yes RemoteCommand cd $JBOSS_HOME; exec $SHELL </code> Now this rule applies to any host with "apps" in its hostname. For more information, see http://man7.org/linux/man-pages/man5/ssh_config.5.html
I've created a tool to SSH and CD into a server consecutively aptly named sshcd. For the example you've given, you'd simply use: <code>sshcd somehost:/some/directory/somewhere/named/Foo </code> Let me know if you have any questions or problems!
Which is better, return value or out parameter?
Return values are almost always the right choice when the method doesn't have anything else to return. (In fact, I can't think of any cases where I'd ever want a void method with an <code>out</code> parameter, if I had the choice. C# 7's <code>Deconstruct</code> methods for language-supported deconstruction acts as a very, very rare exception to this rule.) Aside from anything else, it stops the caller from having to declare the variable separately: <code>int foo; GetValue(out foo); </code> vs <code>int foo = GetValue(); </code> Out values also prevent method chaining like this: <code>Console.WriteLine(GetValue().ToString("g")); </code> (Indeed, that's one of the problems with property setters as well, and it's why the builder pattern uses methods which return the builder, e.g. <code>myStringBuilder.Append(xxx).Append(yyy)</code>.) Additionally, out parameters are slightly harder to use with reflection and usually make testing harder too. (More effort is usually put into making it easy to mock return values than out parameters). Basically there's nothing I can think of that they make easier... Return values FTW. EDIT: In terms of what's going on... Basically when you pass in an argument for an "out" parameter, you have to pass in a variable. (Array elements are classified as variables too.) The method you call doesn't have a "new" variable on its stack for the parameter - it uses your variable for storage. Any changes in the variable are immediately visible. Here's an example showing the difference: <code>using System; class Test { static int value; static void ShowValue(string description) { Console.WriteLine(description + value); } static void Main() { Console.WriteLine("Return value test..."); value = 5; value = ReturnValue(); ShowValue("Value after ReturnValue(): "); value = 5; Console.WriteLine("Out parameter test..."); OutParameter(out value); ShowValue("Value after OutParameter(): "); } static int ReturnValue() { ShowValue("ReturnValue (pre): "); int tmp = 10; ShowValue("ReturnValue (post): "); return tmp; } static void OutParameter(out int tmp) { ShowValue("OutParameter (pre): "); tmp = 10; ShowValue("OutParameter (post): "); } } </code> Results: <code>Return value test... ReturnValue (pre): 5 ReturnValue (post): 5 Value after ReturnValue(): 10 Out parameter test... OutParameter (pre): 5 OutParameter (post): 10 Value after OutParameter(): 10 </code> The difference is at the "post" step - i.e. after the local variable or parameter has been changed. In the ReturnValue test, this makes no difference to the static <code>value</code> variable. In the OutParameter test, the <code>value</code> variable is changed by the line <code>tmp = 10;</code>
What's better, depends on your particular situation. One of the reasons <code>out</code> exists is to facilitate returning multiple values from one method call: <code>public int ReturnMultiple(int input, out int output1, out int output2) { output1 = input + 1; output2 = input + 2; return input; } </code> So one is not by definition better than the other. But usually you'd want to use a simple return, unless you have the above situation for example. EDIT: This is a sample demonstrating one of the reasons that the keyword exists. The above is in no way to be considered a best practise.
Static link of shared library function in gcc <sep> How can I link a shared library function statically in gcc?
Yeah, I know this is an 8 year-old question, but I was told that it was possible to statically link against a shared-object library and this was literally the top hit when I searched for more information about it. To actually demonstrate that statically linking a shared-object library is not possible with <code>ld</code> (<code>gcc</code>'s linker) -- as opposed to just a bunch of people insisting that it's not possible -- use the following <code>gcc</code> command: <code>gcc -o executablename objectname.o -Wl,-Bstatic -l:libnamespec.so </code> (Of course you'll have to compile <code>objectname.o</code> from <code>sourcename.c</code>, and you should probably make up your own shared-object library as well. If you do, use <code>-Wl,--library-path,.</code> so that ld can find your library in the local directory.) The actual error you receive is: <code>/usr/bin/ld: attempted static link of dynamic object `libnamespec.so' collect2: error: ld returned 1 exit status </code> Hope that helps.
If you have the .a file of your shared library (.so) you can simply include it with its full path as if it was an object file, like this: This generates main.o by just compiling: <code>gcc -c main.c </code> This links that object file with the corresponding static library and creates the executable (named "main"): <code>gcc main.o mylibrary.a -o main </code> Or in a single command: <code>gcc main.c mylibrary.a -o main </code> It could also be an absolute or relative path: <code>gcc main.c /usr/local/mylibs/mylibrary.a -o main </code>
Do I need to heartbeat to keep a TCP connection open?
If your components: are in a conventional wired network there are no firewalls or NAT routers between them neither of them crash then you do not need to have a heartbeat. If any of these assumptions are false (I am looking at you, GPRS!), a heartbeat becomes necessary rather quickly.
You don't need to send heartbeats yourself. The TCP connection will remain open regardless of usage. Note that TCP implements an optional keepalive mechanism, which can be used to identify a closed connection in a timely fashion, rather than requiring you to send data at some later date and only then discover the connection is closed.
Git format-patch to be svn compatible?
I always have to Google this but the way I've found that works perfectly (for me) is: Create the patch with <code>git diff --no-prefix master..branch > somefile.diff</code>, the master and branch part are optional, depends how you want to get your diffs. Send it wherever and apply with <code>patch -p0 < somefile.diff</code>. It always seems to work fine for me and seems to be the simplest method that I've come across.
The short answer is <code>patch -p1 -i {patch.file}</code>. Please refer to this blog for details: Creating Subversion patches with git.
Why isn't all code compiled position independent?
It adds an indirection. With position independent code you have to load the address of your function and then jump to it. Normally the address of the function is already present in the instruction stream.
Yes there are performance reasons. Some accesses are effectively under another layer of indirection to get the absolute position in memory. There is also the GOT (Global offset table) which stores offsets of global variables. To me, this just looks like an IAT fixup table, which is classified as position dependent by wikipedia and a few other sources. http://en.wikipedia.org/wiki/Position_independent_code
How to determine if a string is a valid IPv4 or IPv6 address in C#?
Just a warning about using <code>System.Net.IpAddress.TryParse()</code>: If you pass it an string containing an integer (e.g. "3") the TryParse function will convert it to "0.0.0.3" and, therefore, a valid InterNetworkV4 address. So, at the very least, the reformatted "0.0.0.3" should be returned to the user application so the user knows how their input was interpreted.
<code>string myIpString = "192.168.2.1"; System.Net.IPAddress ipAddress = null; bool isValidIp = System.Net.IPAddress.TryParse(myIpString, out ipAddress); </code> If <code>isValidIp</code> is true, you can check <code>ipAddress.AddressFamily</code> to determine if it's IPv4 or IPv6. It's <code>AddressFamily.InterNetwork</code> for IPv4 and <code>AddressFamily.InterNetworkV6</code> for IPv6.
How can you get the first digit in an int (C#)?
Benchmarks Firstly, you must decide on what you mean by "best" solution, of course that takes into account the efficiency of the algorithm, its readability/maintainability, and the likelihood of bugs creeping up in the future. Careful unit tests can generally avoid those problems, however. I ran each of these examples 10 million times, and the results value is the number of <code>ElapsedTicks</code> that have passed. Without further ado, from slowest to quickest, the algorithms are: Converting to a string, take first character <code>int firstDigit = (int)(Value.ToString()[0]) - 48; </code> Results: <code>12,552,893 ticks </code> Using a logarithm <code>int firstDigit = (int)(Value / Math.Pow(10, (int)Math.Floor(Math.Log10(Value)))); </code> Results: <code>9,165,089 ticks </code> Looping <code>while (number >= 10) number /= 10; </code> Results: <code>6,001,570 ticks </code> Conditionals <code>int firstdigit; if (Value < 10) firstdigit = Value; else if (Value < 100) firstdigit = Value / 10; else if (Value < 1000) firstdigit = Value / 100; else if (Value < 10000) firstdigit = Value / 1000; else if (Value < 100000) firstdigit = Value / 10000; else if (Value < 1000000) firstdigit = Value / 100000; else if (Value < 10000000) firstdigit = Value / 1000000; else if (Value < 100000000) firstdigit = Value / 10000000; else if (Value < 1000000000) firstdigit = Value / 100000000; else firstdigit = Value / 1000000000; </code> Results: <code>1,421,659 ticks </code> Unrolled & optimized loop <code>if (i >= 100000000) i /= 100000000; if (i >= 10000) i /= 10000; if (i >= 100) i /= 100; if (i >= 10) i /= 10; </code> Results: <code>1,399,788 ticks </code> Note: each test calls <code>Random.Next()</code> to get the next <code>int</code>
variation on Anton's answer: <code> // cut down the number of divisions (assuming i is positive & 32 bits) if (i >= 100000000) i /= 100000000; if (i >= 10000) i /= 10000; if (i >= 100) i /= 100; if (i >= 10) i /= 10; </code>
`final` keyword equivalent for variables in Python?
Python 3.8 (via PEP 591) adds <code>Final</code> variables, functions, methods and classes. Here are some ways to use it: <code>@final</code> Decorator (classes, methods) <code>from typing import final @final class Base: # Cannot inherit from Base class Base: @final def foo(self): # Cannot override foo in subclass </code> <code>Final</code> annotation <code>from typing import Final PI: Final[float] = 3.14159 # Cannot set PI to another value KM_IN_MILES: Final = 0.621371 # Type annotation is optional class Foo: def __init__(self): self.bar: Final = "baz" # Final instance attributes only allowed in __init__ </code> Please note that like other typing hints, these do not prevent you from overriding the types, but they do help linters or IDEs warn you about incorrect type usage.
An assign-once variable is a design issue. You design your application in a way that the variable is set once and once only. However, if you want run-time checking of your design, you can do it with a wrapper around the object. <code>class OnePingOnlyPleaseVassily(object): def __init__(self): self.value = None def set(self, value): if self.value is not None: raise Exception("Already set.") self.value = value someStateMemo = OnePingOnlyPleaseVassily() someStateMemo.set(aValue) # works someStateMemo.set(aValue) # fails </code> That's clunky, but it will detect design problems at run time.
Running the same JUnit test case multiple time with different data <sep> Is there there any way to tell JUnit to run a specific test case multiple times with different data continuously before going on to the next test case?
take a look to junit 4.4 theories: <code>import org.junit.Test; import org.junit.experimental.theories.*; import org.junit.runner.RunWith; @RunWith(Theories.class) public class PrimeTest { @Theory public void isPrime(int candidate) { // called with candidate=1, candidate=2, etc etc } public static @DataPoints int[] candidates = {1, 2, 3, 4, 5}; } </code>
It sounds like that is a perfect candidate for parametrized tests. But, basically, parametrized tests allow you to run the same set of tests on different data. Here are some good blog posts about it: Writing a parameterized JUnit test Unit Testing with JUnit 4.0.
Why does defining __getitem__ on a class make it iterable in python?
Iteration's support for <code>__getitem__</code> can be seen as a "legacy feature" which allowed smoother transition when PEP234 introduced iterability as a primary concept. It only applies to classes without <code>__iter__</code> whose <code>__getitem__</code> accepts integers 0, 1, &c, and raises <code>IndexError</code> once the index gets too high (if ever), typically "sequence" classes coded before <code>__iter__</code> appeared (though nothing stops you from coding new classes this way too). Personally, I would rather not rely on this in new code, though it's not deprecated nor is it going away (works fine in Python 3 too), so this is just a matter of style and taste ("explicit is better than implicit" so I'd rather explicitly support iterability rather than rely on <code>__getitem__</code> supporting it implicitly for me -- but, not a bigge).
If you take a look at PEP234 defining iterators, it says: <code>1. An object can be iterated over with "for" if it implements __iter__() or __getitem__(). 2. An object can function as an iterator if it implements next(). </code>
Convert integer to hex and hex to integer <sep> So I have this query working (where <code>signal_data</code> is a column) in Sybase but it doesn't work in Microsoft SQL Server: <code>HEXTOINT(SUBSTRING((INTTOHEX(signal_data)),5,2)) as Signal </code> I also have it in Excel (where <code>A1</code> contains the value): <code>=HEX2DEC(LEFT(DEC2HEX(A1),LEN(DEC2HEX(A1))-2)) </code> Does anyone know how I would do this in SQL Server?
It is possible using the function FORMAT available on SQL Server 2012 and above <code>select FORMAT(10,'x2') </code> Results in: <code>0a </code>
Convert int to hex: <code>SELECT FORMAT(512+255,'X')</code>
How can I profile a multithread program in Python?
Please see yappi (Yet Another Python Profiler).
Instead of running one <code>cProfile</code>, you could run separate <code>cProfile</code> instance in each thread, then combine the stats. <code>Stats.add()</code> does this automatically.
Django vs other Python web frameworks?
<blockquote> the religious debates between the Django and WSGI camps </blockquote> It would seem as though you're a tad bit confused about what WSGI is and what Django is. Saying that Django and WSGI are competing is a bit like saying that C and SQL are competing: you're comparing apples and oranges. Django is a framework, WSGI is a protocol (which is supported by Django) for how the server interacts with the framework. Most importantly, learning to use WSGI directly is a bit like learning assembly. It's a great learning experience, but it's not really something you should do for production code (nor was it intended to be). At any rate, my advice is to figure it out for yourself. Most frameworks have a "make a wiki/blog/poll in an hour" type exercise. Spend a little time with each one and figure out which one you like best. After all, how can you decide between different frameworks if you're not willing to try them out?
I'd say you're being a bit too pessimistic about "not learning anything" using Django or a similar full-stack framework, and underestimating the value of documentation and a large community. Even with Django there's still a considerable learning curve; and if it doesn't do everything you want, it's not like the framework code is impenetrable. Some personal experience: I spent years, on and off, messing around with Twisted/Nevow, TurboGears and a few other Python web frameworks. Inever finished anything because the framework code was perpetually unfinished and being rewritten underneath me, the documentation was often nonexistent or wrong and the only viable support was via IRC (where I often got great advice, but felt like I was imposing if I asked too many questions). By comparison, in the past couple of years I've knocked off a few sites with Django. Unlike my previous experience, they're actually deployed and running. The Django development process may be slow and careful, but it results in much less bitrot and deprecation, and documentation that is actually helpful. HTTP authentication support for Django finally went in a few weeks ago, if that's what you're referring to in #3.
How can I refactor C++ source code using emacs?
In recent Emacs versions (24), Semantic is able to this. Possibly activate semantic mode M-x semantic-mode RET. Bring up the Symref buffer with C-c , g. Press C-c C-e to open all references. Rename with R.
If you can program in elisp, you can look to combination of cedet + srecode from CEDET libraries - it provide all instruments for this task - find callers of functions, get signature, etc. But you need to create refactory tool yourself, using these instruments
Notepad++ HTML Tidy <sep> Is HTML Tidy for Notepad++ broken?
Windows 7-10 x64, Notepad++ 5.9.5 Solution: It has to do with the libTidy.dll not being included in the current distributions. However, it was available in earlier versions. Solution is to download the 5.9 zip, then copy one of the following folders: ansi\plugins\Config\tidy or Unicode\plugins\Config\tidy to your current Notepad++\plugins\Config folder Also, if you install to the c:\Program Files or c:\Program Files (x86) directories, you will need to adjust the permissions on the tidy folder to allow non-administrator access
All of the menu options except the first one rewrite the HTMLTIDY.CFG file, which specifies the formatting rules that HTML Tidy uses. If HTMLTIDY.CFG does not exist, these menu options may not work. Create a text file and type a simple instruction like: <blockquote><code>text-spaces: 2</code></blockquote> Save the file as htmltidy.cfg in %ProgramFiles%\Notepad++\plugins\Config\tidy. Restart Notepad++ and all of the options should work.
Parallel execution of shell processes <sep> Is there a tool available to execute several process in parallel in a Windows batch file?
Try <code>start</code>: <code>start "title of the process" "P:\ath\to.exe" </code> It opens a new window with the given title and executes the BAT, CMD or EXE file. You can also set the priority, set the same environment etc. Files being not executeable are opened with the associated program. Further reading: Start -> Run <code>cmd /k start /? </code> Start is available at least since WinME. Good luck!
Sounds more like you want to use Powershell 2. However, you can spawn new <code>cmd</code> windows (or other processes) by using <code>start</code>, see also this answer. Although you probably have to use some other tools and a little trickery to create something like a "process pool" (to have only a maximum of n instances running at a time). You could achieve the latter by using <code>tasklist /im</code> and counting how many are already there (<code>for</code> loop or <code>wc</code>, if applicable) and simply wait (<code>ping -n 2 ::1 >nul 2>&1</code>) and re-check again whether you can spawn a new process. I have cobbled together a little test batch for this: <code>@echo off for /l %%i in (1,1,20) do call :loop %%i goto :eof :loop call :checkinstances if %INSTANCES% LSS 5 ( rem just a dummy program that waits instead of doing useful stuff rem but suffices for now echo Starting processing instance for %1 start /min wait.exe 5 sec goto :eof ) rem wait a second, can be adjusted with -w (-n 2 because the first ping returns immediately; rem otherwise just use an address that's unused and -n 1) echo Waiting for instances to close ... ping -n 2 ::1 >nul 2>&1 rem jump back to see whether we can spawn a new process now goto loop goto :eof :checkinstances rem this could probably be done better. But INSTANCES should contain the number of running instances afterwards. for /f "usebackq" %%t in (`tasklist /fo csv /fi "imagename eq wait.exe"^|find /c /v ""`) do set INSTANCES=%%t goto :eof </code> It spawns a maximum of four new processes that execute in parallel and minimized. Wait time needs to be adjusted probably, depending on how much each process does and how long it is running. You probably also need to adjust the process name for which tasklist is looking if you're doing something else. There is no way to properly count the processes that are spawned by this batch, though. One way would be to create a random number at the start of the batch (<code>%RANDOM%</code>) and create a helper batch that does the processing (or spawns the processing program) but which can set its window title to a parameter: <code>@echo off title %1 "%2" "%3" </code> This would be a simple batch that sets its title to the first parameter and then runs the second parameter with the third as argument. You can then filter in tasklist by selecting only processes with the specified window title (<code>tasklist /fi "windowtitle eq ..."</code>). This should work fairly reliable and prevents too many false positives. Searching for <code>cmd.exe</code> would be a bad idea if you still have some instances running, as that limits your pool of worker processes. You can use <code>%NUMBER_OF_PROCESSORS%</code> to create a sensible default of how many instances to spawn. You can also easily adapt this to use <code>psexec</code> to spawn the processes remotely (but wouldn't be very viable as you have to have admin privileges on the other machine as well as provide the password in the batch). You would have to use process names for filtering then, though.
A good project tree browser for Emacs?
Projectile + NeoTree are my combination of choice. Projectile just uses your version control system to track files and has an awesome jump to file in project function. Also, check the notes for integrating the two together.
Speedbar? If you just want to manage related files, perhaps you would like eproject.
How to fix ASP.NET error "The file 'nnn.aspx' has not been pre-compiled, and cannot be requested."?
I got this error when I upgraded a site from 2.0 to 4.0. The error was caused by a file <code>PrecompiledApp.config</code> in the site's <code>root</code> directory. Once I deleted that file, the site started working.
Just as a footnote to all of the above answers that resolved the issue via republishing to replace a missing assembly... While i have solved this issue previously with that same solution, i have just encountered another reason for it's occurrence which may assist others. The AppPool that my site was running under had it's "Enable 32-bit applications" setting set to false. By changing this to true via the "Advanced Settings" dialog of the app pool i resolved my issue. Hope that helps some other poor sucker.
PostgreSQL how to create a copy of a database or schema?
If it's on the same server, you just use the CREATE DATABASE command with the TEMPLATE parameter. For example: <code>CREATE DATABASE newdb WITH TEMPLATE olddb; </code>
<code>pg_dump</code> with the <code>--schema-only</code> option.
how to response.write bytearray?
You're probably looking for: <code>Response.BinaryWrite(tgtBytes); </code> MSDN documentation here.
<code>Response.OutputStream.Write(tgtBytes, 0, tgtBytes.Length); </code>
how (replace|create) an enum field on rails 2.0 migrations?
You can manually specify the type by using the <code>t.column</code> method instead. Rails will interpret this as a string column, and you can simply add a validator to the model like Pavel suggested: <code>class CreatePayments < ActiveRecord::Migration def self.up create_table :payments do |t| t.string :concept t.integer :user_id t.text :notes t.column :status, "ENUM('accepted', 'cancelled', 'pending')" t.timestamps end end def self.down drop_table :payments end end class Payment < ActiveRecord::Base validates_inclusion_of :status, :in => %w(accepted cancelled pending) end </code>
Look at tip #3 on http://zargony.com/2008/04/28/five-tips-for-developing-rails-applications This exactly what you need! <code> class User < ActiveRecord::Base validates_inclusion_of :status, :in => [:active, :inactive] def status read_attribute(:status).to_sym end def status= (value) write_attribute(:status, value.to_s) end end </code> HTH
What is a first class programming construct?
The notion of "first-class citizen" or "first-class element" in a programming language was introduced by British computer scientist Christopher Strachey in the 1960s in the context of first-class functions. The most famous formulation of this principle is probably in Structure and Interpretation of Computer Programs (just before <code>Exercise 1.40</code>) by Gerald Jay Sussman and Harry Abelson: They may be named by variables. They may be passed as arguments to procedures. They may be returned as the results of procedures. They may be included in data structures. Basically, it means that you can do with this programming language element everything that you can do with all other elements in the programming language.
I suspect you won't find a formal definition Apparently Jrg W Mittag found one :) Given that formal definition, the rest of my answer is merely my understanding of it at the time. Whether everyone who uses the term "first-class construct" means exactly the same thing is a different matter, of course. The way to determine whether something is a "first class" construct or not is to ask yourself something like this: <blockquote> Is the feature supported and thoroughly integrated with the rest of the language, or are there a lot of unnecessary restrictions which give the impression that it's just been "bolted on" possibly to tackle just one particular use case without consideration for other areas where the construct could be really useful if it had been more fully "part of the language"? </blockquote> As you can see, it's a definite grey area :) Delegates in C# are a good example, actually. In C# 1 you could pass delegates into methods, and there were plenty of ways in which they were well integrated into the language (things like conversions being available, event handling, += and -= translating to Delegate.Combine/Remove). I'd say they were first class constructs. However, that doesn't contradict the fact that delegates have gained tremendously from C# 2 and 3, with anonymous methods, implicit method group conversions, lambda expressions and covariance. They're arguably more of a first class construct now... and even though I would say they were "first class" in C# 1 I could see why someone might disagree. A similar case might be made for <code>IEnumerable</code>. In C# 1.0, it was supported by <code>foreach</code> but the <code>foreach</code> loop wouldn't dispose of the <code>IEnumerator</code> at the end. This part was fixed in C# 1.2, but there was still only language support for consuming <code>IEnumerable</code>s, not creating them. C# 2.0 provided iterator blocks, which make it trivial to implement <code>IEnumerable</code> (and its generic equivalent). Does that mean the concept of an iterable sequence wasn't a "first class" construct in C# 1.0? Debatable, basically...
Python sockets buffering <sep> Let's say I want to read a line from a socket, using the standard <code>socket</code> module: <code>def read_line(s): ret = '' while True: c = s.recv(1) if c == '\n' or c == '': break else: ret += c return ret </code> What exactly happens in <code>s.recv(1)</code>?
If you are concerned with performance and control the socket completely (you are not passing it into a library for example) then try implementing your own buffering in Python -- Python string.find and string.split and such can be amazingly fast. <code>def linesplit(socket): buffer = socket.recv(4096) buffering = True while buffering: if "\n" in buffer: (line, buffer) = buffer.split("\n", 1) yield line + "\n" else: more = socket.recv(4096) if not more: buffering = False else: buffer += more if buffer: yield buffer </code> If you expect the payload to consist of lines that are not too huge, that should run pretty fast, and avoid jumping through too many layers of function calls unnecessarily. I'd be interesting in knowing how this compares to file.readline() or using socket.recv(1).
The <code>recv()</code> call is handled directly by calling the C library function. It will block waiting for the socket to have data. In reality it will just let the <code>recv()</code> system call block. <code>file.readline()</code> is an efficient buffered implementation. It is not threadsafe, because it presumes it's the only one reading the file. (For example by buffering upcoming input.) If you are using the file object, every time <code>read()</code> is called with a positive argument, the underlying code will <code>recv()</code> only the amount of data requested, unless it's already buffered. It would be buffered if: you had called readline(), which reads a full buffer the end of the line was before the end of the buffer Thus leaving data in the buffer. Otherwise the buffer is generally not overfilled. The goal of the question is not clear. if you need to see if data is available before reading, you can <code>select()</code> or set the socket to nonblocking mode with <code>s.setblocking(False)</code>. Then, reads will return empty, rather than blocking, if there is no waiting data. Are you reading one file or socket with multiple threads? I would put a single worker on reading the socket and feeding received items into a queue for handling by other threads. Suggest consulting Python Socket Module source and C Source that makes the system calls.
wxPython: Calling an event manually <sep> How can I call a specific event manually from my own code?
Old topic, but I think I've got this figured out after being confused about it for a long time, so if anyone else comes through here looking for the answer, this might help. To manually post an event, you can use <code>self.GetEventHandler().ProcessEvent(event) </code> (wxWidgets docs here, wxPython docs here) or <code>wx.PostEvent(self.GetEventHandler(), event) </code> (wxWidgets docs, wxPython docs) where <code>event</code> is the event you want to post. Construct the event with e.g. <code>wx.PyCommandEvent(wx.EVT_BUTTON.typeId, self.GetId()) </code> if you want to post a EVT_BUTTON event. Making it a PyCommandEvent means that it will propagate upwards; other event types don't propagate by default. You can also create custom events that can carry whatever data you want them to. Here's an example: <code>myEVT_CUSTOM = wx.NewEventType() EVT_CUSTOM = wx.PyEventBinder(myEVT_CUSTOM, 1) class MyEvent(wx.PyCommandEvent): def __init__(self, evtType, id): wx.PyCommandEvent.__init__(self, evtType, id) myVal = None def SetMyVal(self, val): self.myVal = val def GetMyVal(self): return self.myVal </code> (I think I found this code in a mailing list archive somewhere, but I can't seem to find it again. If this is your example, thanks! Please add a comment and take credit for it!) So now, to Post a custom event: <code>event = MyEvent(myEVT_CUSTOM, self.GetId()) event.SetMyVal('here is some custom data') self.GetEventHandler().ProcessEvent(event) </code> and you can bind it just like any other event <code>self.Bind(EVT_CUSTOM, self.on_event) </code> and get the custom data in the event handler <code>def on_event(self, e): data = e.GetMyVal() print 'custom data is: {0}'.format(data) </code> Or include the custom data in the event constructor and save a step: <code>class MyEvent(wx.PyCommandEvent): def __init__(self, evtType, id, val = None): wx.PyCommandEvent.__init__(self, evtType, id) self.myVal = val </code> etc. Hope this is helpful to someone.
I think you want wx.PostEvent. There's also some info about posting events from other thread for long running tasks on the wxPython wiki.
selenium vs windmill <sep> Selenium vs. Windmill, what are your experiences, what do you recommend?
I am by no means an impartial commenter (I'm a windmill core developer). Windmill supports testing multiple domains inside a single test and even across SSL connections, Selenium does not (Selenium2.0 will support this via WebDriver). Windmill has an amazing community, hop on to #windmill on irc.freenode.org any time and someone who help you out. Windmill supports Python and JavaScript for test writing, and it supports them very well. Windmill includes debugging tools in an integrated IDE with Firebug integration and all kinds of other useful features. Windmill has been used by some facebook applications for about a year now, the process of supporting these users meant that Windmill had to find a way to deal with every terrible thing a site can do in javascript because Facebook does ALL OF THEM! If you're not using Python or JavaScript don't bother with Windmill at this time. There is an RSpec API for Ruby written by a community member using a JSONRPC interface that anyone else could use to create bindings in a new language but these are the only ones supported at this time.
Windmill started as a fork of Selenium but now is almost an entirely different codebase. I've never used it myself, but I would note: Selenium has a very active community. So my recommendation is: unless there's something in Windmill you must have (ie: native Python support), go with Selenium.
Windows Registry best practices <sep> In what way is the Windows registry meant to be used?
I'm going to take a contrarian view. The registry is a fine place to put configuration data of all types. In general it is faster than most configuration files and more reliable (individual operations on the registry are transacted so if your app crashes during a write the registry isn't corrupted - in general that isn't the case with ini files). Marcelo MD is totally right: Storing things like operation percentage complete in the registry (or any other non volitile storage) is a horrible idea. On the other hand storing data like the most recently used files is just fine - the registry was built for just that kind of problem. A number of the other commenters on this post talking about the MRU list have discussed the problem of what happens when the MRU list gets out of sync due to application crashes. I'm wondering why storing the MRU list in a flat file in per-user storage is any better? I'm also not sure what the "security implications" of storing your data in the registry are. The registry is just as secure as the filesystem - the registry and the filesystem use the same ACL mechanism to protect their data. If you ARE going to store your user data in a file, you should absolutely put your data in %APPDATA%\CompanyName\ApplicationName at least - that way if two different developers create an application with the same name (how many "Media Manager" applications are there out there?) you won't have collisions.
For me, simple user configuration items and user data is better to be stored in either a simple XML configuration file, a SQLLite db, or a MS SQL Server Compact db. The exact storage medium depends on the specifics of the implementation. I only use the registry for things that I need to set infrequently and that users don't need to be able to change/see. For example, I have stored encrypted license information in the registry before to avoid accidental user removal of the data.
Is There A Built-In Way to Split Strings In C++?
Here's a perl-style split function I use: <code>void split(const string& str, const string& delimiters , vector<string>& tokens) { // Skip delimiters at beginning. string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". string::size_type pos = str.find_first_of(delimiters, lastPos); while (string::npos != pos || string::npos != lastPos) { // Found a token, add it to the vector. tokens.push_back(str.substr(lastPos, pos - lastPos)); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } } </code>
There's no built-in way to split a string in C++, but boost provides the string algo library to do all sort of string manipulation, including string splitting.
How do I turn off slow motion in the iPhone simulator?
Updated: <code>version 11.3</code> (2019 Dec) works fine. I have iOS Simulator <code>version 8.3</code> (Xcode 6) and the new shortcut is command + T to toggle "Slow Animations"
Pre beta 5 it was tripple shift. Apple changed (or broke it) see this question (which doesn't have an answer).
window.showModalDialog vs. window.open <sep> What are situation when you want to use window.showModalDialog function?
It has been a few years since this question was originally asked and things have changed a bit since then. <code>window.showModalDialog</code> is now officially standardized as part of HTML5 and is supported in IE, Firefox 3+, Chrome (albeit buggy), and Safari 5.1+. Unfortunately <code>window.showModalDialog</code> is still plagued by a number of issues. Modal dialogs are blocked as popups by default in Firefox, Chrome, and Safari. The modal dialogs in Chrome are buggy and aren't truly modal - see http://code.google.com/p/chromium/issues/detail?id=16045 & http://code.google.com/p/chromium/issues/detail?id=42939. All browsers except Chrome block the user from interacting with the entire window (favorites, browser controls, other tabs, etc...) when a modal dialog is up. They're a pain to debug because they halt JavaScript execution in the parent window while waiting for the modal dialog to complete. No mobile browsers support <code>window.showModalDialog</code>. Therefore it's still not a good idea to use <code>window.showModalDialog</code>. If you need the window opened to be modal (i.e. the user cannot interact with the rest of the page until they deal with the dialog) I would suggest using jQuery UI's dialog plugin. <code>window.open</code> will work for non modal windows but I would stick with jQuery UI's dialog because opening new windows tends to annoy users. If you're interested I write about this in more detail on my blog - http://tjvantoll.com/2012/05/02/showmodaldialog-what-it-is-and-why-you-should-never-use-it/.
Modal dialogs are dialogs that once opened by the parent, do not allow you to focus on the parent until the dialog is closed. One could use a modal dialog for a login form, edit form, etc where you want to have a popup for user interaction but not allow the user to return to the window that opened the popup. As a side note, I believe only Internet Explorer implementes <code>window.showModalDialog</code>, so that kind of limits your usage of it.
How can I detect touch in cocos2d?
A better way to do this is to actually use the bounding box on the sprite itself (which is a CGRect). In this sample code, I put all my sprites in a NSMutableArray and I simple check if the sprite touch is in the bounding box. Make sure you turn on touch detection in the init. If you notice I also accept/reject touches on the layer by returning YES(if I use the touch) or NO(if I don't) <code>- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event { CGPoint location = [self convertTouchToNodeSpace: touch]; for (CCSprite *station in _objectList) { if (CGRectContainsPoint(station.boundingBox, location)) { DLog(@"Found sprite"); return YES; } } return NO; } </code>
Following Jonas's instructions, and adding onto it a bit more ... <code>- (void)ccTouchesBegan:(NSSet*)touches withEvent:(UIEvent*)event { UITouch* touch = [touches anyObject]; CGPoint location = [[[Director sharedDirector] convertCoordinate: touch.location]; CGRect particularSpriteRect = CGMakeRect(particularSprite.position.x, particularSprite.position.y, particularSprite.contentSize.width, particularSprite.contentSize.height); if(CGRectContainsPoint(particularSpriteRect, location)) { // particularSprite touched return kEventHandled; } } </code> You may need to adjust the x/y a little to account for the 'centered positioning' in Cocos
What rendering engine does cfdocument use for HTML-&gt;PDF conversion?
Yes, it does use iText. CF8 uses version 1.4: <code><cfset doc = createObject("java", "com.lowagie.text.Document")> <cfdump var="#doc.getVersion()#"> </code>
The documentation for the <code>cfdocument</code> tag includes a listing of the supported CSS styles.
How do I add an existing directory tree to a project in Visual Studio?
In Visual Studio 2015, this is how you do it. If you want to automatically include all descendant files below a specific folder: <code><Content Include="Path\To\Folder\**" /> </code> This can be restricted to include only files within the path specified: <code><Content Include="Path\To\Folder\*.*" /> </code> Or even only files with a specified extension: <code><Content Include="Path\To\Folder\*.jpg" > </code>
Copy & Paste. To Add a folder, all the sub-directories, and files we can also Copy and Paste. For example we can: Right click in Windows explorer on the folder, and Copy on the folder with many files and folders. Then in Visual Studio Solution explorer, right click on the destination folder and click paste. Optional add to TFS; Then in the top folder right click and check in to TFS to check in all sub-folders and files.
Eclipse jump to closing brace <sep> What is the keyboard short cut in Eclipse to jump to the closing brace of a scope?
To select content use Alt + Shift + Up arrow To select content up to the next wrapping block press this shortcut again To go back one step press Alt + Shift + Down arrow. This is also a useful shortcut when you need to select content in a complex expression and do not want to miss something.
Press Ctrl + Shift + P. Before Eclipse Juno you need to place the cursor just beyond an opening or closing brace. In Juno cursor can be anywhere in the code block.
Returning multiple values from a C++ function <sep> Is there a preferred way to return multiple values from a C++ function?
With C++17 you can also return one ore more unmovable/uncopyable values (in certain cases). The possibility to return unmovable types come via the new guaranteed return value optimization, and it composes nicely with aggregates, and what can be called templated constructors. <code>template<typename T1,typename T2,typename T3> struct many { T1 a; T2 b; T3 c; }; // guide: template<class T1, class T2, class T3> many(T1, T2, T3) -> many<T1, T2, T3>; auto f(){ return many{string(),5.7, unmovable()}; }; int main(){ // in place construct x,y,z with a string, 5.7 and unmovable. auto [x,y,z] = f(); } </code> The pretty thing about this is that it is guaranteed to not cause any copying or moving. You can make the example <code>many</code> struct variadic too. More details: Returning variadic aggregates (struct) and syntax for C++17 variadic template 'construction deduction guide'
The OO solution for this is to create a ratio class. It wouldn't take any extra code (would save some), would be significantly cleaner/clearer, and would give you some extra refactorings letting you clean up code outside this class as well. Actually I think someone recommended returning a structure, which is close enough but hides the intent that this needs to be a fully thought-out class with constructor and a few methods, in fact, the "method" that you originally mentioned (as returning the pair) should most likely be a member of this class returning an instance of itself. I know your example was just an "Example", but the fact is that unless your function is doing way more than any function should be doing, if you want it to return multiple values you are almost certainly missing an object. Don't be afraid to create these tiny classes to do little pieces of work--that's the magic of OO--you end up breaking it down until every method is very small and simple and every class small and understandable. Another thing that should have been an indicator that something was wrong: in OO you have essentially no data--OO isn't about passing around data, a class needs to manage and manipulate it's own data internally, any data passing (including accessors) is a sign that you may need to rethink something..
How do I include a pipe | in my linux find -exec command?
The job of interpreting the pipe symbol as an instruction to run multiple processes and pipe the output of one process into the input of another process is the responsibility of the shell (/bin/sh or equivalent). In your example you can either choose to use your top level shell to perform the piping like so: <code>find -name 'file_*' -follow -type f -exec zcat {} \; | agrep -dEOE 'grep' </code> In terms of efficiency this results costs one invocation of find, numerous invocations of zcat, and one invocation of agrep. This would result in only a single agrep process being spawned which would process all the output produced by numerous invocations of zcat. If you for some reason would like to invoke agrep multiple times, you can do: <code>find . -name 'file_*' -follow -type f \ -printf "zcat %p | agrep -dEOE 'grep'\n" | sh </code> This constructs a list of commands using pipes to execute, then sends these to a new shell to actually be executed. (Omitting the final "| sh" is a nice way to debug or perform dry runs of command lines like this.) In terms of efficiency this results costs one invocation of find, one invocation of sh, numerous invocations of zcat and numerous invocations of agrep. The most efficient solution in terms of number of command invocations is the suggestion from Paul Tomblin: <code>find . -name "file_*" -follow -type f -print0 | xargs -0 zcat | agrep -dEOE 'grep' </code> ... which costs one invocation of find, one invocation of xargs, a few invocations of zcat and one invocation of agrep.
<code>find . -name "file_*" -follow -type f -print0 | xargs -0 zcat | agrep -dEOE 'grep' </code>
In JavaScript can I make a "click" event fire programmatically for a file input element?
just use a label tag, that way you can hide the input, and make it work through its related label https://developer.mozilla.org/fr/docs/Web/HTML/Element/Label
For those who understand that you have to overlay an invisible form over the link, but are too lazy to write, I wrote it for you. Well, for me, but might as well share. Comments are welcome. HTML (Somewhere): <code><a id="fileLink" href="javascript:fileBrowse();" onmouseover="fileMove();">File Browse</a> </code> HTML (Somewhere you don't care about): <code><div id="uploadForm" style="filter:alpha(opacity=0); opacity: 0.0; width: 300px; cursor: pointer;"> <form method="POST" enctype="multipart/form-data"> <input type="file" name="file" /> </form> </div> </code> JavaScript: <code>function pageY(el) { var ot = 0; while (el && el.offsetParent != el) { ot += el.offsetTop ? el.offsetTop : 0; el = el.offsetParent; } return ot; } function pageX(el) { var ol = 0; while (el && el.offsetParent != el) { ol += el.offsetLeft ? el.offsetLeft : 0; el = el.offsetParent; } return ol; } function fileMove() { if (navigator.appName == "Microsoft Internet Explorer") { return; // Don't need to do this in IE. } var link = document.getElementById("fileLink"); var form = document.getElementById("uploadForm"); var x = pageX(link); var y = pageY(link); form.style.position = 'absolute'; form.style.left = x + 'px'; form.style.top = y + 'px'; } function fileBrowse() { // This works in IE only. Doesn't do jack in FF. :( var browseField = document.getElementById("uploadForm").file; browseField.click(); } </code>
How to get a variable name as a string in PHP?
Lucas on PHP.net provided a reliable way to check if a variable exists. In his example, he iterates through a copy of the global variable array (or a scoped array) of variables, changes the value to a randomly generated value, and checks for the generated value in the copied array. <code>function variable_name( &$var, $scope=false, $prefix='UNIQUE', $suffix='VARIABLE' ){ if($scope) { $vals = $scope; } else { $vals = $GLOBALS; } $old = $var; $var = $new = $prefix.rand().$suffix; $vname = FALSE; foreach($vals as $key => $val) { if($val === $new) $vname = $key; } $var = $old; return $vname; } </code> Then try: <code>$a = 'asdf'; $b = 'asdf'; $c = FALSE; $d = FALSE; echo variable_name($a); // a echo variable_name($b); // b echo variable_name($c); // c echo variable_name($d); // d </code> Be sure to check his post on PHP.net: http://php.net/manual/en/language.variables.php
I made an inspection function for debugging reasons. It's like print_r() on steroids, much like Krumo but a little more effective on objects. I wanted to add the var name detection and came out with this, inspired by Nick Presta's post on this page. It detects any expression passed as an argument, not only variable names. This is only the wrapper function that detects the passed expression. Works on most of the cases. It will not work if you call the function more than once in the same line of code. This works fine: die(inspect($this->getUser()->hasCredential("delete"))); inspect() is the function that will detect the passed expression. We get: $this->getUser()->hasCredential("delete") <code>function inspect($label, $value = "__undefin_e_d__") { if($value == "__undefin_e_d__") { /* The first argument is not the label but the variable to inspect itself, so we need a label. Let's try to find out it's name by peeking at the source code. */ /* The reason for using an exotic string like "__undefin_e_d__" instead of NULL here is that inspected variables can also be NULL and I want to inspect them anyway. */ $value = $label; $bt = debug_backtrace(); $src = file($bt[0]["file"]); $line = $src[ $bt[0]['line'] - 1 ]; // let's match the function call and the last closing bracket preg_match( "#inspect\((.+)\)#", $line, $match ); /* let's count brackets to see how many of them actually belongs to the var name Eg: die(inspect($this->getUser()->hasCredential("delete"))); We want: $this->getUser()->hasCredential("delete") */ $max = strlen($match[1]); $varname = ""; $c = 0; for($i = 0; $i < $max; $i++){ if( $match[1]{$i} == "(" ) $c++; elseif( $match[1]{$i} == ")" ) $c--; if($c < 0) break; $varname .= $match[1]{$i}; } $label = $varname; } // $label now holds the name of the passed variable ($ included) // Eg: inspect($hello) // => $label = "$hello" // or the whole expression evaluated // Eg: inspect($this->getUser()->hasCredential("delete")) // => $label = "$this->getUser()->hasCredential(\"delete\")" // now the actual function call to the inspector method, // passing the var name as the label: // return dInspect::dump($label, $val); // UPDATE: I commented this line because people got confused about // the dInspect class, wich has nothing to do with the issue here. echo("The label is: ".$label); echo("The value is: ".$value); } </code> Here's an example of the inspector function (and my dInspect class) in action: http://inspect.ip1.cc Texts are in spanish in that page, but code is concise and really easy to understand.
How do I simulate a low bandwidth, high latency environment?
I found this little neat program for Windows called clumsy. It's in kind of alpha status, but it seem to work fine for me, and it's open source. Edit: Others have noticed that you can't limit bandwidth with clumsy, and that's true. You can only add Latency and a couple of other network related errors. This will disqualify this answer as a valid answer to the question, however since I had good use for it when I wanted to simulate a bad network so I'll leave it here as long as it has > 0 votes or similar.
For Windows you can use this application: http://www.softperfect.com/products/connectionemulator/ WAN Connection Emulator for Windows 2000, XP, 2003, Vista, Seven and 2008. Perhaps the only one available for Windows.
Maven compile with multiple src directories <sep> Is there a way to compile multiple java source directories in a single maven project?
I naively do it this way : <code><build> <finalName>osmwse</finalName> <sourceDirectory>src/main/java, src/interfaces, src/services</sourceDirectory> </build> </code>
This worked for me <code><build> <sourceDirectory>.</sourceDirectory> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <includes> <include>src/main/java/**/*.java</include> <include>src/main2/java/**/*.java</include> </includes> </configuration> </plugin> </plugins> </build> </code>
How to list only top level directories in Python?
This seems to work too (at least on linux): <code>import glob, os glob.glob('*' + os.path.sep) </code>
Note that, instead of doing <code>os.listdir(os.getcwd())</code>, it's preferable to do <code>os.listdir(os.path.curdir)</code>. One less function call, and it's as portable. So, to complete the answer, to get a list of directories in a folder: <code>def listdirs(folder): return [d for d in os.listdir(folder) if os.path.isdir(os.path.join(folder, d))] </code> If you prefer full pathnames, then use this function: <code>def listdirs(folder): return [ d for d in (os.path.join(folder, d1) for d1 in os.listdir(folder)) if os.path.isdir(d) ] </code>
Starting Eclipse w/ Specific Workspace <sep> Is there a way to start an instance of eclipse, passing it some sort of parameter telling it to use a specific workspace?
We set the default workspace for students at a high school by modifying the shortcut properties. In this case, we operate a Windows 7 environment. The default workspace is on a student's network share mapped as the H: drive so we added -data h:\workspace. The screenshot shows exactly where.
note that you can use UNIX-style relative path names such as <code>-data ../workspace </code> even under Windows, in case something doesn't like colons or backslashes in parameters, like Jumplist Launcher
Prevent multiple instances of a given app in .NET?
Use Mutex. One of the examples above using GetProcessByName has many caveats. Here is a good article on the subject: http://odetocode.com/Blogs/scott/archive/2004/08/20/401.aspx <code>[STAThread] static void Main() { using(Mutex mutex = new Mutex(false, "Global\\" + appGuid)) { if(!mutex.WaitOne(0, false)) { MessageBox.Show("Instance already running"); return; } Application.Run(new Form1()); } } private static string appGuid = "c0a76b5a-12ab-45c5-b9d9-d693faa6e7b9"; </code>
<code>if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1) { AppLog.Write("Application XXXX already running. Only one instance of this application is allowed", AppLog.LogMessageType.Warn); return; } </code>
How many database indexes is too many?
In data warehousing it is very common to have a high number of indexes. I have worked with fact tables having two hundred columns and 190 of them indexed. Although there is an overhead to this it must be understood in the context that in a data warehouse we generally only insert a row once, we never update it, but it can then participate in thousands of SELECT queries which might benefit from indexing on any of the columns. For maximum flexibility a data warehouse generally uses single column bitmap indexes except on high cardinality columns, where (compressed) btree indexes can be used. The overhead on index maintenance is mostly associated with the expense of writing to a great many blocks and the block splits as new rows are added with values that are "in the middle" of existing value ranges for that column. This can be mitigated by partitioning and having the new data loads aligned with the partitioning scheme, and by using direct path inserts. To address your question more directly, I think it is probably fine to index the obvious at first, but do not be afraid of adding more indexes on if the queries against the table would benefit.
In a paraphrase of Einstein about simplicity, add as many indexes as you need and no more. Seriously, however, every index you add requires maintenance whenever data is added to the table. On tables that are primarily read only, lots of indexes are a good thing. On tables that are highly dynamic, fewer is better. My advice is to cover the common and obvious cases and then, as you encounter issues where you need more speed in getting data from specific tables, evaluate and add indices at that point. Also, it's a good idea to re-evaluate your indexing schemes every few months, just to see if there is anything new that needs indexing or any indices that you've created that aren't being used for anything and should be gotten rid of.
How to see what will be updated from repository before issuing "svn update" command?
Depending on what you want to know between your working copy and the latest svn server repository, without updating your local working copy, here is what you can do: if you want to know what has been changed in svn server repository, run command: <code>$ svn st -u </code> if you want to know if the same file has been modified both in your local working copy and in svn server repository, run command: <code>$ svn st -u | grep -E '^M {7}\*' </code> if you want to get list of files changed between a particular revision and HEAD, run command: <code>$ svn diff -r revisionNumber:HEAD --summarize </code> if you want to get a list of files changed between paticular revisions, run command: <code>$ svn diff -r revisionNumber:anotherRevisionNumber --summarize </code> if you want to see what will be updated (without actually updating), run command: <code>$ svn merge --dry-run -r BASE:HEAD . </code> if you want to know what content of a particular file has been changed in svn server repository compared with your working copy, run command: <code>$ svn diff -r BASE:HEAD ./pathToYour/file </code> if you want to know what contents of all the files have been changed in svn server repository compared with your working copy, run command: <code>$ svn diff -r BASE:HEAD . </code>
The same but shorter shorter :) : <code>svn st -u </code>
What is __gxx_personality_v0 for?
It is used in the stack unwiding tables, which you can see for instance in the assembly output of my answer to another question. As mentioned on that answer, its use is defined by the Itanium C++ ABI, where it is called the Personality Routine. The reason it "works" by defining it as a global NULL void pointer is probably because nothing is throwing an exception. When something tries to throw an exception, then you will see it misbehave. Of course, if nothing is using exceptions, you can disable them with <code>-fno-exceptions</code> (and if nothing is using RTTI, you can also add <code>-fno-rtti</code>). If you are using them, you have to (as other answers already noted) link with <code>g++</code> instead of <code>gcc</code>, which will add <code>-lstdc++</code> for you.
Exception handling is included in free standing implementations. The reason of this is that you possibly use <code>gcc</code> to compile your code. If you compile with the option <code>-###</code> you will notice it is missing the linker-option <code>-lstdc++</code> when it invokes the linker process . Compiling with <code>g++</code> will include that library, and thus the symbols defined in it.
What is the difference between List (of T) and Collection(of T)?
In C#, there are three concepts for representing a bag of objects. In order of increasing features, they are: Enumerable - unordered, unmodifiable Collection - can add/remove items List - allows items to have an order (accessing and removing by index) Enumerable has no order. You cannot add or remove items from the set. You cannot even get a count of items in the set. It strictly lets you access each item in the set, one after the other. Collection is a modifiable set. You can add and remove objects from the set, you can also get the count of items in the set. But there still is no order, and because there is no order: no way to access an item by index, nor is there any way to sort. List is an ordered set of objects. You can sort the list, access items by index, remove items by index. In fact, when looking at the interfaces for these, they build on one another: <code>interface IEnumerable<T></code> <code>GetEnumeration<T></code> <code>interface ICollection<T> : IEnumerable<T></code> <code>Add</code> <code>Remove</code> <code>Clear</code> <code>Count</code> <code>interface IList<T> : ICollection<T></code> <code>Insert</code> <code>IndexOf</code> <code>RemoveAt</code> When declaring variables, or method parameters, you should choose to use IEnumerable ICollection IList based on what conceptually you need to do with the set of objects. If you just need to be able to do something to every object in a list, then you only need <code>IEnumerable</code>: <code>void SaveEveryUser(IEnumerable<User> users) { for User u in users ... } </code> You don't care if the Users are kept in a <code>List<T></code>, <code>Collection<T></code>, <code>Array<T></code> or anything else. You only need the <code>IEnumerable<T></code> interface. If you need to be able to add, remove, or count the items in a set, then use a Collection: <code>ICollection<User> users = new Collection<User>(); users.Add(new User()); </code> If you care about a sort order, and need the order to be correct, then use a List: <code>IList<User> users = FetchUsers(db); </code> In chart form: <code>| Feature | IEnumerable<T> | ICollection<T> | IList<T> | |------------------------|----------------|----------------|----------| | Enumerating items | X | X | X | | | | | | | Adding items | | X | X | | Removing items | | X | X | | Count of items | | X | X | | | | | | | Accessing by index | | | X | | Removing by index | | | X | | Getting index of item | | | X | </code> The <code>List<T></code> and <code>Collection<T></code> in <code>System.Collections.Generic</code> are two classes that implement these interfaces; but they aren't the only classes: <code>ConcurrentBag<T></code> is an ordered bag of objects (<code>IEnumerable<T></code>) <code>LinkedList<T></code> is a bag where you are not allowed to access items by index (<code>ICollection</code>); but you can arbitrarily add and remove items from the collection <code>SynchronizedCollection<T></code> is an ordered collection, where you can add/remove items by index So you can easily change: <code>IEnumerable<User> users = new SynchronizedCollection<User>(); SaveEveryUser(users); </code> tl;dr Enumerable - access items, unordered, unmodifiable Collection - can be modified (add,delete,count) List - can access by index Choose the concept you need, then use the matching class.
<code>Collection<T></code> is a customizable wrapper around <code>IList<T></code>. While <code>IList<T></code> is not sealed, it doesn't provide any customization points. <code>Collection<T></code>'s methods are by default delegated to the standard <code>IList<T></code> methods, but can be easily overridden to do what you want. It is also possible to wireup events inside a <code>Collection<T></code> that I don't believe could be done with an IList. In short, it's much easier to extend it after the fact, which could potentially mean a lot less refactoring.
std::map insert or std::map find?
The answer is you do neither. Instead you want to do something suggested by Item 24 of Effective STL by Scott Meyers: <code>typedef map<int, int> MapType; // Your map type may vary, just change the typedef MapType mymap; // Add elements to map here int k = 4; // assume we're searching for keys equal to 4 int v = 0; // assume we want the value 0 associated with the key of 4 MapType::iterator lb = mymap.lower_bound(k); if(lb != mymap.end() && !(mymap.key_comp()(k, lb->first))) { // key already exists // update lb->second if you care to } else { // the key does not exist in the map // add it to the map mymap.insert(lb, MapType::value_type(k, v)); // Use lb as a hint to insert, // so it can avoid another lookup } </code>
The answer to this question also depends on how expensive it is to create the value type you're storing in the map: <code>typedef std::map <int, int> MapOfInts; typedef std::pair <MapOfInts::iterator, bool> IResult; void foo (MapOfInts & m, int k, int v) { IResult ir = m.insert (std::make_pair (k, v)); if (ir.second) { // insertion took place (ie. new entry) } else if ( replaceEntry ( ir.first->first ) ) { ir.first->second = v; } } </code> For a value type such as an int, the above will more efficient than a find followed by an insert (in the absence of compiler optimizations). As stated above, this is because the search through the map only takes place once. However, the call to insert requires that you already have the new "value" constructed: <code>class LargeDataType { /* ... */ }; typedef std::map <int, LargeDataType> MapOfLargeDataType; typedef std::pair <MapOfLargeDataType::iterator, bool> IResult; void foo (MapOfLargeDataType & m, int k) { // This call is more expensive than a find through the map: LargeDataType const & v = VeryExpensiveCall ( /* ... */ ); IResult ir = m.insert (std::make_pair (k, v)); if (ir.second) { // insertion took place (ie. new entry) } else if ( replaceEntry ( ir.first->first ) ) { ir.first->second = v; } } </code> In order to call 'insert' we are paying for the expensive call to construct our value type - and from what you said in the question you won't use this new value 20% of the time. In the above case, if changing the map value type is not an option then it is more efficient to first perform the 'find' to check if we need to construct the element. Alternatively, the value type of the map can be changed to store handles to the data using your favourite smart pointer type. The call to insert uses a null pointer (very cheap to construct) and only if necessary is the new data type constructed.
What's the best method in ASP.NET to obtain the current domain?
<code>Request.Url.GetLeftPart(UriPartial.Authority) </code> This is included scheme.
WARNING! To anyone who uses Current.Request.Url.Host. Understand that you are working based on the CURRENT REQUEST and that the current request will not ALWAYS be with your server and can sometimes be with other servers. So if you use this in something like, Application_BeginRequest() in Global.asax, then 99.9% of the time it will be fine, but 0.1% you might get something other than your own server's host name. A good example of this is something I discovered not long ago. My server tends to hit http://proxyjudge1.proxyfire.net/fastenv from time to time. Application_BeginRequest() gladly handles this request so if you call Request.Url.Host when it's making this request you'll get back proxyjudge1.proxyfire.net. Some of you might be thinking "no duh" but worth noting because it was a very hard bug to notice since it only happened 0.1% of the time : P This bug has forced me to insert my domain host as a string in the config files.
Is there a way to make a TSQL variable constant?
One solution, offered by Jared Ko is to use pseudo-constants. As explained in SQL Server: Variables, Parameters or Literals? Or Constants?: <blockquote> Pseudo-Constants are not variables or parameters. Instead, they're simply views with one row, and enough columns to support your constants. With these simple rules, the SQL Engine completely ignores the value of the view but still builds an execution plan based on its value. The execution plan doesn't even show a join to the view! Create like this: <code>CREATE SCHEMA ShipMethod GO -- Each view can only have one row. -- Create one column for each desired constant. -- Each column is restricted to a single value. CREATE VIEW ShipMethod.ShipMethodID AS SELECT CAST(1 AS INT) AS [XRQ - TRUCK GROUND] ,CAST(2 AS INT) AS [ZY - EXPRESS] ,CAST(3 AS INT) AS [OVERSEAS - DELUXE] ,CAST(4 AS INT) AS [OVERNIGHT J-FAST] ,CAST(5 AS INT) AS [CARGO TRANSPORT 5] </code> Then use like this: <code>SELECT h.* FROM Sales.SalesOrderHeader h JOIN ShipMethod.ShipMethodID const ON h.ShipMethodID = const.[OVERNIGHT J-FAST] </code> Or like this: <code>SELECT h.* FROM Sales.SalesOrderHeader h WHERE h.ShipMethodID = (SELECT TOP 1 [OVERNIGHT J-FAST] FROM ShipMethod.ShipMethodID) </code> </blockquote>
My workaround to missing constans is to give hints about the value to the optimizer. <code>DECLARE @Constant INT = 123; SELECT * FROM [some_relation] WHERE [some_attribute] = @Constant OPTION( OPTIMIZE FOR (@Constant = 123)) </code> This tells the query compiler to treat the variable as if it was a constant when creating the execution plan. The down side is that you have to define the value twice.
Intellij shortcut for quick call hierarchy <sep> Is there a shortcut key to bring up the call hierarchy of a method inline with the code, in the quick menu format, rather than bringing up the call hierarchy panel?
I don't think the inline method call hierarchy exists (please enlighten me if I am wrong). Ctrl + Alt + H shows the call hierarchy in the tool window Alt + F7 opens the dialog to find the usages Ctrl + F7 finds the usages in the same file
If you just want to jump to one of the callers of the method, CTRL + ALT + F7 is the way to go. On a Mac, use: Command + Option + F7 There is a 'Default Keymap Reference' on the 'Help' menu
What's the best online payment processing solution?
You can't really answer this kind of question with a "I like 'insert provide name here'" type answer because like so many things it is a balance and the reasons for choosing a payment processing solution tend to be complex. Volume / Value The most important factor in choosing a secure payment clearance service (the people who will connect to the banking networks and clear the money for you - will refer to them as SPCS) is how many widgets will you be selling at what cost. The pricing models of all the SCPS providers is based around this equation. This dictates the economics of using the service, which is nearly always the most important factor. For example, in the UK securetrading.net have a large annual fee and high minimum transaction values (been a while since I've seen the exact numbers and they don't make it immediately obvious on the site, but this is for illustration only anyway) making it one of the most expensive solutions to use if you are selling high value low volume. Most smaller clients will fall into this model. High value is really anything over a couple of dollars. Low volume is typically anything less than tens of thousands of units per month. However, if you are running a donations service in the aftermath of an international environmental disaster (relatively low value very high volume) then they become one of the cheapest. Factor in to this the setup costs (relatively high), and the cost to tie the service into the site (in SecureTrading's case it's very easy to do, but still a lot harder than adding a PayPal button) and you start to build up a true picture. On the flip side, a service such as PayPal has very low setup costs (no fee to pay, and trivially easy to integrate), but relatively high transaction costs. It is great for high value / low volume transactions. The Bank There are two main categories of payment clearance service - Bureau and Bank Acquired. In the UK at least NetBanx, SecureTrading and WorldPay offer both bank acquired and bureau services. ProtX and SecPay offer only bank acquired services. PayPal and its ilk operates slightly outside both definitions (see Protection below). A Bank Acquired service plumbs into your normal banking merchant account and clears the funds straight into it. As well as charging you for this service, your bank will also take a slice, typically this is more than the SPCS provider will charge and so it actually is the bank that becomes the deciding factor. Some banks will only work with their preferred provider. In the UK, most banks want you to have a separate Internet Merchant Account even if you already have a Merchant Account with them. I always tell clients to shop around, as this will make a huge difference to how much their e-commerce venture can bring in. All banks are not created equal. Bureau services effectively act as your bank at the same time as providing the clearance service. They were popular in a time when banks hadn't grasped the concept of the Internet and would prefer transactions be chiseled into stone tablets if they got their way. Often the choice between a bureau service and a bank acquired service is made for you based on circumstances. Trading History In many countries (including the UK), most banks won't give you a merchant account until you have been trading for a particular period of time (2 years in the UK). Your only option is then a bureau service. Cash flow Most bureau services will hold onto your cash as security against "charge backs". If you sell me a Ferrari and I am horrified to learn that you've sold me a small metal toy rather than the 1.5 tonnes of Italian automotive passion I was expecting, I will complain to my credit card company who will refund me and then chase your merchant services provider for a refund. They will have to give them the refund and then chase you for the money. It's therefore in their interests to hold on to your money for a period of 4-6 weeks to protect against this. If you sell services or goods with no capital outlay (software for instance), then you can afford this. If on the other hand, you really are having to pay your luxury car importer to provide you with stock, then cash flow becomes very important and you're going to need a bank acquired service where you can be paid immediately. Protection One major downside to PayPal and similar services is that it is not covered under the same regulations that govern credit cards. Simply put, if you buy something on a credit card your card provider is liable for ensure you get what you paid for (broadly speaking, in most countries, does not constitute legal advice etc.) and if you have a problem with your purchase they will refund you very quickly and then will go and chase the person that you paid. This is the kind of protection you hear about when Leo Laporte advertises American Express on his podcasts. It is a "Good Thing"TM. You don't have that protection with PayPal because when you use your credit card on PayPal, you are actually buying PayPal's service. So, even if you are mis-sold a product, the person you paid for the service (PayPal) didn't mis-sell, they provided the service you paid for. This breaks the chain. PayPal don't have a legal obligation to protect you in the same way, and their record on refunding ripped off customers is less than spangly. I'm guessing they have "Caveat Emptor" writ large on the walls of their head office. :) I'm not dissing PayPal, they are way ahead of the curve on many other security features, but just another factor to bear in mind. End to end integration Different services differ in their ease of integration. Oh boy do they differ. I'm sitting on some work right now to do an HSBC integration. I'd rather have a root canal. Some of the systems make big assumptions about the way you have to work with them, and are poorly designed or inflexible. Retro-fitting them to an active site can be very painful. Some of them are beautiful and easy to work with (and not necessarily less secure). The biggest difference is how you choose to integrate though. Most services integrate by allowing you to redirect to a secure site where your customer fills in his / her details. They are finally redirected back to a page on your own site with the results of the transaction. This works well in most cases and is easiest to integrate. When you buy something on Amazon, you don't get redirected to WorldPay, or PayPal however. If you want end-to-end integration, most services now will let the communication happen behind the scenes. Your own site has to have a decent secure server certificate of course, and the integration is necessarily more complex. Reputation It used to be that PayPal was used on dinky sites. You wouldn't catch Amazon using it. That perception has changed a lot, and in fact in some senses PayPal does security better than most. If your audience expects to see PayPal and you give them some other service then you may lose custom, or vice versa. These days many merchants offer a choice to customers. UK Providers WorldPay. Well established. Bureau and bank acquired. Relatively high transaction costs and annual costs. Fairly easy to integrate. Owned ultimately by Royal Bank of Scotland. SecPay. Bank Acquired. Low per transaction cost and low annual cost and flexible payment models. ProtX. Bank Acquired. Low per transaction cost and low annual cost, flexible payment models. Can be quite demanding to integrate. HSBC. Bank Acquired. Low per transaction cost. High set up and annual costs. Very inflexible to integrate. SecureTrading. Bureau and Bank Acquired. Low per transaction cost but high setup and annual costs. Was a doddle to integrate last time I used it (9 years ago!) NetBanx. Bureau and Bank Acquired. Haven't used since 1996 so can't comment! And of course PayPal, Google Checkout and Amazon FPS are well worth looking at and worth a whole answer on their own! Summary Told you it wasn't that simple! Usually, as developers, we're not in the position to choose for ourselves, and these decisions should be driven by the business needs of our employer / client. Most e-commerce projects would start with PayPal or similar. When the business gets enough orders that they could save money by switching to another service, then they've got enough money to pay for the switch. Disclaimer: I am UK based, and have performed many integrations with a whole slew of these services over the years, however the market changes all the time and things may have changed and your mileage may vary! I am not a lawyer or accountant, and if you take my advice it's not my fault :)
I'd say paypal or GoogleCheckout. Google Checkout is either 2% + .20USD or free depending on how much you spend on adwords. If you spend a dollar on adWords, your next $10 on Google checkout is free. Paypal is 1.9% to 2.9% + $0.30 USD (2.9% for up to $30,000/month, 1.9% for more than $100,000/month) Without factoring in the 20/30 cents, Paypal is just barely cheaper if you sell more than $100,000 per month, and spend nothing on adwords.
What is the easiest way to parse an INI File in C++?
If you are already using Qt <code>QSettings my_settings("filename.ini", QSettings::IniFormat); </code> Then read a value <code>my_settings.value("GroupName/ValueName", <<DEFAULT_VAL>>).toInt() </code> There are a bunch of other converter that convert your INI values into both standard types and Qt types. See Qt documentation on QSettings for more information.
I use SimpleIni. It's cross-platform.
Tool to visualise code flow (C/C++) <sep> Do you have any sugestions of tools to ease the task of understanding C/C++ code?
SourceInsight and Understand for C++ are the best tools you can get for c/c++ code analysis including flow charts.
Profiling software gives you an idea of which functions have been called. If you can use Linux, try KCachegrind
SSL pages under ASP.NET MVC <sep> How do I go about using HTTPS for some of the pages in my ASP.NET MVC based site?
If you are using ASP.NET MVC 2 Preview 2 or higher, you can now simply use: <code>[RequireHttps] public ActionResult Login() { return View(); } </code> Though, the order parameter is worth noting, as mentioned here.
MVCFutures has a 'RequireSSL' attribute. (thanks Adam for pointing that out in your updated blogpost) Just apply it to your action method, with 'Redirect=true' if you want an http:// request to automatically become https:// : <code> [RequireSsl(Redirect = true)] </code> See also: ASP.NET MVC RequireHttps in Production Only
How can I get the content of the file specified as the 'src' of a tag?
tl;dr script tags are not subject to CORS and same-origin-policy and therefore javascript/DOM cannot offer access to the text content of the resource loaded via a <code><script></code> tag, or it would break <code>same-origin-policy</code>. long version: Most of the other answers (and the accepted answer) indicate correctly that the "correct" way to get the text content of a javascript file inserted via a <code><script></code> loaded into the page, is using an XMLHttpRequest to perform another seperate additional request for the resource indicated in the scripts <code>src</code> property, something which the short javascript code below will demonstrate. I however found that the other answers did not address the point why to get the javascript files text content, which is that allowing to access content of the file included via the <code><script src=[url]></script></code> would break the <code>CORS</code> policies, e.g. modern browsers prevent the XHR of resources that do not provide the Access-Control-Allow-Origin header, hence browsers do not allow any other way than those subject to <code>CORS</code>, to get the content. With the following code (as mentioned in the other questions "use XHR/AJAX") it is possible to do another request for all not inline script tags in the document. <code>function printScriptTextContent(script) { var xhr = new XMLHttpRequest(); xhr.open("GET",script.src) xhr.onreadystatechange = function () { if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { console.log("the script text content is",xhr.responseText); } }; xhr.send(); } Array.prototype.slice.call(document.querySelectorAll("script[src]")).forEach(printScriptTextContent); </code> and so I will not repeat that, but instead would like to add via this answer upon the aspect why itthat
Update: HTML Imports are now deprecated (alternatives). --- I know it's a little late but some browsers support the tag LINK <code>rel="import"</code> property. http://www.html5rocks.com/en/tutorials/webcomponents/imports/ <code><link rel="import" href="/path/to/imports/stuff.html"> </code> For the rest, ajax is still the preferred way.
CSS to make an empty cell's border appear?
Another way of making sure there is data in all cells: <code> $(document).ready(function() { $("td:empty").html("&nbsp;"); }); </code>
If you set the <code>border-collapse</code> property to <code>collapse</code>, IE7 will show empty cells. It also collapses the borders though so this might not be 100% what you want <code>td { border: 1px solid red; } table { border-collapse: collapse; } <html> <head> <title>Border-collapse Test</title> <style type="text/css"> td { border: 1px solid red; } table { border-collapse: collapse; }</code> <code><table> <tr> <td></td> <td>test</td> <td>test</td> </tr> <tr> <td>test</td> <td></td> <td>test</td> </tr> <tr> <td>test</td> <td></td> <td>test</td> </tr> <tr> <td>test</td> <td></td> <td /> </tr> </table></code>
Is it possible to implement mixins in C#?
I usually employ this pattern: <code>public interface IColor { byte Red {get;} byte Green {get;} byte Blue {get;} } public static class ColorExtensions { public static byte Luminance(this IColor c) { return (byte)(c.Red*0.3 + c.Green*0.59+ c.Blue*0.11); } } </code> I have the two definitions in the same source file/namespace. That way the extensions are always available when the interface is used (with 'using'). This gives you a limited mixin as described in CMS' first link. Limitations: no data fields no properties (you'll have to call myColor.Luminance() with parentheses, extension properties anyone?) It's still sufficient for many situations. It would be nice if they (MS) could add some compiler magic to auto-generate the extension class: <code>public interface IColor { byte Red {get;} byte Green {get;} byte Blue {get;} // compiler generates anonymous extension class public static byte Luminance(this IColor c) { return (byte)(c.Red*0.3 + c.Green*0.59+ c.Blue*0.11); } } </code> Although Jon's proposed compiler trick would be even nicer.
There is an open source framework that enables you to implement mixins via C#. Have a look on http://remix.codeplex.com/. It is very easy to implement mixins with this framework. Just have a look on the samples and the "Additional Information" links given on the page.
What is the minimum client footprint required to connect C# to an Oracle database?
As of 2014, the OPD.NET, Managed Driver is the smallest footprint. Here is a code usage comparison to the non-managed versions that previous (outdated) answers suggested: http://docs.oracle.com/cd/E51173_01/win.122/e17732/intro005.htm#ODPNT148 You will need to download these dlls and reference <code>Oracle.ManagedDataAccess.dll</code> in your project: Download the ODP.NET, Managed Driver Xcopy version only Here is a typical foot print you will need to package with your release: <code>Oracle.ManagedDataAccess.dll</code> <code>Oracle.ManagedDataAccessDTC.dll</code> all together, a whopping 6.4 MB for .Net 4.0.
This way allows you to connect with ODP.net using 5 redistributable files from oracle: Chris's blog entry: Using the new ODP.Net to access Oracle from C# with simple deployment Edit: In case the blog every goes down, here is a brief summary... oci.dll Oracle.DataAccess.dll oraociicus11.dll OraOps11w.dll orannzsbb11.dll oraocci11.dll ociw32.dll <blockquote> make sure you get ALL those DLL's from the same ODP.Net / ODAC distribution to avoid version number conflicts, and put them all in the same folder as your EXE </blockquote>
PostgreSQL UNIX domain sockets vs TCP sockets <sep> I wonder if the UNIX domain socket connections with postgresql are faster then tcp connections from localhost in high concurrency rate and if it does, by how much?
Postgres core developer Bruce Momjian has blogged about this topic. Momjian states, "Unix-domain socket communication is measurably faster." He measured query network performance showing that the local domain socket was 33% faster than using the TCP/IP stack.
UNIX domain sockets should offer better performance than TCP sockets over loopback interface (less copying of data, fewer context switches), but I don't know whether the performance increase can be demonstrated with PostgreSQL. I found a small comparison on the FreeBSD mailinglist: http://lists.freebsd.org/pipermail/freebsd-performance/2005-February/001143.html.
What is the best rich textarea editor for jQuery?
I'm surprised nobody has mentioned markitup: markItUp! is a JavaScript plugin built on the jQuery library. It allows you to turn any textarea into a markup editor. Html, Textile, Wiki Syntax, Markdown, BBcode or even your own Markup system can be easily implemented.
For me markitup is an excellent editor. It does rich text as a markup editor and allows you to use different standards: html, wiki, UBB, etc... It also allows plugins very easily.
Self-signed SSL Cert or CA?
There's a common misconception that self-signed certificates are inherently less secure than those sold by commercial CA's like GoDaddy and Verisign, and that you have to live with browser warnings/exceptions if you use them; this is incorrect. If you securely distribute a self-signed certificate (or CA cert, as bobince suggested) and install it in the browsers that will use your site, it's just as secure as one that's purchased and is not vulnerable to man-in-the-middle attacks and cert forgery. Obviously this means that it's only feasible if only a few people need secure access to your site (e.g., internal apps, personal blogs, etc.). In the interest of increasing awareness and encouraging fellow small-time bloggers like myself to protect themselves, I've written up a entry-level tutorial that explains the concepts behind certificates and how to safely create and use your own self-signed cert (complete with code samples and screenshots) here.
The SSL certificate solves two purposes: encryption of traffic (for RSA key exchange, at least) and verification of trust. As you know, you can encrypt traffic with (or without, if we're talking SSL 3.0 or TLS) any self-signed certificate. But trust is accomplished through a chain of certificates. I don't know you, but I do trust verisign (or at least Microsoft does, because they've been paid lots of money to get it installed in their operating systems by default), and since Verisign trusts you, then I trust you too. As a result, there's no scary warning when I go to such an SSL page in my Web browser because somebody that I trust has said you are who you are. Generally, the more expensive the certificate, the more investigating that the issuing certificate authority does. So for the Extended Validation certificates, the requesters have to submit more documents to prove that they are who they say they are, and in return they get a bright, happy green bar in modern Web browsers (I think Safari doesn't do anything with it quite yet). Finally, some companies go with the big boys like Verisign purely for the brand name alone; they know that their customers have at least heard of Verisign and so that for people shopping on their online store, their seal looks a little less sketch-ball than, say, GoDaddy's. If the branding is not important to you or if your site is not prone to phishing attacks, then the cheapest SSL cert that you can buy that has its root installed in most Web browsers by default will be fine. Usually, the only verification done is that you must be able to reply to an e-mail sent to the DNS's administrative contact, thus "proving" that you "own" that domain name. You can use those cheap-o certificates on non-GoDaddy servers, sure, but you'll probably have to install an intermediate certificate on the server first. This is a certificate that sits between your cheap-o $30 certificate and the GoDaddy "real deal" root certificate. Web browsers visiting your site will be like "hmm, looks like this was signed with an intermediate, you got that?" which requires may require an extra trip. But then it'll request the intermediate from your server, see that it chains up to a trusted root certificate that it knows about, and there is no problem. But if you are not allowed to install the intermediate on your server (such as in a shared hosting scenario), then you are out of luck. This is why most people say that GoDaddy certs can't be used on non-GoDaddy servers. Not true, but true enough for many scenarios. (At work we use a Comodo certificate for our online store, and a cheapo $30 GoDaddy cert to secure the internal connection to the database.) Edited in italics to reflect erickson's insightful clarifications below. Learn something new every day!
MySQL Row Format: Difference between fixed and dynamic?
The difference really only matters for MyISAM, other storage engines do not care about the difference. EDIT : Many users commented that InnoDB does care: link 1 by steampowered, link 2 by Kaan. With MyISAM with fixed width rows, there are a few advantages: No row fragmentation: It is possible with variable width rows to get single rows split into multiple sections across the data file. This can increase disk seeks and slow down operations. It is possible to defrag it with OPTIMIZE TABLE, but this isn't always practical. Data file pointer size: In MyISAM, there is a concept of a data file pointer which is used when it needs to reference the data file. For example, this is used in indexes when they refer to where the row actually is present. With fixed width sizes, this pointer is based on the row offset in the file (ie. rows are 1, 2, 3 regardless of their size). With variable width, the pointer is based on the byte offset (ie. rows might be 1, 57, 163). The result is that with large tables, the pointer needs to be larger which then adds potentially a lot more overhead to the table. Easier to fix in the case of corruption. Since every row is the same size, if your MyISAM table gets corrupted it is much easier to repair, so you will only lose data that is actually corrupted. With variable width, in theory it is possible that the variable width pointers get messed up, which can result in hosing data in a bad way. Now the primary drawback of fixed width is that it wastes more space. For example, you need to use CHAR fields instead of VARCHAR fields, so you end up with extra space taken up. Normally, you won't have much choice in the format, since it is dictated based on the schema. However, it might be worth if you only have a few varchar's or a single blob/text to try to optimize towards this. For example, consider switching the only varchar into a char, or split the blob into it's own table. You can read even more about this at: http://dev.mysql.com/doc/refman/5.0/en/static-format.html http://dev.mysql.com/doc/refman/5.0/en/dynamic-format.html
One key difference occurs when you update a record. If the row format is fixed, there is no change in the length of the record. In contrast, if the row format is dynamic and the new data causes the record to increase in length, a link is used to point to the "overflow" data (i.e. it's called the overflow pointer). This fragments the table and generally slows things down. There is a command to defragment (OPTIMIZE TABLE), which somewhat mitigates the issue.
Using Selenium IDE with random values <sep> Is it possible to create Selenium tests using the Firefox plugin that use randomly generated values to help do regression tests?
(Based on Thilo answer) You can mix literals and random numbers like this: <code>javascript{"joe+" + Math.floor(Math.random()*11111) + "@gmail.com";} </code> Gmail makes possible that automatically everything that use aliases, for example, <code>joe+testing@gmail.com</code> will go to your address <code>joe@gmail.com</code> Multiplying *11111 to give you more random values than 1 to 9 (in Thilo example)
You can add user exentions.js to get the random values . Copy the below code and save it as .js extension (randomgenerator.js) and add it to the Selenium core extensions (SeleniumIDE-->Options--->general tab) <code>Selenium.prototype.doRandomString = function( options, varName ) { var length = 8; var type = 'alphanumeric'; var o = options.split( '|' ); for ( var i = 0 ; i < 2 ; i ++ ) { if ( o[i] && o[i].match( /^\d+$/ ) ) length = o[i]; if ( o[i] && o[i].match( /^(?:alpha)?(?:numeric)?$/ ) ) type = o[i]; } switch( type ) { case 'alpha' : storedVars[ varName ] = randomAlpha( length ); break; case 'numeric' : storedVars[ varName ] = randomNumeric( length ); break; case 'alphanumeric' : storedVars[ varName ] = randomAlphaNumeric( length ); break; default : storedVars[ varName ] = randomAlphaNumeric( length ); }; }; function randomNumeric ( length ) { return generateRandomString( length, '0123456789'.split( '' ) ); } function randomAlpha ( length ) { var alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split( '' ); return generateRandomString( length, alpha ); } function randomAlphaNumeric ( length ) { var alphanumeric = '01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split( '' ); return generateRandomString( length, alphanumeric ); } function generateRandomString( length, chars ) { var string = ''; for ( var i = 0 ; i < length ; i++ ) string += chars[ Math.floor( Math.random() * chars.length ) ]; return string; } </code> Way to use <code>Command Target Value ----------- --------- ---------- randomString 6 x type username ${x} </code> Above code generates 6 charactes string and it assign to the variable x Code in HTML format looks like below: <code><tr> <td>randomString</td> <td>6</td> <td>x</td> </tr> <tr> <td>type</td> <td>username</td> <td>${x}</td> </tr> </code>
Why aren't classes sealed by default?
In my opinion there should be no default syntax, that way you always write explicitly what you want. This forces the coder to understand/think more. If you want a class to be inheritable then you write <code>public extensible class MyClass </code> otherwise <code>public sealed class MyClass </code> BTW I think the same should go with access modifiers, disallow default access modifiers.
Inheritance is a foundational principle of OO, so arguably, disallowing it by default wouldn't be intuitive.
Python vs Groovy vs Ruby?
Having worked with all 3 of them, this is what I can say: Python has very mature libraries libraries are documented documentation can be accessed from your debugger/shell at runtime through the docstrings you can develop code without an IDE Ruby has some great libraries ( even though some are badly documented ) Ruby's instrospection mechanisms are great. They make writing code pretty easy ( even if documentation is not available ) you can develop code without an IDE Groovy you can benefit from everything Java has to offer syntax is somewhat inspired from Ruby it's hard to write code without an IDE. You have no way to debug stuff from your console ( this is something you can easily do in Python/Ruby ) and the available Groovy plugins have a lot of catching up to do. I wrote some apps using Groovy and as they get bigger I regret not going with Ruby/Python ( debugging would have been WAY more easier ). If you'll only develop from an IDE, Groovy's a cool language.
Just to muddy the waters... Groovy give you access to Java. Java has an extremely rich set of APIs/Libraries, applications, etc. Groovy is embeddable, although easiest in Java. DLLs/Libraries (if you're talking about non-Groovy/Java) may be somewhat problematic, although there are ways and some APIs to help. I've done some Python programming, but being more familiar with Java, Groovy comes a lot easier to me.
Is it possible to change the natural order of columns in Postgres?
You can actually just straight up change the column order, but I'd hardly recommend it, and you should be very careful if you decide to do it. eg. # CREATE TABLE test (a int, b int, c int); # INSERT INTO test VALUES (1,2,3); # SELECT * FROM test; a | b | c ---+---+--- 1 | 2 | 3 (1 row) Now for the tricky bit, you need to connect to your database using the postgres user so you can modify the system tables. # SELECT relname, relfilenode FROM pg_class WHERE relname='test'; relname | relfilenode ---------+------------- test_t | 27666 (1 row) # SELECT attrelid, attname, attnum FROM pg_attribute WHERE attrelid=27666; attrelid | attname | attnum ----------+----------+-------- 27666 | tableoid | -7 27666 | cmax | -6 27666 | xmax | -5 27666 | cmin | -4 27666 | xmin | -3 27666 | ctid | -1 27666 | b | 1 27666 | a | 2 27666 | c | 3 (9 rows) attnum is a unique column, so you need to use a temporary value when you're modifying the column numbers as such: # UPDATE pg_attribute SET attnum=4 WHERE attname='a' AND attrelid=27666; UPDATE 1 # UPDATE pg_attribute SET attnum=1 WHERE attname='b' AND attrelid=27666; UPDATE 1 # UPDATE pg_attribute SET attnum=2 WHERE attname='a' AND attrelid=27666; UPDATE 1 # SELECT * FROM test; b | a | c ---+---+--- 1 | 2 | 3 (1 row) Again, because this is playing around with database system tables, use extreme caution if you feel you really need to do this. This is working as of postgres 8.3, with prior versions, your milage may vary.
If your database is not very big and you can afford some downtime then you can: Disable write access to the database this is essential as otherwise any changes after starting the next point will be lost <code>pg_dump --create --column-inserts databasename > databasename.pgdump.sql</code> Edit apropriate <code>CREATE TABLE</code> statement in databasename.pgdump.sql If the file is too big for your editor just split it using <code>split</code> command, edit, then assemble back using <code>cat</code> <code>drop database databasename</code> You do have a recent backup, just in case, do you? <code>psql --single-transaction -f databasename.pgdump.sql</code> If you don't use <code>--single-transaction</code> it will be very slow If you use so called large objects make sure they are included in the dump. I'm not sure if they are by default in 8.1.
How do you create a PDF from XML in Java?
A - Explanation You should use Apache FOP framework to generate pdf output. Simply you provide data in xml format and render the page with an xsl-fo file and specify the parameters like margin, page layout in this xsl-fo file. I'll provide a simple demo, I use maven build tool to gather the needed jar files. Please notify that at the end of the page, there is an svg graphics embedded in pdf. I also want to demonstrate that you can embed svg graphics inside pdf. B - Sample XML input data <code><?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="application/xml"?> <users-data> <header-section> <data-type id="019">User Bill Data</data-type> <process-date>Thursday December 9 2016 00:04:29</process-date> </header-section> <user-bill-data> <full-name>John Doe</full-name> <postal-code>34239</postal-code> <national-id>123AD329248</national-id> <price>17.84</price> </user-bill-data> <user-bill-data> <full-name>Michael Doe</full-name> <postal-code>54823</postal-code> <national-id>942KFDSCW322</national-id> <price>34.50</price> </user-bill-data> <user-bill-data> <full-name>Jane Brown</full-name> <postal-code>66742</postal-code> <national-id>ABDD324KKD8</national-id> <price>69.36</price> </user-bill-data> </users-data> </code> C - The XSL-FO Template <code><?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" version="1.0"> <xsl:output encoding="UTF-8" indent="yes" method="xml" standalone="no" omit-xml-declaration="no"/> <xsl:template match="users-data"> <fo:root language="EN"> <fo:layout-master-set> <fo:simple-page-master master-name="A4-portrail" page-height="297mm" page-width="210mm" margin-top="5mm" margin-bottom="5mm" margin-left="5mm" margin-right="5mm"> <fo:region-body margin-top="25mm" margin-bottom="20mm"/> <fo:region-before region-name="xsl-region-before" extent="25mm" display-align="before" precedence="true"/> </fo:simple-page-master> </fo:layout-master-set> <fo:page-sequence master-reference="A4-portrail"> <fo:static-content flow-name="xsl-region-before"> <fo:table table-layout="fixed" width="100%" font-size="10pt" border-color="black" border-width="0.4mm" border-style="solid"> <fo:table-column column-width="proportional-column-width(20)"/> <fo:table-column column-width="proportional-column-width(45)"/> <fo:table-column column-width="proportional-column-width(20)"/> <fo:table-body> <fo:table-row> <fo:table-cell text-align="left" display-align="center" padding-left="2mm"> <fo:block> Bill Id:<xsl:value-of select="header-section/data-type/@id"/> , Date: <xsl:value-of select="header-section/process-date"/> </fo:block> </fo:table-cell> <fo:table-cell text-align="center" display-align="center"> <fo:block font-size="150%"> <fo:basic-link external-destination="http://www.example.com">XXX COMPANY</fo:basic-link> </fo:block> <fo:block space-before="3mm"/> </fo:table-cell> <fo:table-cell text-align="right" display-align="center" padding-right="2mm"> <fo:block> <xsl:value-of select="data-type"/> </fo:block> <fo:block display-align="before" space-before="6mm">Page <fo:page-number/> of <fo:page-number-citation ref-id="end-of-document"/> </fo:block> </fo:table-cell> </fo:table-row> </fo:table-body> </fo:table> </fo:static-content> <fo:flow flow-name="xsl-region-body" border-collapse="collapse" reference-orientation="0"> <fo:block>MONTHLY BILL REPORT</fo:block> <fo:table table-layout="fixed" width="100%" font-size="10pt" border-color="black" border-width="0.35mm" border-style="solid" text-align="center" display-align="center" space-after="5mm"> <fo:table-column column-width="proportional-column-width(20)"/> <fo:table-column column-width="proportional-column-width(30)"/> <fo:table-column column-width="proportional-column-width(25)"/> <fo:table-column column-width="proportional-column-width(50)"/> <fo:table-body font-size="95%"> <fo:table-row height="8mm"> <fo:table-cell> <fo:block>Full Name</fo:block> </fo:table-cell> <fo:table-cell> <fo:block>Postal Code</fo:block> </fo:table-cell> <fo:table-cell> <fo:block>National ID</fo:block> </fo:table-cell> <fo:table-cell> <fo:block>Payment</fo:block> </fo:table-cell> </fo:table-row> <xsl:for-each select="user-bill-data"> <fo:table-row> <fo:table-cell> <fo:block> <xsl:value-of select="full-name"/> </fo:block> </fo:table-cell> <fo:table-cell> <fo:block> <xsl:value-of select="postal-code"/> </fo:block> </fo:table-cell> <fo:table-cell> <fo:block> <xsl:value-of select="national-id"/> </fo:block> </fo:table-cell> <fo:table-cell> <fo:block> <xsl:value-of select="price"/> </fo:block> </fo:table-cell> </fo:table-row> </xsl:for-each> </fo:table-body> </fo:table> <fo:block id="end-of-document"> <fo:instream-foreign-object> <svg width="200mm" height="150mm" version="1.1" xmlns="http://www.w3.org/2000/svg"> <path d="M153 334 C153 334 151 334 151 334 C151 339 153 344 156 344 C164 344 171 339 171 334 C171 322 164 314 156 314 C142 314 131 322 131 334 C131 350 142 364 156 364 C175 364 191 350 191 334 C191 311 175 294 156 294 C131 294 111 311 111 334 C111 361 131 384 156 384 C186 384 211 361 211 334 C211 300 186 274 156 274" style="fill:yellow;stroke:red;stroke-width:2"/> </svg> </fo:instream-foreign-object> </fo:block> </fo:flow> </fo:page-sequence> </fo:root> </xsl:template> </xsl:stylesheet> </code> D - Project Directory Structure E - Pom file <code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.levent.fopdemo</groupId> <artifactId>apache-fop-demo</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>apache-fop-demo</name> <url>http://maven.apache.org</url> <properties> <fop.version>2.1</fop.version> </properties> <dependencies> <!-- https://mvnrepository.com/artifact/org.apache.xmlgraphics/fop --> <dependency> <groupId>org.apache.xmlgraphics</groupId> <artifactId>fop</artifactId> <version>${fop.version}</version> </dependency> </dependencies> <build> <finalName>Apache Fop Demo</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project> </code> F - Demo Code: PdfGenerationDemo.java <code>package com.levent.fopdemo; import java.io.File; import java.io.IOException; import java.io.OutputStream; import javax.xml.transform.Result; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.stream.StreamSource; import org.apache.fop.apps.FOPException; import org.apache.fop.apps.FOUserAgent; import org.apache.fop.apps.Fop; import org.apache.fop.apps.FopFactory; import org.apache.fop.apps.MimeConstants; public class PdfGenerationDemo { public static final String RESOURCES_DIR; public static final String OUTPUT_DIR; static { RESOURCES_DIR = "src//main//resources//"; OUTPUT_DIR = "src//main//resources//output//"; } public static void main( String[] args ) { try { convertToPDF(); } catch (FOPException | IOException | TransformerException e) { e.printStackTrace(); } } public static void convertToPDF() throws IOException, FOPException, TransformerException { // the XSL FO file File xsltFile = new File(RESOURCES_DIR + "//template.xsl"); // the XML file which provides the input StreamSource xmlSource = new StreamSource(new File(RESOURCES_DIR + "//data.xml")); // create an instance of fop factory FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI()); // a user agent is needed for transformation FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); // Setup output OutputStream out; out = new java.io.FileOutputStream(OUTPUT_DIR + "//output.pdf"); try { // Construct fop with desired output format Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); // Setup XSLT TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource(xsltFile)); // Resulting SAX events (the generated FO) must be piped through to // FOP Result res = new SAXResult(fop.getDefaultHandler()); // Start XSLT transformation and FOP processing // That's where the XML is first transformed to XSL-FO and then // PDF is created transformer.transform(xmlSource, res); } finally { out.close(); } } } </code> G - Sample Output: output.pdf
You can use XSL Formatting objects. Here are some good articles on how to do it: http://www.xml.com/pub/a/2001/01/17/xsl-fo/index.html http://www.xml.com/pub/a/2001/01/24/xsl-fo/index.html?page=1 http://www.javaworld.com/javaworld/jw-04-2006/jw-0410-html.html
Regexp that matches valid regexps <sep> Is there a regular expression that matches valid regular expressions?
<blockquote> Is there a regular expression that matches valid regular expressions? </blockquote> By definion, it's quite simple: No. The language of all regexes is no regular language (just look at nested parentheses) and therefore there can't be a regular expression to parse it.
If you merely want to check whether a regular expression is valid or not, simply try to compile it with whichever programming language or regular expression library you're working with. Parsing regular expressions is far from trivial. As the author of RegexBuddy, I have been around that block a few times. If you really want to do it, use a regex to tokenize the input, and leave the parsing logic to procedural code. That is, your regex would match one regex token (<code>^</code>, <code>$</code>, <code>\w</code>, <code>(</code>, <code>)</code>, etc.) at a time, and your procedural code would check if they're in the right order.
Best C++ IDE for *nix <sep> What is the best C++ IDE for a *nix envirnoment?
On Ubuntu, some the IDEs that are available in the repositories are: Kdevelop Geany Anjuta There is also: Eclipse (Recommended you don't install from repositories, due to issues with file/folder permissions) Code::blocks And of course, everyone's favourite text-based editors: vi/vim emacs Its true that vim and emacs are very powerful tools, but the learning curve is very steep.. I really don't like Eclipse that much, I find it buggy and a bit too clunky. I've started using Geany as a bare-bones but functional and usable IDE. It has a basic code-completion feature, and is a nice, clean [Gnome] interface. Anjuta I tried for a day, didn't like it at all. I didn't find it as useful as Geany. Kdevelop and code::blocks get a bunch of good reviews, but I haven't tried them. I use gnome, and I'm yet to see a KDE app that looks good in gnome (sorry, I'm sure its a great program). If only bloodshed dev-c++ was released under linux. That is a fantastic (but windows-only) program. You could always run it under Wine ;) To a degree, it comes down to personal preference. My advice is to investigate Kdevelop, Geany and code::blocks as a starting point.
As a programmer who has been writing code under linux for many years, I simply cannot seem to move away from using Vim for writing code. Once you learn it, and learn some of its more advanced features (Code Folding, how to use ctags, how to work with multiple buffers effectively, etc) moving to another editor is very hard - as everything else seems to be missing features that you're used to. The only other editor with a superset of vim's features is emacs. I highly recommend learning one or the other - and if you have questions, don't hesitate to ask here or in #emacs or #vim on irc.freenode.net - there's a very large and helpful community that will help you learn what extensions or commands best suit the software editing problems that you're facing. [Edit: A comment noted that "vim isn't an IDE", I agree. I don't like the IDE moniker because it means a gui with a project manager and a bunch of drop down boxes. I like to use the terminology "Good Tools". See Ted Leung's writings on the matter]
What's the best free IDE for learning smalltalk?
You should also consider Pharo. Pharo is a fork of Squeak. Their goals are: a clean and lean open-source Smalltalk platform, derived from Squeak the obvious choice for professional Smalltalk development an emerging platform to help people invent the future Whether it is Squeak or Pharo, there is a large, active and supportive community.
I think Squeak is the way to go. It has an entire smalltalk environment and is constantly updated. Its what I used for learning and is actually even a cool app in itself.
How to line up HTML input elements?
I tested this out in Internet Explorer 7, Firefox 3 and Safari/Google Chrome. I definitely see the problem with <code><select></code> and <code><input type="file"></code>. My findings showed that if you styled all the inputs at the same width, the <code><select></code> would be about 5 pixels shorter in all browsers. Using the Eric Meyer CSS reset script does not help this issue, however if you simply make your <code><select></code> inputs 5 pixels wider you'll get very good (albeit not perfect) alignment in the major browsers. The only one that differs is Safari/Google Chrome, and it appears to be 1 or 2 pixels wider than all the other browsers. As far as the <code><input type="file"></code> is concerned, you don't have much flexibility with styling there. If JavaScript is an option for you, you can implement the method shown on quirksmode to achieve greater control over the styling of the file upload control. See my full working example below in XHTML 1.0 Strict for a typical form with consistent input widths. Note that this does not use the 100% width trick pointed out by others here because it has the same problem with inconsistent widths. Additionally there are no tables used to render the form as tables should only be used for tabular data and not layout. <code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Example Form</title> <style type="text/css"> label, input, select, textarea { display: block; width: 200px; float: left; margin-bottom: 1em; } select { width: 205px; } label { text-align: right; width: 100px; padding-right: 2em; } .clear { clear: both; } </style> </head> <body> <form action="#"> <fieldset> <legend>User Profile</legend> <label for="fname">First Name</label> <input id="fname" name="fname" type="text" /> <br class="clear" /> <label for="lname">Last Name</label> <input id="lname" name="lname" type="text" /> <br class="clear" /> <label for="fav_lang">Favorite Language</label> <select id="fav_lang" name="fav_lang"> <option value="c#">C#</option> <option value="java">Java</option> <option value="ruby">Ruby</option> <option value="python">Python</option> <option value="perl">Perl</option> </select> <br class="clear" /> <label for="bio">Biography</label> <textarea id="bio" name="bio" cols="14" rows="4"></textarea> <br class="clear" /> </fieldset> </form> </body> </html></code>
I usually put them inside a div or table cell (horrors! I know) of the width I want, then set the select and input style:width to 100% so they fill the div / cell they are in.
When should I write Static Methods?
Static methods are usually useful for operations that don't require any data from an instance of the class (from <code>this</code>) and can perform their intended purpose solely using their arguments. A simple example of this would be a method <code>Point::distance(Point a, Point b);</code> that calculates the distance between two points and don't require an instance. Static fields are useful among others for constants that don't change all that often and are used by all the instances of a class.
It gives a better idea of the intent when you use a static factory -- it also lets you have different factories that take the same argument types but have a different meaning. For example, imagine if Bitmap had LoadFromResource(string) -- it would not be possible to have two constructors that both took string. EDIT: From stevemegson in the comments <blockquote> A static factory can also return null, and can more easily return an instance that it got from cache. Many of my classes have a static FromId(int) to get an instance from a primary key, returning an existing cached instance if we have one. </blockquote>
Which variables should I typecast when doing math operations in C/C++?
Question 1: Float division <code>int a = 2, b = 3; float c = static_cast<float>(a) / b; // need to convert 1 operand to a float </code> Question 2: How the compiler works Five rules of thumb to remember: Arithmetic operations are always performed on values of the same type. The result type is the same as the operands (after promotion) The smallest type arithmetic operations are performed on is int. ANSCI C (and thus C++) use value preserving integer promotion. Each operation is done in isolation. The ANSI C rules are as follows: Most of these rules also apply to C++ though not all types are officially supported (yet). If either operand is a long double the other is converted to a long double. If either operand is a double the other is converted to a double. If either operand is a float the other is converted to a float. If either operand is a unsigned long long the other is converted to unsigned long long. If either operand is a long long the other is converted to long long. If either operand is a unsigned long the other is converted to unsigned long. If either operand is a long the other is converted to long. If either operand is a unsigned int the other is converted to unsigned int. Otherwise both operands are converted to int. Overflow Overflow is always a problem. Note. The type of the result is the same as the input operands so all the operations can overflow, so yes you do need to worry about it (though the language does not provide any explicit way to catch this happening. As a side note: Unsigned division can not overflow but signed division can. <code>std::numeric_limits<int>::max() / -1 // No Overflow std::numeric_limits<int>::min() / -1 // Will Overflow </code>
In general, if operands are of different types, the compiler will promote all to the largest or most precise type: If one number is... And the other is... The compiler will promote to... ------------------- ------------------- ------------------------------- char int int signed unsigned unsigned char or int float float float double double Examples: char + int ==> int signed int + unsigned char ==> unsigned int float + int ==> float Beware, though, that promotion occurs only as required for each intermediate calculation, so: 4.0 + 5/3 = 4.0 + 1 = 5.0 This is because the integer division is performed first, then the result is promoted to float for the addition.
Logging to a file on the iPhone <sep> What would be the best way to write log statements to a file or database in an iPhone application?
This code works great for me.. <code>#if TARGET_IPHONE_SIMULATOR == 0 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *logPath = [documentsDirectory stringByAppendingPathComponent:@"console.log"]; freopen([logPath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr); #endif </code> You can then get the log file off the iphone using the method outlined here http://blog.coriolis.ch/2009/01/09/redirect-nslog-to-a-file-on-the-iphone/#more-85 Note that using freopen will STOP THE CONSOLE IN XCODE working.. however, for some reason the console you can view in xcode's organiser still works great.
This code works for me: <code>- (void)applicationDidFinishLaunching:(UIApplication *)application { #if TARGET_IPHONE_SIMULATOR == 0 freopen([@"/tmp/my_logs.txt" fileSystemRepresentation], "w", stderr); #endif } </code>
How to disable all apache virtual hosts?
You can just do the following: <code>sudo a2dissite '*' </code> or: <code>sudo a2dissite </code> and it will prompt you for the ones you want to disable. When you have finished disabling sites, restart apache2 server: <code>sudo systemctl restart apache2 </code> or just reload apache configuration without a full restart: <code>sudo service apache2 reload </code>
After a little more research, I found out that <code>a2dissite</code> is just a shell script, and it basically just calls <code>rm</code>. So, like other responses, I agree that it is safe to do <code>rm /etc/apache2/sites-enabled/* </code>
What is the best online javascript/css/html/xhtml/dom reference?
I like Mozilla's references: http://developer.mozilla.org/en/JavaScript http://developer.mozilla.org/en/DOM These are not at all the one stop site you want, but they help me.
I like gotapi.com (Update 2: Site is apparently offline -- Use another resource such as MDN) Update: the original answer was from 2008 -- today I would say to check out Mozilla Developer Network (as many others have also said).
Any way to do Visual Studio "project only" build from command line?
Depending on the structure of your build system, this may be what you're looking for: <code>msbuild /p:BuildProjectReferences=false project.proj </code>
MSBuild is what you want <code>MSBuild.exe MyProject.proj /t:build </code>
Rationale behind return 0 as default value in C/C++ <sep> Is there a reason why zero is used as a "default" function return value?
The rationale is that you want to distinguish the set of all the possible (negative) return values corresponding to different errors from the only situation in which all went OK. The simplest, most concise and most C-ish way to pursue such distinction is a logical test, and since in C all integers are "true" except for zero, you want to return zero to mean "the only situation", i.e. you want zero as the "good" value. The same line of reasoning applies to the return values of Unix programs, but indeed in the tests within Unix shell scripts the logic is inverted: a return value of 0 means "true" (for example, look at the return value of /bin/true).
Originally, C did not have "void". If a function didn't return anything, you just left the return type in the declaration blank. But that meant, that it returned an int. So, everything returned something, even if it didn't mean anything. And, if you didn't specifically provide a return value, whatever value happened to be in the register the compiler used to return values became the function's return value. <code>// Perfectly good K&R C code. NoReturn() { // do stuff; return; } int unknownValue = NoReturn(); </code> People took to clearing that to zero to avoid problems.
Relative path reference in WebConfig.ConnectionString <sep> Is it possible to specify a relative path reference in connectionstring, attachDbFileName property in a web.config?
I had the same problem with the following scenario: I wanted to use the same database as the application from my integration tests. I went with the following workaround: In the App.config of my test-project I have: <code><appSettings> <add key="DataDirectory" value="..\..\..\BookShop\App_Data\"/> </appSettings> </code> In the test-setup I execute the following code: <code> var dataDirectory = ConfigurationManager.AppSettings["DataDirectory"]; var absoluteDataDirectory = Path.GetFullPath(dataDirectory); AppDomain.CurrentDomain.SetData("DataDirectory", absoluteDataDirectory); </code>
It depends on where your '|DataDirectory|' is located. If the resolved value of '|DataDirectory|' is in folder A (where the web.config is), then no - you can't specify a relative path that is not a subfolder of the resolved value of '|DataDirectory|'. What you can do is set the value of '|DataDirectory|' to be wherever you would like, by calling the AppDomain.SetData method. From the MSDN online documentation: <blockquote> When DataDirectory is used, the resulting file path cannot be higher in the directory structure than the directory pointed to by the substitution string. For example, if the fully expanded DataDirectory is C:\AppDirectory\app_data, then the sample connection string shown above works because it is below c:\AppDirectory. However, attempting to specify DataDirectory as |DataDirectory|..\data will result in an error because \data is not a subdirectory of \AppDirectory. </blockquote> Hope this helps.
How can I get an OpenFileDialog in a custom control's property grid?
You can use built-in UITypeEditor. It is called FileNameEditor <code>[EditorAttribute(typeof(System.Windows.Forms.Design.FileNameEditor), typeof(System.Drawing.Design.UITypeEditor))] public string SomeFilePath { get; set; } </code>
You can do this by adding a UITypeEditor. Here is an example of a UITypeEditor that gives you the OpenFileDialog for chossing a filename.
Convert an image to XAML?
Inkscape can trace bitmaps, and can save directly to XAML. And, it happens to be free. I've used it to trace a lot of bitmaps and it's worked really well for me.
Illustrator has a trace tool which will do this a cheaper option might be http://vectormagic.com it will export a svg that you should be able to convert to xaml
How do I call a web service from javascript <sep> Say I have a web service http://www.example.com/webservice.pl?q=google which returns text "google.com".
EDIT: It has been a decade since I answered this question and we now have support for cross-domain XHR in the form of CORS. For any modern app consider using fetch to make your requests. If you need support for older browsers you can add a polyfill. Original answer: Keep in mind that you cannot make requests across domains. For example, if your page is on yourexample.com and the web service is on myexample.com you cannot make a request to it directly. If you do need to make a request like this then you will need to set up a proxy on your server. You would make a request to that proxy page, and it will retrieve the data from the web service and return it to your page.
Take a look at one of the many javascript libraries out there. I'd recommend jQuery, personally. Aside from all the fancy UI stuff they can do, it has really good cross-browser AJAX libraries. <code>$.get( "http://xyz.com/webservice.pl", { q : "google" }, function(data) { alert(data); // "google.com" } ); </code>
How to get additional lines of context in a CloudWatch Insights query?
You can actually query the <code>@logStream</code> as well, which in the results will be a link to the exact spot in the respective log stream of the match: <code>fields @timestamp, @message, @logStream | filter @message like /ERROR/ | sort @timestamp desc | limit 20 </code> That will give you a column similar to the right-most one in this screenshot: Clicking the link to the right will take you to and highlight the matching log line. I like to open this in a new tab and look around the highlighted line for context.
I found that the most useful solution is to do your query and search for errors and get the request id from the "requestId" field and open up a second browser tab. In the second tab perform a search on that request id. Example: <code>fields @timestamp, @message | filter @requestId like /fcd09029-0e22-4f57-826e-a64ccb385330/ | sort @timestamp asc | limit 500 </code> With the above query you get all the log messages in the correct order for the request where the error occurred. This is an example that works out of the box with lambda. But if you push logs to CloudWatch in a different way and there is no requestId i would suggest creating a requestId per request or another identifier that is more useful for you use case and push that with your log event.
Property 'focus' does not exist on 'Element'?
I had the same problem and I solved it by defining the type of the element I was expecting from <code>queryselector</code>. In my case I was expecting an <code>input</code> element, so I did: <code>document.querySelector<HTMLInputElement>(`input[name=${element-name}]`)?.focus() </code>
You need to convince TS that <code>currentActive.previousElementSibling</code> is of type <code>HTMLElement</code>. As a bonus tip I would recommend to convince yourself as well avoiding some red crosses in your console. Maybe something along the lines of <code>currentActive?.previousElementSibling?.focus?.();</code>
Does Material UI have an Image component?
Another option (at least in v5) is to use the Box component and select the underlying html element to be img as given in the example below (copied from official docs for v5) <code> <Box component="img" sx={{ height: 233, width: 350, maxHeight: { xs: 233, md: 167 }, maxWidth: { xs: 350, md: 250 }, }} alt="The house from the offer." src="https://images.unsplash.com/photo-1512917774080-9991f1c4c750?auto=format&w=350&dpr=2" /> </code>
There is no such specific custom img component avaiable with material-ui. But you can use the simple html img component inside another wrapper components to create custom img component by your own. e.g <code><Paper variant="outlined"> <img src="url" /> </Paper> </code> Also <code><CardMedia/></code> component has to be used with in conjunction with <code><Card/></code> component. Another such component which uses image is <code><Avatar></code> component. <code><Avatar alt="Example Alt" src="/static/images/avatar.jpg" /> </code>
How to reset input field from useRef in React?
<code>reset</code> is available on <code>form</code> element. You can wrap your input with a form, and trigger <code>reset</code> on it. <code>const {useRef} = React; const App = () => { const formRef = useRef(); const handleClick = () => { formRef.current.reset(); }; return ( <form ref={formRef}> <input type="text" /> <input type="password" /> <input type="checkbox" /> <textarea></textarea> <button onClick={handleClick} type="button"> clear form </button> </form> ); }; ReactDOM.render(<App />, document.getElementById('root'));</code> <code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.2/umd/react-dom.production.min.js"></script> <div id="root"></div></code>
You can clear the value in the input field like below. <code>const handleClick= () => { inputRef.current.value = ""; return "hello world" } </code> and change <code>onClick</code> call in the button like below <code>onClick={handleClick} //or onClick={()=> handleClick()} </code> If you want complete reset of a form having multiple inputs, you can follow the below approach. In below example, form will reset after submit <code> const formRef = useRef(); const handleClick = () => { formRef.current.reset(); } render() { return ( <form ref={formRef}> <input /> <input /> ... <input /> </form> ); } </code> if you don't want to use Ref <code>const handleSubmit = e => { e.preventDefault(); e.target.reset(); } <form onSubmit={handleSubmit}> ... </form> </code>