prompt
stringlengths
48
2.37k
chosen
stringlengths
7
4.28k
rejected
stringlengths
11
4.44k
Question: I have a dictionary of variablenames and I want those to be the variablenames in another script. So I probably need to identify all variables in a Python script and then somehow replace those with the desired ones from the dictionary. Yet I cannot figure out what might be the most elegant way to do that. Do I have to paste the one script as a string to the other script that does the replacement? Any tips? Thanks Edit: The actual question is not to request a complete solution rather than asking whether there is a possibility to identify which word in a script is actually a variable. Is it possible to find these eg compare them to PythonBuiltIn variables?! Answer:
Afaik no, signed pdfs can't be merged, cause the signature is applied to the document, not to its range. Changing the document invalidates the signature.
If you are not concerned about invalidating the signature you can always print to Adobe PDF again and then combine with other PDFs.
Question: I have a C# code that is using an external library which can throw exceptions. In three parts of my code, I want to process these exceptions the following way: ``` try { CallOtherLibrary(); } catch(ExceptionA) { ProcessErrorA(); } catch(ExceptionB) { ProcessErrorB(); } ``` Now I think that copy pasting this code is a code smell. One possible way to fix it to create a method that takes an action as argument, and does the try/catch. But it forces me to duplicate each method that is calling the try/catch, which leads to more code, less readable somehow. What is the clean way to handle this problem, given that I cannot change the behavior of my external library ? Answer:
You can make a `Dictionary<Type, Action> exceptionHandlers` and then call `exceptionHandlers[exception.GetType()]()` in the catch block. ``` void ProcessErrorA() { } void Main() { Dictionary<Type, Action> exceptionHandlers = new Dictionary<Type, Action>(); exceptionHandlers.Add(typeof(NullReferenceException), ProcessErrorA); try{} catch (Exception e) { if (exceptionHandlers.ContainsKey(e.GetType())) { exceptionHandlers[e.GetType()](); } else { // We don't have any handler for this exception. } } } ```
Maybe you could do something like this (adapt for own use): ``` class Program { public int Divide_InExternalLib(int a, int b) { Console.WriteLine(string.Format("a={0}, b={1}", a, b)); int result = a / b; Console.WriteLine(string.Format("Result = {0}", result)); return result; } public void CallExternalFunction(Action funct) { try { funct.Invoke(); } catch (Exception ex) { Console.WriteLine(string.Format("Exception caught: {0}", ex.ToString())); } } static void Main(string[] args) { var p = new Program(); int a = 6; int b = 2; p.CallExternalFunction(() => { p.Divide_InExternalLib(a, b); }); b = 0; p.CallExternalFunction(() => { p.Divide_InExternalLib(a, b); }); Console.ReadLine(); } } ``` Output ``` a=6, b=2 Result = 3 a=6, b=0 Exception caught: System.DivideByZeroException: Attempted to divide by zero. at GenericExceptionHandling.Program.Divide_InExternalLib(Int32 a, Int32 b) in c:\users\siebiers\documents\visual studio 2015\Projects\GenericExceptionHandlin g\GenericExceptionHandling\Program.cs:line 16 at GenericExceptionHandling.Program.<>c__DisplayClass2_0.<Main>b__1() in c:\u sers\siebiers\documents\visual studio 2015\Projects\GenericExceptionHandling\Gen ericExceptionHandling\Program.cs:line 41 at GenericExceptionHandling.Program.CallExternalFunction(Action funct) in c:\ users\siebiers\documents\visual studio 2015\Projects\GenericExceptionHandling\Ge nericExceptionHandling\Program.cs:line 26 ```
Question: I have a C# code that is using an external library which can throw exceptions. In three parts of my code, I want to process these exceptions the following way: ``` try { CallOtherLibrary(); } catch(ExceptionA) { ProcessErrorA(); } catch(ExceptionB) { ProcessErrorB(); } ``` Now I think that copy pasting this code is a code smell. One possible way to fix it to create a method that takes an action as argument, and does the try/catch. But it forces me to duplicate each method that is calling the try/catch, which leads to more code, less readable somehow. What is the clean way to handle this problem, given that I cannot change the behavior of my external library ? Answer:
You can make a `Dictionary<Type, Action> exceptionHandlers` and then call `exceptionHandlers[exception.GetType()]()` in the catch block. ``` void ProcessErrorA() { } void Main() { Dictionary<Type, Action> exceptionHandlers = new Dictionary<Type, Action>(); exceptionHandlers.Add(typeof(NullReferenceException), ProcessErrorA); try{} catch (Exception e) { if (exceptionHandlers.ContainsKey(e.GetType())) { exceptionHandlers[e.GetType()](); } else { // We don't have any handler for this exception. } } } ```
Provide a common exception handler function ``` static void Main(string[] args) { try { CallOtherLibrary(); } catch (Exception ex) { HandleException(ex); } } private static void HandleException(Exception ex) { if (ex is ExceptionA) { ProcessErrorA(); } else if (ex is ExceptionB) { ProcessErrorB(); } } ```
Question: I have a C# code that is using an external library which can throw exceptions. In three parts of my code, I want to process these exceptions the following way: ``` try { CallOtherLibrary(); } catch(ExceptionA) { ProcessErrorA(); } catch(ExceptionB) { ProcessErrorB(); } ``` Now I think that copy pasting this code is a code smell. One possible way to fix it to create a method that takes an action as argument, and does the try/catch. But it forces me to duplicate each method that is calling the try/catch, which leads to more code, less readable somehow. What is the clean way to handle this problem, given that I cannot change the behavior of my external library ? Answer:
You are looking for a wrapper of the alien library. In C# this is commonly done by using an `interface` with a method acting as an [Facade](https://en.wikipedia.org/wiki/Facade_pattern)/[Adapter](https://en.wikipedia.org/wiki/Adapter_pattern). You create a new class acting as an adaptee, implementing the adapter interface and in the implemented method you will have the code you mentioned in the question. You then replace the original code with call to the method of your newly created adapter and use that one in your codebase instead. The good thing about having an adapter for a library you don't own and using this adapter is not have to rewrite your own logic should the method signature of said external library change in the future, but merely change it in the adapting layer and you're all set again.
Maybe you could do something like this (adapt for own use): ``` class Program { public int Divide_InExternalLib(int a, int b) { Console.WriteLine(string.Format("a={0}, b={1}", a, b)); int result = a / b; Console.WriteLine(string.Format("Result = {0}", result)); return result; } public void CallExternalFunction(Action funct) { try { funct.Invoke(); } catch (Exception ex) { Console.WriteLine(string.Format("Exception caught: {0}", ex.ToString())); } } static void Main(string[] args) { var p = new Program(); int a = 6; int b = 2; p.CallExternalFunction(() => { p.Divide_InExternalLib(a, b); }); b = 0; p.CallExternalFunction(() => { p.Divide_InExternalLib(a, b); }); Console.ReadLine(); } } ``` Output ``` a=6, b=2 Result = 3 a=6, b=0 Exception caught: System.DivideByZeroException: Attempted to divide by zero. at GenericExceptionHandling.Program.Divide_InExternalLib(Int32 a, Int32 b) in c:\users\siebiers\documents\visual studio 2015\Projects\GenericExceptionHandlin g\GenericExceptionHandling\Program.cs:line 16 at GenericExceptionHandling.Program.<>c__DisplayClass2_0.<Main>b__1() in c:\u sers\siebiers\documents\visual studio 2015\Projects\GenericExceptionHandling\Gen ericExceptionHandling\Program.cs:line 41 at GenericExceptionHandling.Program.CallExternalFunction(Action funct) in c:\ users\siebiers\documents\visual studio 2015\Projects\GenericExceptionHandling\Ge nericExceptionHandling\Program.cs:line 26 ```
Question: I have a C# code that is using an external library which can throw exceptions. In three parts of my code, I want to process these exceptions the following way: ``` try { CallOtherLibrary(); } catch(ExceptionA) { ProcessErrorA(); } catch(ExceptionB) { ProcessErrorB(); } ``` Now I think that copy pasting this code is a code smell. One possible way to fix it to create a method that takes an action as argument, and does the try/catch. But it forces me to duplicate each method that is calling the try/catch, which leads to more code, less readable somehow. What is the clean way to handle this problem, given that I cannot change the behavior of my external library ? Answer:
You are looking for a wrapper of the alien library. In C# this is commonly done by using an `interface` with a method acting as an [Facade](https://en.wikipedia.org/wiki/Facade_pattern)/[Adapter](https://en.wikipedia.org/wiki/Adapter_pattern). You create a new class acting as an adaptee, implementing the adapter interface and in the implemented method you will have the code you mentioned in the question. You then replace the original code with call to the method of your newly created adapter and use that one in your codebase instead. The good thing about having an adapter for a library you don't own and using this adapter is not have to rewrite your own logic should the method signature of said external library change in the future, but merely change it in the adapting layer and you're all set again.
Provide a common exception handler function ``` static void Main(string[] args) { try { CallOtherLibrary(); } catch (Exception ex) { HandleException(ex); } } private static void HandleException(Exception ex) { if (ex is ExceptionA) { ProcessErrorA(); } else if (ex is ExceptionB) { ProcessErrorB(); } } ```
Question: I am trying to convert time zones from the usual format that `date +%z` is giving, to a 24 hour system. What I mean is that when I ask for ``` # date +%z +0300 ``` I want to get ``` # date +%z | something_in_awk_or_perl 3 ``` But, when I get ``` # date +%z -0700 ``` I want ``` # date +%z | something_in_awk_or_perl 17 ``` P.S. I would prefer an one-line solution Thanks! Answer:
How about using awk: ``` $ TZ=UTC-1 date +%:::z | awk 'BEGIN{FS=OFS=":"}{$1=(24+$1)%24}1' 1 $ TZ=UTC+7:30 date +%:::z | awk 'BEGIN{FS=OFS=":"}{$1=(24+$1)%24}1' 17:30 ``` If you want decimal output, change the output separator and divide by 6: ``` $ TZ=UTC-1 date +%:::z | awk -F: 'BEGIN{OFS="."}{$1=(24+$1)%24;$2/=6}1' 1.0 $ TZ=UTC+7:30 date +%:::z | awk -F: 'BEGIN{OFS="."}{$1=(24+$1)%24;$2/=6}1' 17.5 ```
``` for tz in America/Juneau America/St_Johns UTC Australia/Eucla Asia/Tokyo; do TZ=$tz date "+%z %Z" | gawk 'match($1,/([-+])([0-9][0-9])([0-9][0-9])/,a) { sign = (a[1] == "-" ? -1 : 1) print $2, $1, (sign*(a[2] + a[3]/60) + 24) % 24 }' done ``` ``` AKDT -0800 16 NDT -0230 22.5 UTC +0000 0 CWST +0845 8.75 JST +0900 9 ```
Question: I have only access to db and read-only access to hbm.xml files. It is need to increase column size. I see that in table/column definition in hbm.xml files for this table no attribute length. Should application work with increased column size in this case? Answer:
Yes, it will. Hibernate doesn't care about the length of the columns. Why don't you simply test it?
Hibernate doesn't limit the length of it's attributes it's a limitation set at database level. Normally DB will allocate enough length for the relevant fields. Since you said you only have read access I don't think that it's relevant anyway...
Question: 1. I want to make certain. Can I create for example button programmatically in viewDidLoad, if this view is connect to the xib? 2. Can I customize view programmatically via IBOutlet. Answer:
I am not sure that what happening in your code but i guess You should add all subview programatically and refresh on button click event, or write code in viewDidAppear method.
May be this is helpful to you. One way is create on UI method that set default or required value for required controllers. And call it on button event.
Question: 1. I want to make certain. Can I create for example button programmatically in viewDidLoad, if this view is connect to the xib? 2. Can I customize view programmatically via IBOutlet. Answer:
Reloading them sounds like the wrong thing to do. You can easily reset them to their default state programmatically by setting the various properties to your defaults. Once you do that I would probably just create the whole view and subviews programmatically without using IB. I do everything programmatically now and find it easier to maintain my code. You could come up with a NIB based solution by putting all affected subviews within a parent UIView and load just that parent view from a NIB and then replace the parent UIView only but I don't recommend it. You need to able to set subview properties programmatically in `viewDidLoad` anyway in case the view controller needs to unload/reload the view based on memory warnings.
May be this is helpful to you. One way is create on UI method that set default or required value for required controllers. And call it on button event.
Question: this is a code with MRTK to continuously get the position of my hand with Hololens 1. but it doesn't work because trygetposition is not recognized. how can i solve this problem ? ``` using System.Collections; using System.Collections.Generic; using UnityEngine; using Microsoft.MixedReality.Toolkit; using Microsoft.MixedReality.Toolkit.Input; using Microsoft.MixedReality.Toolkit.Utilities; using UnityEngine.UI; public class HandPosition : MonoBehaviour { public Text myText; public void OnSourceDetected(SourceStateEventData eventData) { var hand = eventData.InputSource as IMixedRealitySourceStateHandler; Vector3 handDetectedPosition; if (hand != null) { hand.TryGetPosition(eventData.SourceId, out handDetectedPosition); myText.text = (handDetectedPosition*1000).ToString(); } } } ``` Answer:
There's a syntax error in the computed property. Also, you only need a `computed` property to show the initials of the `name`: ```js const comp = Vue.component('comp', { template: '#myComp', props: { name: { type: String } }, computed: { computedInitial: { get() { let initials = this.name.match(/\b\w/g) || []; return ((initials.shift() || "") + (initials.pop() || "")).toUpperCase(); } } }, mounted() { this.$emit("set-name", "user test"); } }); new Vue({ el: "#myApp", data () { return { name: "test user" } }, methods: { setName(newName) { this.name = newName; } } }); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="myApp"> <comp :name="name" @set-name="setName" /> </div> <template id="myComp"> <div> {{computedInitial}} </div> </template> ```
your computed option should be like ``` computed:{ computedInitial:{ get(){ return this.name } } } ``` But I recommend to define `showInitial` as another computed property in order to be changed : ``` <template> <div> {{ showInitial }} </div> </template> <script> export default { props: { name: { type: String, }, data() { return { }; }, computed:{ computedInitial:{ get(){ return this.name } }, showInitial (){ let initials = this.computedInitial.match(/\b\w/g) || []; return ((initials.shift() || "") + (initials.pop() || "")).toUpperCase() } }, }; ```
Question: This is an FM transmitter that I built. I wanted to interface it with a microcontroller. The enable connection seems to work, but the range is extremely weak (about one inch), even when running off of a 9V battery. I know I didn't show it in the circuit, but I connected a 22uF capacitor across the 9V battery. The antenna length I used is 3 inches. I selected a low value for the grounded base capacitor (470pF) because I wanted to filter out the mains frequency and allow the tone from the 555 to go through. I do apologize but the bottom transistor is actually 2N3904 and the top one is PN3563, and I used PN3563 for the transmitter because I'm transmitting at a high frequency. Is there any way I can increase the range without requiring the battery to drain quickly and without requiring a higher voltage source? Do I need different transistors? What am I doing wrong? [![circuit](https://i.stack.imgur.com/o3tqv.png)](https://i.stack.imgur.com/o3tqv.png) Answer:
When you're working at VHF frequencies (like 100 MHz), parts layout is *very* important - all components around the oscillating transistor should have short leads, and be placed in a compact space. -It is also easy to **miss** the fundamental oscillating frequency when tuning your receiver...although the FM broadcast band is wide, it is *still* easy to miss. You may be tuning to a harmonic or your receiver may be so overloaded by a strong out-of-band oscillator that you're mistaking a spurious signal for the real output. If you tune around the band, and hear a similar-strength signal in various spots, this is very likely. The best way to find the oscillator's fundamental frequency is by coupling in a frequency counter loosely to the coil. -Your 470 pf base bypass capacitor might be better placed between base-to-Vcc. Connect its Vcc end quite close to the point where 0.1uH attaches to Vcc. And connect its base end very close to T1's base. -Be aware that attaching an antenna will likely move the oscillator's frequency, or possibly make the oscillator quit altogether. -Try attaching your antenna to T1's emitter, rather than to collector. It is difficult to tell what impedance your antenna is (your 3-inch antenna has a small capacitive impedance). Matching antenna coupling to the oscillator can improve signal strength, but you likely have no impedance-matching instrumentation or tools. Experiment with different antenna lengths. -Your 2N3563 for T1 is quite appropriate for this application and your substitution of 2N3904 is fine as well for T2.
Antenna must have a ground plane if just a 1/4 wave. Square law Friis losses dictate you must have 4x the power to get twice the distance. antenna gain is the best way with directional Yagi. Rotor control improves range with directional error. <https://www.pasternack.com/t-calculator-friis.aspx>
Question: I am invoking a java process using Apache exec library. I need to do some operation if the process is forcefully stopped ( using task manager or some other way). Is there any option available in exec library ? I found a waitfor() operation in ResultHandler, which is doing a busy wait. Is there any notification mechanism available ? Answer:
Avoid to hardcode javascript handlers and inline events inside the output of php code: do instead ``` echo '<div class="overlay">'; echo "<button>Close</button>"; echo '</div>'; ``` and previously insert in your page this code that detects a click on your button using event delegation ``` <script> $(document).on('click', '.overlay button', function() { $(this).parent().hide() }); </script> ```
try: ``` <button onclick="this.parentNode.style.display = 'none'; return false;">Close</button> ```
Question: I am invoking a java process using Apache exec library. I need to do some operation if the process is forcefully stopped ( using task manager or some other way). Is there any option available in exec library ? I found a waitfor() operation in ResultHandler, which is doing a busy wait. Is there any notification mechanism available ? Answer:
Avoid to hardcode javascript handlers and inline events inside the output of php code: do instead ``` echo '<div class="overlay">'; echo "<button>Close</button>"; echo '</div>'; ``` and previously insert in your page this code that detects a click on your button using event delegation ``` <script> $(document).on('click', '.overlay button', function() { $(this).parent().hide() }); </script> ```
Try this code: ``` function myfunc() { //then I have a div... echo '<div class="overlay" id="overlay" >'; echo "<button onclick=\"hide()\">Close</button>"; echo '</div>'; } //using the javascript code: function hide() { document.getElementById("overlay").style.display="none"; } ```
Question: I am invoking a java process using Apache exec library. I need to do some operation if the process is forcefully stopped ( using task manager or some other way). Is there any option available in exec library ? I found a waitfor() operation in ResultHandler, which is doing a busy wait. Is there any notification mechanism available ? Answer:
Avoid to hardcode javascript handlers and inline events inside the output of php code: do instead ``` echo '<div class="overlay">'; echo "<button>Close</button>"; echo '</div>'; ``` and previously insert in your page this code that detects a click on your button using event delegation ``` <script> $(document).on('click', '.overlay button', function() { $(this).parent().hide() }); </script> ```
try: ``` $('.overlay button').live('click',function( $('.overlay').css({'display': 'none'}); )); ```
Question: I am invoking a java process using Apache exec library. I need to do some operation if the process is forcefully stopped ( using task manager or some other way). Is there any option available in exec library ? I found a waitfor() operation in ResultHandler, which is doing a busy wait. Is there any notification mechanism available ? Answer:
try: ``` <button onclick="this.parentNode.style.display = 'none'; return false;">Close</button> ```
try: ``` $('.overlay button').live('click',function( $('.overlay').css({'display': 'none'}); )); ```
Question: I am invoking a java process using Apache exec library. I need to do some operation if the process is forcefully stopped ( using task manager or some other way). Is there any option available in exec library ? I found a waitfor() operation in ResultHandler, which is doing a busy wait. Is there any notification mechanism available ? Answer:
Try this code: ``` function myfunc() { //then I have a div... echo '<div class="overlay" id="overlay" >'; echo "<button onclick=\"hide()\">Close</button>"; echo '</div>'; } //using the javascript code: function hide() { document.getElementById("overlay").style.display="none"; } ```
try: ``` $('.overlay button').live('click',function( $('.overlay').css({'display': 'none'}); )); ```
Question: In a portfolio web design which focuses on the mobile version design (because of the scenario in which users will use it) **does it make sense to keep a hamburger menu for the desktop version?** It's a responsive webpage, and when I am on the desktop version, the menu seems inexistent. (It's also located on the right side, what makes it more confusing because it is mixed up between the colorful images. In the mobile version it seems more intuitive and highlighted.) Answer:
As [Evil Closet Monkey](https://ux.stackexchange.com/users/5591/evil-closet-monkey) said, it doesn't make sense that the hamburger icon is being used on a desktop version of the site. If you're using a responsive framework, like [Bootstrap](http://getbootstrap.com/) or [Foundation](http://foundation.zurb.com/), they should automatically adjust the menu style depending on screen size like the picture below. ![Bootstrap Nav bar](https://i.stack.imgur.com/uEm3S.jpg) If you look at [this article where I grabbed the image](http://www.sanwebe.com/2013/02/bootstrap-framework-quick-start), you'll see how navigation works while using Bootstrap. It also shows you the HTML to set up a fluid navigation bar.
I agree with the answer and comments above, it's like UX 101 and I won't argue with that but... let me add a different view to consider. You say this is for a portfolio. Portfolios are meant to display your work, but also who you are. It's a way to tell the world "Hey, I'm me. And additionally, I can do all of this!". Personally, I know what are the basics of UX, UI, design trends, etc. Now I want YOU to show me something else, doesn't matter if right or wrong, I want you to show you can think out of the box. Everybody and his mother can follow the rules in a book, what I want to see is if you can break the rules (providing you know them first). Keep in mind nothing was ever created without breaking rules. By definition. It's an absolute impossible. And by the way, if you're a designer with an artist edge, you probably know how that tedious menu takes that valuable space even on that giant screen, right? You probably don't want to pollute your great design with that boring nav What I mean with this is... yeah, why not? But also... what stops you from doing something else? Something really crazy? You'll have a lot of space to go creative, so... why don't you? PS: I did a desktop site with hidden menus based on some full screen layout with crazy tabs that gave the client 225% more business (consultation and design). I don't know, maybe with the regular menu it could have work even better, but believe me it's not exactly an issue. And if in doubt... TEST!
Question: In a portfolio web design which focuses on the mobile version design (because of the scenario in which users will use it) **does it make sense to keep a hamburger menu for the desktop version?** It's a responsive webpage, and when I am on the desktop version, the menu seems inexistent. (It's also located on the right side, what makes it more confusing because it is mixed up between the colorful images. In the mobile version it seems more intuitive and highlighted.) Answer:
As [Evil Closet Monkey](https://ux.stackexchange.com/users/5591/evil-closet-monkey) said, it doesn't make sense that the hamburger icon is being used on a desktop version of the site. If you're using a responsive framework, like [Bootstrap](http://getbootstrap.com/) or [Foundation](http://foundation.zurb.com/), they should automatically adjust the menu style depending on screen size like the picture below. ![Bootstrap Nav bar](https://i.stack.imgur.com/uEm3S.jpg) If you look at [this article where I grabbed the image](http://www.sanwebe.com/2013/02/bootstrap-framework-quick-start), you'll see how navigation works while using Bootstrap. It also shows you the HTML to set up a fluid navigation bar.
Context is everything. Maybe it matters, maybe it doesn't. The fact that it's a portfolio site has no real bearing in and of itself. Generically speaking, should you retain the hamburger menu on larger screens? Traditionally we haven't. But it's becoming an increasingly popular option. Some sites that retain the hamburger menu even on large screens: * <http://time.com/> * <http://www.squarespace.com/> Whether it's good or bad, again, depends on context. Some sites you want a really robust always-visible navigation system. Sometimes site navigation is secondary to the home page content. It's a judgement call. Arguments for *not* using a hamburger menu on large screens: * hiding navigation is usually a bad idea, so why hide it? * while people are more familiar with them on small screens, they may not be looking for them on large screens Arguments *for* using a hamburger menu on a large screen: * lots of large screens are now touch devices. Hamburger menus allow you to expose a much larger touch-friendly version of site navigation than if it was on-screen at all times. * may make development and maintenance of that part of the site a bit easier across all viewports. * may offer some consistency for users that use your site on multiple devices.
Question: In a portfolio web design which focuses on the mobile version design (because of the scenario in which users will use it) **does it make sense to keep a hamburger menu for the desktop version?** It's a responsive webpage, and when I am on the desktop version, the menu seems inexistent. (It's also located on the right side, what makes it more confusing because it is mixed up between the colorful images. In the mobile version it seems more intuitive and highlighted.) Answer:
The hamburger menu... I'm torn. ***The hamburger menu decreases discoverability because it hides what the user is more than likely going to use to... well... discover*** At a glance, the user can tell what's where and how to find what they are looking for. Being hidden underneath someplace isn't ideal for scanability. Having said that, stay away from keeping it on the desktop site. The reason why people feel the need to keep it on mobile is because there isn't much space for a full blown menu. Just be careful. [The hamburger menu is ambiguous, it was tested to find that people didn't understand it](http://exisweb.net/mobile-menu-abtest). If you want to incorporate the hamburger menu, make sure to at least add a label to it (or just completely take out the icon and leave the label like "menu"). --- To add to this, sites like twitter has completely eliminated the use of the hamburger menu and threw a menu to navigation at the bottom of their application. ![enter image description here](https://i.stack.imgur.com/8BuGR.png) Same thing with Facebook, but they still have a hamburger menu, but for a different purpose. How it was: ![enter image description here](https://i.stack.imgur.com/ygNhW.jpg) To what it became: ![enter image description here](https://i.stack.imgur.com/hhG5X.jpg)
I agree with the answer and comments above, it's like UX 101 and I won't argue with that but... let me add a different view to consider. You say this is for a portfolio. Portfolios are meant to display your work, but also who you are. It's a way to tell the world "Hey, I'm me. And additionally, I can do all of this!". Personally, I know what are the basics of UX, UI, design trends, etc. Now I want YOU to show me something else, doesn't matter if right or wrong, I want you to show you can think out of the box. Everybody and his mother can follow the rules in a book, what I want to see is if you can break the rules (providing you know them first). Keep in mind nothing was ever created without breaking rules. By definition. It's an absolute impossible. And by the way, if you're a designer with an artist edge, you probably know how that tedious menu takes that valuable space even on that giant screen, right? You probably don't want to pollute your great design with that boring nav What I mean with this is... yeah, why not? But also... what stops you from doing something else? Something really crazy? You'll have a lot of space to go creative, so... why don't you? PS: I did a desktop site with hidden menus based on some full screen layout with crazy tabs that gave the client 225% more business (consultation and design). I don't know, maybe with the regular menu it could have work even better, but believe me it's not exactly an issue. And if in doubt... TEST!
Question: In a portfolio web design which focuses on the mobile version design (because of the scenario in which users will use it) **does it make sense to keep a hamburger menu for the desktop version?** It's a responsive webpage, and when I am on the desktop version, the menu seems inexistent. (It's also located on the right side, what makes it more confusing because it is mixed up between the colorful images. In the mobile version it seems more intuitive and highlighted.) Answer:
Context is everything. Maybe it matters, maybe it doesn't. The fact that it's a portfolio site has no real bearing in and of itself. Generically speaking, should you retain the hamburger menu on larger screens? Traditionally we haven't. But it's becoming an increasingly popular option. Some sites that retain the hamburger menu even on large screens: * <http://time.com/> * <http://www.squarespace.com/> Whether it's good or bad, again, depends on context. Some sites you want a really robust always-visible navigation system. Sometimes site navigation is secondary to the home page content. It's a judgement call. Arguments for *not* using a hamburger menu on large screens: * hiding navigation is usually a bad idea, so why hide it? * while people are more familiar with them on small screens, they may not be looking for them on large screens Arguments *for* using a hamburger menu on a large screen: * lots of large screens are now touch devices. Hamburger menus allow you to expose a much larger touch-friendly version of site navigation than if it was on-screen at all times. * may make development and maintenance of that part of the site a bit easier across all viewports. * may offer some consistency for users that use your site on multiple devices.
I agree with the answer and comments above, it's like UX 101 and I won't argue with that but... let me add a different view to consider. You say this is for a portfolio. Portfolios are meant to display your work, but also who you are. It's a way to tell the world "Hey, I'm me. And additionally, I can do all of this!". Personally, I know what are the basics of UX, UI, design trends, etc. Now I want YOU to show me something else, doesn't matter if right or wrong, I want you to show you can think out of the box. Everybody and his mother can follow the rules in a book, what I want to see is if you can break the rules (providing you know them first). Keep in mind nothing was ever created without breaking rules. By definition. It's an absolute impossible. And by the way, if you're a designer with an artist edge, you probably know how that tedious menu takes that valuable space even on that giant screen, right? You probably don't want to pollute your great design with that boring nav What I mean with this is... yeah, why not? But also... what stops you from doing something else? Something really crazy? You'll have a lot of space to go creative, so... why don't you? PS: I did a desktop site with hidden menus based on some full screen layout with crazy tabs that gave the client 225% more business (consultation and design). I don't know, maybe with the regular menu it could have work even better, but believe me it's not exactly an issue. And if in doubt... TEST!
Question: In a portfolio web design which focuses on the mobile version design (because of the scenario in which users will use it) **does it make sense to keep a hamburger menu for the desktop version?** It's a responsive webpage, and when I am on the desktop version, the menu seems inexistent. (It's also located on the right side, what makes it more confusing because it is mixed up between the colorful images. In the mobile version it seems more intuitive and highlighted.) Answer:
The hamburger menu... I'm torn. ***The hamburger menu decreases discoverability because it hides what the user is more than likely going to use to... well... discover*** At a glance, the user can tell what's where and how to find what they are looking for. Being hidden underneath someplace isn't ideal for scanability. Having said that, stay away from keeping it on the desktop site. The reason why people feel the need to keep it on mobile is because there isn't much space for a full blown menu. Just be careful. [The hamburger menu is ambiguous, it was tested to find that people didn't understand it](http://exisweb.net/mobile-menu-abtest). If you want to incorporate the hamburger menu, make sure to at least add a label to it (or just completely take out the icon and leave the label like "menu"). --- To add to this, sites like twitter has completely eliminated the use of the hamburger menu and threw a menu to navigation at the bottom of their application. ![enter image description here](https://i.stack.imgur.com/8BuGR.png) Same thing with Facebook, but they still have a hamburger menu, but for a different purpose. How it was: ![enter image description here](https://i.stack.imgur.com/ygNhW.jpg) To what it became: ![enter image description here](https://i.stack.imgur.com/hhG5X.jpg)
Context is everything. Maybe it matters, maybe it doesn't. The fact that it's a portfolio site has no real bearing in and of itself. Generically speaking, should you retain the hamburger menu on larger screens? Traditionally we haven't. But it's becoming an increasingly popular option. Some sites that retain the hamburger menu even on large screens: * <http://time.com/> * <http://www.squarespace.com/> Whether it's good or bad, again, depends on context. Some sites you want a really robust always-visible navigation system. Sometimes site navigation is secondary to the home page content. It's a judgement call. Arguments for *not* using a hamburger menu on large screens: * hiding navigation is usually a bad idea, so why hide it? * while people are more familiar with them on small screens, they may not be looking for them on large screens Arguments *for* using a hamburger menu on a large screen: * lots of large screens are now touch devices. Hamburger menus allow you to expose a much larger touch-friendly version of site navigation than if it was on-screen at all times. * may make development and maintenance of that part of the site a bit easier across all viewports. * may offer some consistency for users that use your site on multiple devices.
Question: I'm having a arraylist which I need to specify the type in runtime. ``` ArrayList<String> alist = new ArrayList<String>(); ``` I need to specify the type "String" at runtime. how can I do that. It should not be static. Answer:
Thats no possible due to [type erasure](http://java.sun.com/docs/books/tutorial/java/generics/erasure.html) — a process where the compiler removes all information related to type parameters and type arguments within a class or method. It's only available during compile time, to check types. EDIT: As a workaround to your problem you could use `ArrayList<Object>` this would allow you to add any types to the ArrayList. In this case you could check types using instanceof and cast to concrete types.
You mean you want to parameterize the type used to create the `ArrayList`? ``` public <T> List<T> interestingMethod(Class<T> type) { List<T> aList = new ArrayList<T>(); // do something interesting... return aList; } ``` Passing the `type` argument is only needed for type inference and I find this pattern a kludge, but it's the only way with Java. As the everyone else will point out, we don't have runtime type information with generics because of type erasure.
Question: I'm having a arraylist which I need to specify the type in runtime. ``` ArrayList<String> alist = new ArrayList<String>(); ``` I need to specify the type "String" at runtime. how can I do that. It should not be static. Answer:
Thats no possible due to [type erasure](http://java.sun.com/docs/books/tutorial/java/generics/erasure.html) — a process where the compiler removes all information related to type parameters and type arguments within a class or method. It's only available during compile time, to check types. EDIT: As a workaround to your problem you could use `ArrayList<Object>` this would allow you to add any types to the ArrayList. In this case you could check types using instanceof and cast to concrete types.
The generic type parameter is not compiled into the bytecode, therefore it is not available at runtime. An ArrayList<String> is simply an ArrayList at runtime. The closest thing you can achieve, is to add runtime checks yourself. For example, Collections class provides a [decorator](http://en.wikipedia.org/wiki/Decorator_pattern) that does exactly this: ``` List l = Collections.checkedList(new ArrayList<String>(), String.class); l.add("Jave uses erasure"); l.add(14); ``` If the list was created simply as ArrayList<String>, the two additions would succeed at runtime. With the wrapper implementation however, every item addition is validated, so the second call will cause a ClassCastException.
Question: Consider the following piece of swift code ``` view1.autoPinEdge(.top, toEdge: .bottom, ofView: view2) ``` what is going on with `.top`, `.bottom`? 1) Why is this seemingly ambiguous way of specifying a variable allowed? 2) How does swift handle the situation where there are many possible `.top` and `.bottom`? Answer:
The method is (most likely) declared as ``` func autoPinEdge(_ from: UIRectEdge, toEdge: UIRectEdge, ofView: UIView) ``` so the compiler knows that the type of the first two parameters is `UIRectEdge`. --- The full syntax to call the method is ``` view1.autoPinEdge(UIRectEdge.top, toEdge: UIRectEdge.bottom, ofView: view2) ``` but as the compiler knows (the documentation says *can infer*) the type you can pass only the members ``` view1.autoPinEdge(.top, toEdge: .bottom, ofView: view2) ```
This is just a shorthand way of using an enum value. for example, using the function... ``` func applyColour(_ colour: UIColor) { // apply the colour } ``` Could be called using the following syntax ``` applyColour(UIColor.red) ``` or ``` applyColour(.red) ``` Because the compiler knows that the function is expecting a `UIColor` parameter. So it can imply the type when you use `.red` You can also use type inference with static functions and variables like so: ``` extension String { static var headerText { return "This is the header" } } ``` Usage: ``` headerLabel.text = .headerText ``` or: ``` let heading: String = .headerText ```
Question: So I'm getting started with React Native. Honestly working with XCode has been one of the most miserable development experiences I've experienced in my life. The simulator literally takes 20+ minutes to boot up (is this normal??) and when it does I can't launch the app because it's on port 8081 which apparently something else is running on so it just crashes. So now I have to change it and probably wait another 30 minutes for the simulator to boot up. My question is, what is the best way to change the port number in a React Native iOS app. I've seen references to the appDelegate.m file but it seems that it's not allowing you to change it in this file anymore because I see no reference to localhost:8081 anywhere in it. Any help would be appreciated. I also have tried `react-native start --port 9988` this starts a terminal session and looks like it's working but doesn't launch xcode, the simulator or anything. When I launch Xcode and then run the app from here it launches another terminal session pointing to port 8081 pretty much just undoing what I did. Been basically sitting and waiting on xcode for the last 5 hours. Super frustrating. Just wanna start coding!! Thanks! Answer:
Had the same problem, I found that the React library takes a user defined setting to change the default port : `RCT_METRO_PORT` in : -> Libraries -> React.xcodeproj -> Build Settings -> Add user defined setting i added this and it solved my problem
In `react-native: 0.60.5` Go to > [Your Project] > ios > [Your Project].xcodeproj > project.pbxproj. Search for 8081 and replace all the port 8081 to 8089(example) ``` shellScript = "export RCT_METRO_PORT=\"${RCT_METRO_PORT:=8089}\"\necho \"export RCT_METRO_PORT=${RCT_METRO_PORT}\" > \"${SRCROOT}/../node_modules/react-native/scripts/.packager.env\"\nif [ -z \"${RCT_NO_LAUNCH_PACKAGER+xxx}\" ] ; then\n if nc -w 5 -z localhost ${RCT_METRO_PORT} ; then\n if ! curl -s \"http://localhost:${RCT_METRO_PORT}/status\" | grep -q \"packager-status:running\" ; then\n echo \"Port ${RCT_METRO_PORT} already in use, packager is either not running or not running correctly\"\n exit 2\n fi\n else\n open \"$SRCROOT/../node_modules/react-native/scripts/launchPackager.command\" || echo \"Can't start packager automatically\"\n fi\nfi\n"; ```
Question: my code is this ``` bv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if(mp.isPlaying()){ mp.pause(); bv.setImageResource(R.drawable.playzz); } else { bv.setImageResource(R.drawable.pausezz); for (int i=1; i<=10 ; i++){ mp.start(); } } } ``` I wanted to repeat a song for only 10 time. i used for loop but the sound plays only one time and stops. Any idea how to do this?? thanks in advance. Answer:
You should do this in a separate thread (assuming mp is a field): ``` mp.setOnCompletionListener(new OnCompletionListener() { int n = 0; @Override public void onCompletion(MediaPlayer mp) { if (n < 10) { mp.start(); n++; } } }); mp.start(); ``` doing ``` while(mp.isPlaying()); ``` will eat your CPU.
I believe that the song starts 10 times without waiting for the first instance to end, so what you need to do is check if the song is still playing and start it again only after it has stopped playing. Maybe something like this - ``` for (int i=1; i<=10 ; i++){ mp.start(); while(mp.isPlaying()); } ``` This will make sure that the next instance of the song starts only after the current instance has finished. Also you need to run this in the background and not in onClick so that it won't interrupt any other foreground process.
Question: If you are building a large cloud based platform, you will have so many different modules/components within that platform. This ranges from web service configurations (address, ports,...) to domain specific configurations for every component that you have. One can configure such system by giving every component in the system a tockenized config file and then have a big tocken resolving file for the entire platform. This gets messy in no time! I was thinking that maybe a better approach to centralize the whole platform configuration into a web service as the central configuration system for the platform and then every component in the system come to this web service and request their configuration settings by providing their id or a unique config name. I even think that such configuration must be type safe so that all the system component refer to their desired configuration explicitly vs a key-value way approach. Another important feature of this central configuration system should be the ability to make configuration values dependent on the server side so that I would be able to say component1Config.LogServiceAddress = someMasterConfig.Address; at the server side. So only the central configuration system knows about the above logic and component1 simply gets a value for its LogServiceAddress without knowing how that was resolved by the central configuration system. My question is, does such central configuration system already exist? Is there any open source software out there providing such central configuration system capabilities? Answer:
Chef/Puppet are the standard ways to centralize provisioning of multiple stacks on various machines. The central server can bring up remote nodes, and then push required stack on that machine. While I have seen usage of same for provisioning of software, I think it very well can be extended to fulfill your needs!
[WCF Discovery Overview](http://msdn.microsoft.com/en-us/library/dd456791.aspx) Make a service and when a service announces, it adds to the list of services. Use Metadata to serve up configuration settings and such. To be fair, there is also [Mono.Zeroconf](http://www.mono-project.com/Mono.Zeroconf) which requires bonjour(apple).
Question: This if for the C++ gurus out there. Consider the following code: ``` class X { }; template <class T> class Mistake { public: T x; Mistake(const T& k) : x(k) { } Mistake(const X&) : x(1) { } void print() { cout << x << endl; } }; template <class T> Mistake<T> operator+(const Mistake<T>& a, const Mistake<T>& b) { return Mistake<T>(a.x + b.x); } ``` I have a class "Mistake" for which I want to have the addition operation. When I try: ``` X a, b; Mistake<int> foo = a + b; ``` I get a compilation error; the compiler cannot seem to realize that the template operator+ has to be instantiated. If, on the other hand, I add the following piece of code before: ``` Mistake<int> operator+(const Mistake<int>& a, const Mistake<int>& b) { return Mistake<int>(a.x + b.x); } ``` then all is well. Anyone has any clue why? I suspect the compiler cannot figure out what to instantiate because of the type conversion needed from class X to class Mistake, but I don't know how to fix this issue short of not using templates at all. By the way, defining the operator inside the class as a friend also doesn't work. Thanks! Answer:
I don't think there is a way. The purest you can achieve is ``` Mistake<int> foo = static_cast<Mistake<int>>(a) + static_cast<Mistake<int>>(b); ``` Or if you push it a little using an additional overload that matches assymetric operand types: ``` template <class T, class U> Mistake<T> operator+(const Mistake<T>& a, U const& b) { return a + static_cast<Mistake<T>>(b); } // and later: foo = Mistake<int>(a) + b; ``` Full live demo: <http://ideone.com/ki14GO> ``` #include <iostream> class X { }; template <class T> class Mistake { public: T x; Mistake(const T& k) : x(k) { } Mistake(const X&) : x(1) { } void print() { std::cout << x << std::endl; } }; template <class T> Mistake<T> operator+(const Mistake<T>& a, const Mistake<T>& b) { return Mistake<T>(a.x + b.x); } template <class T, class U> Mistake<T> operator+(const Mistake<T>& a, U const& b) { return a + static_cast<Mistake<T>>(b); } template <class T, class U> Mistake<T> operator+(const U& a, Mistake<T> const& b) { return static_cast<Mistake<T>>(a) + b; } int main() { X a, b; Mistake<int> foo = static_cast<Mistake<int>>(a) + static_cast<Mistake<int>>(b); foo = Mistake<int>(a) + b; foo = a + Mistake<int>(b); } ```
I believe the compiler has a problem with deducing the type of `a + b`. You can define: ``` X operator+(const X & a, const X & b) { return a /* ??? or something else */; } ``` if you have any way to tell what the answer to `a + b` is in terms of `X`.
Question: This if for the C++ gurus out there. Consider the following code: ``` class X { }; template <class T> class Mistake { public: T x; Mistake(const T& k) : x(k) { } Mistake(const X&) : x(1) { } void print() { cout << x << endl; } }; template <class T> Mistake<T> operator+(const Mistake<T>& a, const Mistake<T>& b) { return Mistake<T>(a.x + b.x); } ``` I have a class "Mistake" for which I want to have the addition operation. When I try: ``` X a, b; Mistake<int> foo = a + b; ``` I get a compilation error; the compiler cannot seem to realize that the template operator+ has to be instantiated. If, on the other hand, I add the following piece of code before: ``` Mistake<int> operator+(const Mistake<int>& a, const Mistake<int>& b) { return Mistake<int>(a.x + b.x); } ``` then all is well. Anyone has any clue why? I suspect the compiler cannot figure out what to instantiate because of the type conversion needed from class X to class Mistake, but I don't know how to fix this issue short of not using templates at all. By the way, defining the operator inside the class as a friend also doesn't work. Thanks! Answer:
While others have proposed possible solutions to your problem, I would like to point out what is going on, and why your expectation cannot be met. The problem here is that **user-defined conversions are not considered when performing type deduction**. When the compiler is presented with this expression: ``` a + b ``` Where both `a` and `b` are of type `X`, and the following signature for `operator +`: ``` template <class T> Mistake<T> operator+(const Mistake<T>& a, const Mistake<T>& b) ``` The first thing the compiler will do is to try and deduce `T` so that the types of the parameters of the operator match *exaclty* the types of the arguments. If this is not possible, the compiler immediately gives up, without considering possible converting constructors, and focuses on other candidate functions (or function templates). Considering the situation above, it is clear that there is no way to make `Mistake<T>` become *exaclty* `X`, whatever `T` you pick (`Mistake<int>` is not `X`, `Mistake<X>` is not `X`, and so on). Therefore, substitution fails and the compiler does not know how to resolve the call because there are no other candidates around. On the other hand, when you have this: ``` Mistake<int> operator+(const Mistake<int>& a, const Mistake<int>& b) ``` There is no type deduction involved, because the above is not a function template. Therefore, the compiler *will* take user-defined conversions into account when trying to resolve the call, and since `Mistake<int>` has a constructor that accepts an `X`, the above `operator +` is considered a viable candidate, and it gets picked.
I don't think there is a way. The purest you can achieve is ``` Mistake<int> foo = static_cast<Mistake<int>>(a) + static_cast<Mistake<int>>(b); ``` Or if you push it a little using an additional overload that matches assymetric operand types: ``` template <class T, class U> Mistake<T> operator+(const Mistake<T>& a, U const& b) { return a + static_cast<Mistake<T>>(b); } // and later: foo = Mistake<int>(a) + b; ``` Full live demo: <http://ideone.com/ki14GO> ``` #include <iostream> class X { }; template <class T> class Mistake { public: T x; Mistake(const T& k) : x(k) { } Mistake(const X&) : x(1) { } void print() { std::cout << x << std::endl; } }; template <class T> Mistake<T> operator+(const Mistake<T>& a, const Mistake<T>& b) { return Mistake<T>(a.x + b.x); } template <class T, class U> Mistake<T> operator+(const Mistake<T>& a, U const& b) { return a + static_cast<Mistake<T>>(b); } template <class T, class U> Mistake<T> operator+(const U& a, Mistake<T> const& b) { return static_cast<Mistake<T>>(a) + b; } int main() { X a, b; Mistake<int> foo = static_cast<Mistake<int>>(a) + static_cast<Mistake<int>>(b); foo = Mistake<int>(a) + b; foo = a + Mistake<int>(b); } ```
Question: This if for the C++ gurus out there. Consider the following code: ``` class X { }; template <class T> class Mistake { public: T x; Mistake(const T& k) : x(k) { } Mistake(const X&) : x(1) { } void print() { cout << x << endl; } }; template <class T> Mistake<T> operator+(const Mistake<T>& a, const Mistake<T>& b) { return Mistake<T>(a.x + b.x); } ``` I have a class "Mistake" for which I want to have the addition operation. When I try: ``` X a, b; Mistake<int> foo = a + b; ``` I get a compilation error; the compiler cannot seem to realize that the template operator+ has to be instantiated. If, on the other hand, I add the following piece of code before: ``` Mistake<int> operator+(const Mistake<int>& a, const Mistake<int>& b) { return Mistake<int>(a.x + b.x); } ``` then all is well. Anyone has any clue why? I suspect the compiler cannot figure out what to instantiate because of the type conversion needed from class X to class Mistake, but I don't know how to fix this issue short of not using templates at all. By the way, defining the operator inside the class as a friend also doesn't work. Thanks! Answer:
While others have proposed possible solutions to your problem, I would like to point out what is going on, and why your expectation cannot be met. The problem here is that **user-defined conversions are not considered when performing type deduction**. When the compiler is presented with this expression: ``` a + b ``` Where both `a` and `b` are of type `X`, and the following signature for `operator +`: ``` template <class T> Mistake<T> operator+(const Mistake<T>& a, const Mistake<T>& b) ``` The first thing the compiler will do is to try and deduce `T` so that the types of the parameters of the operator match *exaclty* the types of the arguments. If this is not possible, the compiler immediately gives up, without considering possible converting constructors, and focuses on other candidate functions (or function templates). Considering the situation above, it is clear that there is no way to make `Mistake<T>` become *exaclty* `X`, whatever `T` you pick (`Mistake<int>` is not `X`, `Mistake<X>` is not `X`, and so on). Therefore, substitution fails and the compiler does not know how to resolve the call because there are no other candidates around. On the other hand, when you have this: ``` Mistake<int> operator+(const Mistake<int>& a, const Mistake<int>& b) ``` There is no type deduction involved, because the above is not a function template. Therefore, the compiler *will* take user-defined conversions into account when trying to resolve the call, and since `Mistake<int>` has a constructor that accepts an `X`, the above `operator +` is considered a viable candidate, and it gets picked.
I believe the compiler has a problem with deducing the type of `a + b`. You can define: ``` X operator+(const X & a, const X & b) { return a /* ??? or something else */; } ``` if you have any way to tell what the answer to `a + b` is in terms of `X`.
Question: I just released my first ever application into the world and asked for feedback. I was surprised by the feedback, because the users are asking for a lot of detail. They seem to want a user interface filled with buttons, knobs and sliders that lets them tweak every little thing to their desire. Everything I've read about usability tells me that this is exactly what to avoid, but it is what the users are asking for. So I'm trying to figure out if I should give the users what they are asking for, or if it is typical for users to ask for more detail than they really want. Answer:
This is the kind of feedback that is the easiest to elicit from users - details on color choice or extra features. I think the "intention" part is the important one. The problem the users are trying to solve using your application. So if you have any way of contacting the users who has given you feedback - or even just a radom selection of any of your users, you might find the answers to this question relevant: [How to discover what users NEED and not what they WANT?](https://ux.stackexchange.com/questions/13674/how-to-discover-what-users-need-and-not-what-they-want)
Actually, it is perfectly normal to receive very little feedback. So it's good you're hearing from your users. Try to organize these requests, filter them, prioritize them. You don't want to do anything to jeapordize the usability of your application. Some requests you'll simply have to say no to, but there may be others that are worth implementing. Try to find the intention behind these requests. Many times someone will state the problem they're trying to solve and suggest a solution. Their solution may not be the best one, even if their problem is valid. So it's your job to find the most elegant solution. Also I'd consider signing up with a site like [Uservoice](http://uservoice.com/) or [GetSatisfaction](http://getsatisfaction.com/). Then your users will be able to vote on feature requests, and that'll more or less prioritize your work for you.
Question: I just released my first ever application into the world and asked for feedback. I was surprised by the feedback, because the users are asking for a lot of detail. They seem to want a user interface filled with buttons, knobs and sliders that lets them tweak every little thing to their desire. Everything I've read about usability tells me that this is exactly what to avoid, but it is what the users are asking for. So I'm trying to figure out if I should give the users what they are asking for, or if it is typical for users to ask for more detail than they really want. Answer:
Actually, it is perfectly normal to receive very little feedback. So it's good you're hearing from your users. Try to organize these requests, filter them, prioritize them. You don't want to do anything to jeapordize the usability of your application. Some requests you'll simply have to say no to, but there may be others that are worth implementing. Try to find the intention behind these requests. Many times someone will state the problem they're trying to solve and suggest a solution. Their solution may not be the best one, even if their problem is valid. So it's your job to find the most elegant solution. Also I'd consider signing up with a site like [Uservoice](http://uservoice.com/) or [GetSatisfaction](http://getsatisfaction.com/). Then your users will be able to vote on feature requests, and that'll more or less prioritize your work for you.
When users give feedback, they are saying that there is an issue. It's your task to discover what they 'need'. To discover that, you have to ask the 'why' question loads of times. Why do you want that button? Why is that important? Why are you trying to do this? After asking loads of questions, you'll need to test new designs to make sure the interface changes slowly (Interface changes are always hard to digest), and to make sure these changes are really useful.
Question: I just released my first ever application into the world and asked for feedback. I was surprised by the feedback, because the users are asking for a lot of detail. They seem to want a user interface filled with buttons, knobs and sliders that lets them tweak every little thing to their desire. Everything I've read about usability tells me that this is exactly what to avoid, but it is what the users are asking for. So I'm trying to figure out if I should give the users what they are asking for, or if it is typical for users to ask for more detail than they really want. Answer:
This is the kind of feedback that is the easiest to elicit from users - details on color choice or extra features. I think the "intention" part is the important one. The problem the users are trying to solve using your application. So if you have any way of contacting the users who has given you feedback - or even just a radom selection of any of your users, you might find the answers to this question relevant: [How to discover what users NEED and not what they WANT?](https://ux.stackexchange.com/questions/13674/how-to-discover-what-users-need-and-not-what-they-want)
When users give feedback, they are saying that there is an issue. It's your task to discover what they 'need'. To discover that, you have to ask the 'why' question loads of times. Why do you want that button? Why is that important? Why are you trying to do this? After asking loads of questions, you'll need to test new designs to make sure the interface changes slowly (Interface changes are always hard to digest), and to make sure these changes are really useful.
Question: I just released my first ever application into the world and asked for feedback. I was surprised by the feedback, because the users are asking for a lot of detail. They seem to want a user interface filled with buttons, knobs and sliders that lets them tweak every little thing to their desire. Everything I've read about usability tells me that this is exactly what to avoid, but it is what the users are asking for. So I'm trying to figure out if I should give the users what they are asking for, or if it is typical for users to ask for more detail than they really want. Answer:
This is the kind of feedback that is the easiest to elicit from users - details on color choice or extra features. I think the "intention" part is the important one. The problem the users are trying to solve using your application. So if you have any way of contacting the users who has given you feedback - or even just a radom selection of any of your users, you might find the answers to this question relevant: [How to discover what users NEED and not what they WANT?](https://ux.stackexchange.com/questions/13674/how-to-discover-what-users-need-and-not-what-they-want)
Bear in mind that the people who feedback are a self selecting group who want changes. There may well be another, larger, group who are perfectly happy with your original interface, and may become unhappy if you start adding lots of extra controls. The only way you'll know whether this is the case is by organising some proper user research.
Question: I just released my first ever application into the world and asked for feedback. I was surprised by the feedback, because the users are asking for a lot of detail. They seem to want a user interface filled with buttons, knobs and sliders that lets them tweak every little thing to their desire. Everything I've read about usability tells me that this is exactly what to avoid, but it is what the users are asking for. So I'm trying to figure out if I should give the users what they are asking for, or if it is typical for users to ask for more detail than they really want. Answer:
Bear in mind that the people who feedback are a self selecting group who want changes. There may well be another, larger, group who are perfectly happy with your original interface, and may become unhappy if you start adding lots of extra controls. The only way you'll know whether this is the case is by organising some proper user research.
When users give feedback, they are saying that there is an issue. It's your task to discover what they 'need'. To discover that, you have to ask the 'why' question loads of times. Why do you want that button? Why is that important? Why are you trying to do this? After asking loads of questions, you'll need to test new designs to make sure the interface changes slowly (Interface changes are always hard to digest), and to make sure these changes are really useful.
Question: Recently on [Reddit ReverseEngineering](http://www.reddit.com/r/ReverseEngineering) I stumbled on a [self-modifying code in Python](http://www.reddit.com/r/ReverseEngineering/comments/1da222/selfmodifying_python_bytecode/). Looking at the [Github](https://github.com/0vercl0k/stuffz/tree/master/Python%27s%20internals) repository was quite instructive and I found picture of the Python bytecode program exposed in CFG form: ![enter image description here](https://i.stack.imgur.com/TKeQM.png) I am wondering if there are tools to perform static analysis on Python bytecode program with some nice features (such as generating the CFG or allowing to manipulate the code, ...) ? Answer:
There are several tools dedicated to Python's bytecode reversing: * [Uncompyle](https://github.com/gstarnberger/uncompyle) and [Uncompyle2](https://github.com/fry/uncompyle2) > > 'uncompyle' converts Python byte-code back into equivalent Python > source. It accepts byte-code from Python version 2.7 only. The generated source is very readable: docstrings, lists, tuples and hashes get pretty-printed. > > > 'uncompyle' may also verify the equivalence of the generated source by > by compiling it and comparing both byte-codes. > 'uncompyle' is based on John Aycock's generic small languages compiler > '[spark](http://www.csr.uvic.ca/~aycock/python/)' and his prior work on > 'decompyle'. > > > * [pyREtic](https://github.com/MyNameIsMeerkat/pyREtic), that is more a powerful framework than a simple program > > pyREtic is an extensible framework to assist in performing various reverse engineering tasks for Python language projects. It assists a reverse engineer in gaining sourcecode (.py's) back from bytecode (.pyc's), in particular it assists when the code that is being reversed has put some effort into trying to stop decompilation using standard toolsets. > > > * [pycdc](https://github.com/zrax/pycdc), which works better than uncompyle, and is simpler to use than pyRetic > > Decompyle++ aims to translate compiled Python byte-code back into valid and human-readable Python source code. While other projects have achieved this with varied success, Decompyle++ is unique in that it seeks to support byte-code from any version of Python. > > > Decompyle++ includes both a byte-code disassembler (pycdas) and a decompiler (pycdc). > > > * The [Manyard](https://bitbucket.org/larry/maynard) framework, which is dedicated to Python3
[Maynard](https://bitbucket.org/larry/maynard) is a (dis)assembler for Python byte code written by a member of Python core and the release manager for Python 3.4. Reading material [here](https://lwn.net/Articles/544787/) and [here](https://www.youtube.com/watch?v=CKu6d_v4Pqo). I'm not aware of a public tool (besides the one you linked) that can do CFG visualization like that, but you certainly could build one on top of Maynard.
Question: Recently on [Reddit ReverseEngineering](http://www.reddit.com/r/ReverseEngineering) I stumbled on a [self-modifying code in Python](http://www.reddit.com/r/ReverseEngineering/comments/1da222/selfmodifying_python_bytecode/). Looking at the [Github](https://github.com/0vercl0k/stuffz/tree/master/Python%27s%20internals) repository was quite instructive and I found picture of the Python bytecode program exposed in CFG form: ![enter image description here](https://i.stack.imgur.com/TKeQM.png) I am wondering if there are tools to perform static analysis on Python bytecode program with some nice features (such as generating the CFG or allowing to manipulate the code, ...) ? Answer:
[Maynard](https://bitbucket.org/larry/maynard) is a (dis)assembler for Python byte code written by a member of Python core and the release manager for Python 3.4. Reading material [here](https://lwn.net/Articles/544787/) and [here](https://www.youtube.com/watch?v=CKu6d_v4Pqo). I'm not aware of a public tool (besides the one you linked) that can do CFG visualization like that, but you certainly could build one on top of Maynard.
The [Flare-bytecode graph](https://github.com/fireeye/flare-bytecode_graph) project can help with graphical bytecode CFG representation. Taken from the project `README`: > > ... > > It is also possible to create control flow diagrams using GraphViz. The disassembly within the graph can include the output from a simple peephole decompiler. > > > > ``` > import bytecode_graph > def Sample(): > i = 2 + 2 > if i == 4: > print "2 + 2 = %d" % i > else: > print "oops" > > bcg = bytecode_graph.BytecodeGraph(Sample.__code__) > graph = bytecode_graph.Render(bcg, Sample.__code__).dot() > graph.write_png('example_graph.png') > > ``` > > [![program CFG](https://i.stack.imgur.com/TuxNr.png)](https://i.stack.imgur.com/TuxNr.png) > > >
Question: Recently on [Reddit ReverseEngineering](http://www.reddit.com/r/ReverseEngineering) I stumbled on a [self-modifying code in Python](http://www.reddit.com/r/ReverseEngineering/comments/1da222/selfmodifying_python_bytecode/). Looking at the [Github](https://github.com/0vercl0k/stuffz/tree/master/Python%27s%20internals) repository was quite instructive and I found picture of the Python bytecode program exposed in CFG form: ![enter image description here](https://i.stack.imgur.com/TKeQM.png) I am wondering if there are tools to perform static analysis on Python bytecode program with some nice features (such as generating the CFG or allowing to manipulate the code, ...) ? Answer:
There are several tools dedicated to Python's bytecode reversing: * [Uncompyle](https://github.com/gstarnberger/uncompyle) and [Uncompyle2](https://github.com/fry/uncompyle2) > > 'uncompyle' converts Python byte-code back into equivalent Python > source. It accepts byte-code from Python version 2.7 only. The generated source is very readable: docstrings, lists, tuples and hashes get pretty-printed. > > > 'uncompyle' may also verify the equivalence of the generated source by > by compiling it and comparing both byte-codes. > 'uncompyle' is based on John Aycock's generic small languages compiler > '[spark](http://www.csr.uvic.ca/~aycock/python/)' and his prior work on > 'decompyle'. > > > * [pyREtic](https://github.com/MyNameIsMeerkat/pyREtic), that is more a powerful framework than a simple program > > pyREtic is an extensible framework to assist in performing various reverse engineering tasks for Python language projects. It assists a reverse engineer in gaining sourcecode (.py's) back from bytecode (.pyc's), in particular it assists when the code that is being reversed has put some effort into trying to stop decompilation using standard toolsets. > > > * [pycdc](https://github.com/zrax/pycdc), which works better than uncompyle, and is simpler to use than pyRetic > > Decompyle++ aims to translate compiled Python byte-code back into valid and human-readable Python source code. While other projects have achieved this with varied success, Decompyle++ is unique in that it seeks to support byte-code from any version of Python. > > > Decompyle++ includes both a byte-code disassembler (pycdas) and a decompiler (pycdc). > > > * The [Manyard](https://bitbucket.org/larry/maynard) framework, which is dedicated to Python3
[pyREtic](http://www.immunitysec.com/resources-freesoftware.shtml) from [Immunity Sec](http://www.immunitysec.com/) can also provide some help in looking into original source code and perform modifications as well. You may be interested in review the capabilities of the tool in this document: **"[pyREtic, In memory reverse engineering for obfuscated Python bytecode](https://www.defcon.org/images/defcon-18/dc-18-presentations/RSmith/DEFCON-18-RSmith-pyREtic.pdf)"** by Rich Smith [PDF]
Question: Recently on [Reddit ReverseEngineering](http://www.reddit.com/r/ReverseEngineering) I stumbled on a [self-modifying code in Python](http://www.reddit.com/r/ReverseEngineering/comments/1da222/selfmodifying_python_bytecode/). Looking at the [Github](https://github.com/0vercl0k/stuffz/tree/master/Python%27s%20internals) repository was quite instructive and I found picture of the Python bytecode program exposed in CFG form: ![enter image description here](https://i.stack.imgur.com/TKeQM.png) I am wondering if there are tools to perform static analysis on Python bytecode program with some nice features (such as generating the CFG or allowing to manipulate the code, ...) ? Answer:
[pyREtic](http://www.immunitysec.com/resources-freesoftware.shtml) from [Immunity Sec](http://www.immunitysec.com/) can also provide some help in looking into original source code and perform modifications as well. You may be interested in review the capabilities of the tool in this document: **"[pyREtic, In memory reverse engineering for obfuscated Python bytecode](https://www.defcon.org/images/defcon-18/dc-18-presentations/RSmith/DEFCON-18-RSmith-pyREtic.pdf)"** by Rich Smith [PDF]
The [Flare-bytecode graph](https://github.com/fireeye/flare-bytecode_graph) project can help with graphical bytecode CFG representation. Taken from the project `README`: > > ... > > It is also possible to create control flow diagrams using GraphViz. The disassembly within the graph can include the output from a simple peephole decompiler. > > > > ``` > import bytecode_graph > def Sample(): > i = 2 + 2 > if i == 4: > print "2 + 2 = %d" % i > else: > print "oops" > > bcg = bytecode_graph.BytecodeGraph(Sample.__code__) > graph = bytecode_graph.Render(bcg, Sample.__code__).dot() > graph.write_png('example_graph.png') > > ``` > > [![program CFG](https://i.stack.imgur.com/TuxNr.png)](https://i.stack.imgur.com/TuxNr.png) > > >
Question: Recently on [Reddit ReverseEngineering](http://www.reddit.com/r/ReverseEngineering) I stumbled on a [self-modifying code in Python](http://www.reddit.com/r/ReverseEngineering/comments/1da222/selfmodifying_python_bytecode/). Looking at the [Github](https://github.com/0vercl0k/stuffz/tree/master/Python%27s%20internals) repository was quite instructive and I found picture of the Python bytecode program exposed in CFG form: ![enter image description here](https://i.stack.imgur.com/TKeQM.png) I am wondering if there are tools to perform static analysis on Python bytecode program with some nice features (such as generating the CFG or allowing to manipulate the code, ...) ? Answer:
There are several tools dedicated to Python's bytecode reversing: * [Uncompyle](https://github.com/gstarnberger/uncompyle) and [Uncompyle2](https://github.com/fry/uncompyle2) > > 'uncompyle' converts Python byte-code back into equivalent Python > source. It accepts byte-code from Python version 2.7 only. The generated source is very readable: docstrings, lists, tuples and hashes get pretty-printed. > > > 'uncompyle' may also verify the equivalence of the generated source by > by compiling it and comparing both byte-codes. > 'uncompyle' is based on John Aycock's generic small languages compiler > '[spark](http://www.csr.uvic.ca/~aycock/python/)' and his prior work on > 'decompyle'. > > > * [pyREtic](https://github.com/MyNameIsMeerkat/pyREtic), that is more a powerful framework than a simple program > > pyREtic is an extensible framework to assist in performing various reverse engineering tasks for Python language projects. It assists a reverse engineer in gaining sourcecode (.py's) back from bytecode (.pyc's), in particular it assists when the code that is being reversed has put some effort into trying to stop decompilation using standard toolsets. > > > * [pycdc](https://github.com/zrax/pycdc), which works better than uncompyle, and is simpler to use than pyRetic > > Decompyle++ aims to translate compiled Python byte-code back into valid and human-readable Python source code. While other projects have achieved this with varied success, Decompyle++ is unique in that it seeks to support byte-code from any version of Python. > > > Decompyle++ includes both a byte-code disassembler (pycdas) and a decompiler (pycdc). > > > * The [Manyard](https://bitbucket.org/larry/maynard) framework, which is dedicated to Python3
The [Flare-bytecode graph](https://github.com/fireeye/flare-bytecode_graph) project can help with graphical bytecode CFG representation. Taken from the project `README`: > > ... > > It is also possible to create control flow diagrams using GraphViz. The disassembly within the graph can include the output from a simple peephole decompiler. > > > > ``` > import bytecode_graph > def Sample(): > i = 2 + 2 > if i == 4: > print "2 + 2 = %d" % i > else: > print "oops" > > bcg = bytecode_graph.BytecodeGraph(Sample.__code__) > graph = bytecode_graph.Render(bcg, Sample.__code__).dot() > graph.write_png('example_graph.png') > > ``` > > [![program CFG](https://i.stack.imgur.com/TuxNr.png)](https://i.stack.imgur.com/TuxNr.png) > > >
Question: If necessary, a factory can access elements of the infrastructure to build an object?. In a particular case, I have an object that I need to add email signature that is stored as a parameter in the configuration layer of the application. Answer:
In DDD, a Factory is at the same architectural level as a Repository, but for creating new objects instead of loading existing objects. So it can call infrastructure services just like the repository.
There is no one correct answer to this problem. If the factory itself is part of your application layer this should be fine. You can also add an application service that hands the email signature down into your domain when needed.
Question: Suppose i have my mailbox configured and i have a special folder for mails with attachments in outlook 2007. What i want to do is i. either configure outlook to save the attachment of mails coming in a specified folder (Mails with Attachments) to specific folder in my computer drive in a desired folder ii. Or if i can write some macro or script to copy those all to my computer location. If so can you please give me quick overview or refer me some where. Answer:
``` double milliseconds = 1000.0 * [[NSDate date] timeIntervalSince1970]; ```
``` CGFloat milliseconds = [NSDate timeIntervalSinceReferenceDate]*1000.0; ```
Question: What is the best way to backup a SQL Server 2005 database nightly? I'm looking for a solution/strategy that would make the database backup file, and place it in an "outgoing" directory. We're wanting our FTP software to move it out to an offsite server. Any suggestions on how to make this work as desired? Answer:
You can do this free. Create a maintenance plan to back up the DB, you can define the location you want to send the file, and add a clean up task. If it's express and you can't use maint plans, use this tool to run the backup job automatically: <http://www.codeplex.com/ExpressMaint> and use a simple VB script to clean up the folder as a windows scheduled task Then create a script to FTP the logs home nightly as windows scheduled task. We do pretty the exact same thing in one of our setups. If the offsite server is on a constant VPN with the DB Server, you could DFS the backup folder. EDIT: If you are wanting to this as "extra" full backup along side local bks, you'll need to use a TSQL statement for the backup job in the plan, and throw in the "COPY\_ONLY" for the backup, so differentials aren't using that as their reference, but your local fulls as planned.
Backup Exec System Recovery will do the backup and FTP it offsite on any schedule
Question: What is the best way to backup a SQL Server 2005 database nightly? I'm looking for a solution/strategy that would make the database backup file, and place it in an "outgoing" directory. We're wanting our FTP software to move it out to an offsite server. Any suggestions on how to make this work as desired? Answer:
An easy script (albiet using an undocumented procedure) is below. This will put it in the default backup directory, but if your service account has rights to other directories you can add that in front of the last question mark. The "init" will over write the last database backup so it doesn't fill up the drive. ``` set quoted_identifier on exec sp_MSforeachdb " if ( '?' not in ( 'tempdb' ) ) begin backup database [?] to disk = '?.bak' with init, stats = 10 end " ```
Backup Exec System Recovery will do the backup and FTP it offsite on any schedule
Question: What is the best way to backup a SQL Server 2005 database nightly? I'm looking for a solution/strategy that would make the database backup file, and place it in an "outgoing" directory. We're wanting our FTP software to move it out to an offsite server. Any suggestions on how to make this work as desired? Answer:
You can do this free. Create a maintenance plan to back up the DB, you can define the location you want to send the file, and add a clean up task. If it's express and you can't use maint plans, use this tool to run the backup job automatically: <http://www.codeplex.com/ExpressMaint> and use a simple VB script to clean up the folder as a windows scheduled task Then create a script to FTP the logs home nightly as windows scheduled task. We do pretty the exact same thing in one of our setups. If the offsite server is on a constant VPN with the DB Server, you could DFS the backup folder. EDIT: If you are wanting to this as "extra" full backup along side local bks, you'll need to use a TSQL statement for the backup job in the plan, and throw in the "COPY\_ONLY" for the backup, so differentials aren't using that as their reference, but your local fulls as planned.
An easy script (albiet using an undocumented procedure) is below. This will put it in the default backup directory, but if your service account has rights to other directories you can add that in front of the last question mark. The "init" will over write the last database backup so it doesn't fill up the drive. ``` set quoted_identifier on exec sp_MSforeachdb " if ( '?' not in ( 'tempdb' ) ) begin backup database [?] to disk = '?.bak' with init, stats = 10 end " ```
Question: What is the best way to backup a SQL Server 2005 database nightly? I'm looking for a solution/strategy that would make the database backup file, and place it in an "outgoing" directory. We're wanting our FTP software to move it out to an offsite server. Any suggestions on how to make this work as desired? Answer:
You can do this free. Create a maintenance plan to back up the DB, you can define the location you want to send the file, and add a clean up task. If it's express and you can't use maint plans, use this tool to run the backup job automatically: <http://www.codeplex.com/ExpressMaint> and use a simple VB script to clean up the folder as a windows scheduled task Then create a script to FTP the logs home nightly as windows scheduled task. We do pretty the exact same thing in one of our setups. If the offsite server is on a constant VPN with the DB Server, you could DFS the backup folder. EDIT: If you are wanting to this as "extra" full backup along side local bks, you'll need to use a TSQL statement for the backup job in the plan, and throw in the "COPY\_ONLY" for the backup, so differentials aren't using that as their reference, but your local fulls as planned.
Logshipping does this well too.
Question: What is the best way to backup a SQL Server 2005 database nightly? I'm looking for a solution/strategy that would make the database backup file, and place it in an "outgoing" directory. We're wanting our FTP software to move it out to an offsite server. Any suggestions on how to make this work as desired? Answer:
An easy script (albiet using an undocumented procedure) is below. This will put it in the default backup directory, but if your service account has rights to other directories you can add that in front of the last question mark. The "init" will over write the last database backup so it doesn't fill up the drive. ``` set quoted_identifier on exec sp_MSforeachdb " if ( '?' not in ( 'tempdb' ) ) begin backup database [?] to disk = '?.bak' with init, stats = 10 end " ```
Logshipping does this well too.
Question: I have a problem when trying removing a file with name something like `-h_some_file_name`, this is because of generated script that I made and forget to check the prefix. If I run the command `rm '-h_some_file_name'` it return an error `rm: invalid option -- 'h'`. If I try to change the name and then remove it using `mv '-h_some_file_name' new_filename` it return `mv: invalid option -- 'h'` **Question:** How to remove a file with name like `-h_some_file_name` in shell? if using gui I can right click and move to trash, but in shell only returns an error Answer:
Just: ``` rm -- -h_some_file_name ``` Or: ``` rm ./-h_some_file_name ``` See the manpage of `rm`: ``` To remove a file whose name starts with a `-', for example `-foo', use one of these commands: rm -- -foo rm ./-foo ``` The `--` argument tells `rm` that all following argument should not be treated as parameters. A variety of other Linux/Unix command line tools support that argument. This interpretation of `--` follows the POSIX argument parsing conventions1). The `mv` utility also supports it: ``` mv -- -h_some_file_name new_file_name ``` --- 1) [The Open Group Base Specifications Issue 7, IEEE Std 1003.1, Guideline 10](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html)
You can use wildcards. Here in this case you can use '\*' wildcard. Go to the directory where files of this type is to be deleted or you need to mention the complete path in the command. After setting to the terminal prompt to your directory, type in the following ``` rm ./-h* ``` For little bit more information you can see this link: <http://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm> For indepth information follow some book related to bash.
Question: After upgrading to 18.04 every time I start Ubuntu and the fire up Firefox I get a "Sorry. We’re having trouble getting your pages back." How to I fix this? Answer:
This should clear it ``` # sudo systemd-resolve --flush-cache ``` You can check with ``` # sudo systemd-resolve --statistics ``` * it should show 0 in Current cache size ``` DNSSEC supported by current servers: no Transactions Current Transactions: 0 Total Transactions: 93750 Cache Current Cache Size: 0 Cache Hits: 18686 Cache Misses: 28576 DNSSEC Verdicts Secure: 0 Insecure: 0 Bogus: 0 Indeterminate: 0 ```
Maybe this version also has two (2) DNS caches, like Ubuntu 20.10. Please check the full tutorial to flush DNS caches: <https://askubuntu.com/a/1315569/136919>
Question: My SQL Server table has a column defined as: ``` TicketNo varchar(5) ``` The rows in this table are inserted by some bulk load files from different sources. Now, depending on who prepared the bulk load input files, sometimes `TicketNo` has leading 0s, sometimes not. How can I enforce INSERTS to the table so that `TicketNo` will always be set with leading zeros, something like: ``` TicketNo = RIGHT('00000'+TicketNo, 5) ``` Answer:
You can use a char(5) column with a check constraint. ``` create table YourTable ( TicketNo char(5) check (patindex('%[^0-9]%', TicketNo) = 0) ) ``` Update: Using [this answer](https://dba.stackexchange.com/a/34731/2103) by [Martin Smith](https://stackoverflow.com/users/73226/martin-smith) it could look like this instead to make sure there are only 0-9 allowed. ``` create table YourTable ( TicketNo char(5) collate Latin1_General_CS_AS check (patindex('%[^0123456789]%', TicketNo) = 0) ) ```
How you enforce it is a tricky question. My first through would be to create a stored procedure and force all inserts to take place through that. Then you could use rs's solutions. Other than that you can create an insert/update trigger that checks for leading zeros.
Question: I have a program in c. Input of this program is the address of a file. This program gets the complete address of input file like d:\bin\files\examples\data\file.txt. How can I correct the program that gets input in form of data\file.txt ? and the d:\bin\files\examples\ add itself. Answer:
Ok, here is a little class that can parse your xml: ``` public class Parser { public List<Dictionary<string, object>> Parse(XElement root) { var result = new List<Dictionary<string, object>>(); foreach (var e in root.Elements()) { if (e.Name == "dict") { result.Add(ParseDict(e)); } } return result; } private Dictionary<string, object> ParseDict(XElement element) { var dict = new Dictionary<string, object>(); foreach (var subelement in element.Elements()) { if (subelement.Name == "key") { dict.Add(subelement.Value, ParseValue(subelement.ElementsAfterSelf().First())); } } return dict; } private object ParseValue(XElement valueElement) { if (valueElement.Name == "string") { return valueElement.Value; } if (valueElement.Name == "array") { return new List<object>(valueElement.Elements().Select(e => ParseValue(e))); } if (valueElement.Name == "dict") { return ParseDict(valueElement); } if (valueElement.Name == "true") { return true; } if (valueElement.Name == "false") { return false; } return null; } } ``` It is used like this: ``` var parser = new Parser(); var doc = XDocument.Load(<path to xml file>); var result = parser.Parse(doc.Root); ``` The parser is very crude and makes assumptions about the xml. And as pointed out in earlier comments, it is not the best way to use xml like this, where position of elements has significance. Also the use of "object" in the parser isn't a good solution, but the parser gets a lot more advanced if you want to avoid that.
I used Hakan's Parser class almost straight out of the box: I needed an integer element but no true or false - simple edits. This snippet might help people test their code. I have renamed some of Hakan's symbols to fit my project. ``` private void Button_Click_1(object sender, RoutedEventArgs e) { List<Dictionary<string, object>> topicsList = topicParser.Parse(topicsXDocument.Root); Console.WriteLine("The Topics List contains:"); foreach (Dictionary<string, object> topic in topicsList) { foreach (KeyValuePair<string, object> element in topic) { string name = element.Key; object content = element.Value; Console.WriteLine("Key: {0}, Value: {1}", name, content.ToString()); } } } ```
Question: The set of complex numbers can be defined using the reals: $$\mathbb{C}=\{a+bi\,|\,a,b\in\mathbb{R}\}.$$ Could I do the opposite and define the reals using the complex numbers? $$\mathbb{R}=\{z\,|\,z\in\mathbb{C},\,\operatorname{Im}(z)=0\}.$$ Answer:
Yes, you could, in principle. The reason we usually go the other way is because we already know what the reals are (namely "Cauchy sequences of rationals", or "Dedekind cuts"), so going $\mathbb{R}$ to $\mathbb{C}$ allows us to build a more complicated object from something we already know about. There's no reason to go $\mathbb{C}$ to $\mathbb{R}$, because in order to construct $\mathbb{C}$ you must have constructed $\mathbb{R}$ already. So if you have somehow already defined $\mathbb{C}$ then you could use your definition as a definition of $\mathbb{R}$; but otherwise you can't, because your "definition" would be circular.
You could, see the caveat by Patrick, though. Another way would be to say $$\Bbb R=\{z \in \Bbb C: \bar{z}=z\}$$ or $$\Bbb R=\{z \in \Bbb C: |z|=z \lor |z|=-z \}$$ and a few others.
Question: The set of complex numbers can be defined using the reals: $$\mathbb{C}=\{a+bi\,|\,a,b\in\mathbb{R}\}.$$ Could I do the opposite and define the reals using the complex numbers? $$\mathbb{R}=\{z\,|\,z\in\mathbb{C},\,\operatorname{Im}(z)=0\}.$$ Answer:
Yes, you could, in principle. The reason we usually go the other way is because we already know what the reals are (namely "Cauchy sequences of rationals", or "Dedekind cuts"), so going $\mathbb{R}$ to $\mathbb{C}$ allows us to build a more complicated object from something we already know about. There's no reason to go $\mathbb{C}$ to $\mathbb{R}$, because in order to construct $\mathbb{C}$ you must have constructed $\mathbb{R}$ already. So if you have somehow already defined $\mathbb{C}$ then you could use your definition as a definition of $\mathbb{R}$; but otherwise you can't, because your "definition" would be circular.
Yes, you can represent the real numbers like this. If you are pedantic, you may want to distinguish between the real number $x$ and the complex number $x + 0i$. If this is a concern, you can write $$ \mathbb{R} = \bigl\{ \mathrm{Re}(z) \bigm| z \in \mathbb{C} \bigr\}. $$
Question: If I have an entity such as the following: ``` @Entity public class Customer { private Address address; } ``` And the Address is also an entity: ``` @Entity public class Address {...} ``` Does persisting the Customer in turn persist its contained Address? Or is this not possible at all? The idea was basically to have a main entity that consists of its fields, some of which are entities themselves that will be stored in individual tables. Some of the fields of Customer are unique in that I also would like a Customer table for that data. Unless I'm just missing it, I haven't been able to find this answer. This was something I was just curious about and I'm not currently on a machine where I can try it, so I wanted to ask first. Thanks in advance. Answer:
**Graft** uses Mercurial internal merging, while **transplant** relies on patch mechanism. Therefore **graft** should be able to handle three-way-merges better than **transplant** currently does.
From the documentation of hg graft it looks like opposite to the transplant extension graft only handles branches within the same repository but can't handle different repositories.
Question: I want to create a text area on the mouse hover in given link. What I've tried is there in this [fiddle code.](http://jsfiddle.net/viralshah/nmZb9/5/) But I want to create text area dynamically when mouse over on the link. This text area will set on the **right side** (when click on the link) and also declare some fields which supports **CSS for that text area** so, can able to modify the style of text area. Can anyone help me on this? Thanks Answer:
TL:DR ----- For OAuth 2 tokens if you login... * At `login.salesforce.com` use <https://login.salesforce.com/services/oauth2/token> * At `test.salesforce.com` use <https://test.salesforce.com/services/oauth2/token> Story: ------ 1. I was following [Salesforce "Set Up OAuth 2.0"](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/quickstart_oauth.htm) 2. Credentials were correct (many character by character checks) 3. When I'd call `curl https://login.salesforce.com/services/oauth2/token -d "...credentials..."` it still failed with: `{"error":"invalid_grant","error_description":"authentication failure"}` Solution: --------- Realized there are different OAuth environments when reading [Digging Deeper into OAuth 2.0 in Salesforce](https://help.salesforce.com/articleView?id=remoteaccess_authenticate_overview.htm) specifically (emphasis added): > > ### OAuth 2.0 Authentication Endpoints > > > OAuth endpoints are the URLs that you use to make OAuth authentication requests to Salesforce. When your application makes an authentication request, make sure you’re using the correct Salesforce OAuth endpoint. The primary endpoints are: > > > * Authorization—<https://login.salesforce.com/services/oauth2/authorize> > * Token—<https://login.salesforce.com/services/oauth2/token> > * Revoke—<https://login.salesforce.com/services/oauth2/revoke> (see Revoke OAuth Tokens for details on revoking access) > > > Instead of ***login.salesforce.com***, customers can also use the ***My Domain***, ***community***, or ***test.salesforce.com*** (sandbox) domains in these endpoints. > > > Fix --- Because I logged into my environment via `test.salesforce.com` switching to `curl https://test.salesforce.com/services/oauth2/token -d "...credentials..."` resulted in a **"Congrats! (>^\_^)> Give OAuth token response"**
Make sure your password *only* has alphanumeric characters in it.
Question: I want to create a text area on the mouse hover in given link. What I've tried is there in this [fiddle code.](http://jsfiddle.net/viralshah/nmZb9/5/) But I want to create text area dynamically when mouse over on the link. This text area will set on the **right side** (when click on the link) and also declare some fields which supports **CSS for that text area** so, can able to modify the style of text area. Can anyone help me on this? Thanks Answer:
We had this issue as well. Check your `Connected App` settings - under `Selected OAuth Scopes`, you may need to adjust the selected permissions. Our app primarily uses *Chatter*, so we had to add both: * Access and manage your Chatter feed (`chatter_api`) * Perform requests on your behalf at any time (`refresh_token`). Again, your mileage may vary but try different combinations of permissions based on what your Application does/needs. Additionally, the actual **`invalid_grant`** error seems to occur due to **IP restrictions**. Ensure that the server's IP address that is running the OAuth authentication code is allowed. I found that if the SFDC environment has IP restriction setting `Enforce IP restrictions` set (*`Setup` -> `Administer` -> `Manage Apps` -> `Connected Apps`*), then each *User Profile* must have the allowed IP addresses as well.
I had this problem and after trying several failed tutorials I came across a post that said Salesforce won't accept a password with special characters in it (!, @ ,#). I changed my password in Salesforce to one without special characters and finally got it to work.
Question: I want to create a text area on the mouse hover in given link. What I've tried is there in this [fiddle code.](http://jsfiddle.net/viralshah/nmZb9/5/) But I want to create text area dynamically when mouse over on the link. This text area will set on the **right side** (when click on the link) and also declare some fields which supports **CSS for that text area** so, can able to modify the style of text area. Can anyone help me on this? Thanks Answer:
To whitelist an IP address range follow these steps: 1. Click `Setup` in the top-right 2. Select `Administer` > `Security Controls` > `Network Access` from the left navigation 3. Click `New` 4. Add your ip address range 5. Click `Save`
I tried many solutions above which did not work for me. However the trick that actually worked for me was to stop using curl and to use [postman](https://www.getpostman.com/) application to make the request instead. By replicating the request in postman, with a POST request and the following params 1. grant\_type 2. client\_id 3. client\_secret 4. username 5. password This solved the issue for me. Just posting it here in case there are others who have tried all the possible solutions with no avail (like I did).
Question: I want to create a text area on the mouse hover in given link. What I've tried is there in this [fiddle code.](http://jsfiddle.net/viralshah/nmZb9/5/) But I want to create text area dynamically when mouse over on the link. This text area will set on the **right side** (when click on the link) and also declare some fields which supports **CSS for that text area** so, can able to modify the style of text area. Can anyone help me on this? Thanks Answer:
To whitelist an IP address range follow these steps: 1. Click `Setup` in the top-right 2. Select `Administer` > `Security Controls` > `Network Access` from the left navigation 3. Click `New` 4. Add your ip address range 5. Click `Save`
I was banging my head against the desk trying to get this to work. Turns out my issue was copying and pasting, which messed up the " character. I went and manually typed " pasted that into the command line and then it worked.
Question: I want to create a text area on the mouse hover in given link. What I've tried is there in this [fiddle code.](http://jsfiddle.net/viralshah/nmZb9/5/) But I want to create text area dynamically when mouse over on the link. This text area will set on the **right side** (when click on the link) and also declare some fields which supports **CSS for that text area** so, can able to modify the style of text area. Can anyone help me on this? Thanks Answer:
To whitelist an IP address range follow these steps: 1. Click `Setup` in the top-right 2. Select `Administer` > `Security Controls` > `Network Access` from the left navigation 3. Click `New` 4. Add your ip address range 5. Click `Save`
Make sure your password *only* has alphanumeric characters in it.
Question: I want to create a text area on the mouse hover in given link. What I've tried is there in this [fiddle code.](http://jsfiddle.net/viralshah/nmZb9/5/) But I want to create text area dynamically when mouse over on the link. This text area will set on the **right side** (when click on the link) and also declare some fields which supports **CSS for that text area** so, can able to modify the style of text area. Can anyone help me on this? Thanks Answer:
TL:DR ----- For OAuth 2 tokens if you login... * At `login.salesforce.com` use <https://login.salesforce.com/services/oauth2/token> * At `test.salesforce.com` use <https://test.salesforce.com/services/oauth2/token> Story: ------ 1. I was following [Salesforce "Set Up OAuth 2.0"](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/quickstart_oauth.htm) 2. Credentials were correct (many character by character checks) 3. When I'd call `curl https://login.salesforce.com/services/oauth2/token -d "...credentials..."` it still failed with: `{"error":"invalid_grant","error_description":"authentication failure"}` Solution: --------- Realized there are different OAuth environments when reading [Digging Deeper into OAuth 2.0 in Salesforce](https://help.salesforce.com/articleView?id=remoteaccess_authenticate_overview.htm) specifically (emphasis added): > > ### OAuth 2.0 Authentication Endpoints > > > OAuth endpoints are the URLs that you use to make OAuth authentication requests to Salesforce. When your application makes an authentication request, make sure you’re using the correct Salesforce OAuth endpoint. The primary endpoints are: > > > * Authorization—<https://login.salesforce.com/services/oauth2/authorize> > * Token—<https://login.salesforce.com/services/oauth2/token> > * Revoke—<https://login.salesforce.com/services/oauth2/revoke> (see Revoke OAuth Tokens for details on revoking access) > > > Instead of ***login.salesforce.com***, customers can also use the ***My Domain***, ***community***, or ***test.salesforce.com*** (sandbox) domains in these endpoints. > > > Fix --- Because I logged into my environment via `test.salesforce.com` switching to `curl https://test.salesforce.com/services/oauth2/token -d "...credentials..."` resulted in a **"Congrats! (>^\_^)> Give OAuth token response"**
I was banging my head against the desk trying to get this to work. Turns out my issue was copying and pasting, which messed up the " character. I went and manually typed " pasted that into the command line and then it worked.
Question: I want to create a text area on the mouse hover in given link. What I've tried is there in this [fiddle code.](http://jsfiddle.net/viralshah/nmZb9/5/) But I want to create text area dynamically when mouse over on the link. This text area will set on the **right side** (when click on the link) and also declare some fields which supports **CSS for that text area** so, can able to modify the style of text area. Can anyone help me on this? Thanks Answer:
We had this issue as well. Check your `Connected App` settings - under `Selected OAuth Scopes`, you may need to adjust the selected permissions. Our app primarily uses *Chatter*, so we had to add both: * Access and manage your Chatter feed (`chatter_api`) * Perform requests on your behalf at any time (`refresh_token`). Again, your mileage may vary but try different combinations of permissions based on what your Application does/needs. Additionally, the actual **`invalid_grant`** error seems to occur due to **IP restrictions**. Ensure that the server's IP address that is running the OAuth authentication code is allowed. I found that if the SFDC environment has IP restriction setting `Enforce IP restrictions` set (*`Setup` -> `Administer` -> `Manage Apps` -> `Connected Apps`*), then each *User Profile* must have the allowed IP addresses as well.
You can call your APEX controller using [Postman](https://www.getpostman.com) if you enter the Consumer Key and Consumer Secret in the Access Token settings - you don't need the Security Token for this. Set up the Authorization like this screenshot... [Postman OAuth 2.0](https://i.stack.imgur.com/uf2EZ.png) And enter your credentials on the window after hitting the Get New Access Token button... [Get Access Token](https://i.stack.imgur.com/CbPeK.png) Then hit the Request Token button to generate a token, then hit the Use Token button and it will populate the Access Token field on the Authorization tab where you hit the Get New Access Token button.
Question: I want to create a text area on the mouse hover in given link. What I've tried is there in this [fiddle code.](http://jsfiddle.net/viralshah/nmZb9/5/) But I want to create text area dynamically when mouse over on the link. This text area will set on the **right side** (when click on the link) and also declare some fields which supports **CSS for that text area** so, can able to modify the style of text area. Can anyone help me on this? Thanks Answer:
To whitelist an IP address range follow these steps: 1. Click `Setup` in the top-right 2. Select `Administer` > `Security Controls` > `Network Access` from the left navigation 3. Click `New` 4. Add your ip address range 5. Click `Save`
You can call your APEX controller using [Postman](https://www.getpostman.com) if you enter the Consumer Key and Consumer Secret in the Access Token settings - you don't need the Security Token for this. Set up the Authorization like this screenshot... [Postman OAuth 2.0](https://i.stack.imgur.com/uf2EZ.png) And enter your credentials on the window after hitting the Get New Access Token button... [Get Access Token](https://i.stack.imgur.com/CbPeK.png) Then hit the Request Token button to generate a token, then hit the Use Token button and it will populate the Access Token field on the Authorization tab where you hit the Get New Access Token button.
Question: This is a comprehension cloze question for 11 year olds: > > His only hope for cure was a bone marrow transplant. His brother was chosen to donate some of his bone marrow. The \_\_\_\_\_\_\_\_ would take place in the States. > > > Was told that 'transplant' and 'procedure' can be accepted but 'operation' cannot because patient won't be cut. Is it really so? Answer:
The relevant definition of *operation* in *Merriam-Webster's Eleventh Collegiate Dictionary* (2003) doesn't mention cutting as a prerequisite: > > **operation** *n* ... **4 :** a procedure performed on a living body usu. with instruments esp. for the repair of damage or the restoration of health > > > Under the *Eleventh Collegiate*'s definition, a bone marrow transplant would certainly be an operation; in fact, it might be viewed as two operations—one on the donor and one on the recipient. Any more-precise notion of the meaning of *operation* as a medical term of art involves a more sophisticated understanding of the term than Merriam-Webster seems to possess, and I think it is asking a lot of an eleven-year-old to be expected to possess it. This is not to say that the operation in question may not also be characterized as a procedure.
An operation is generally understood to be a procedure that is performed by a surgeon. And a surgeon is the person who generally does the cutting, as you put it. So with that in mind, I would agree with the person who gave you the advice.
Question: This is a comprehension cloze question for 11 year olds: > > His only hope for cure was a bone marrow transplant. His brother was chosen to donate some of his bone marrow. The \_\_\_\_\_\_\_\_ would take place in the States. > > > Was told that 'transplant' and 'procedure' can be accepted but 'operation' cannot because patient won't be cut. Is it really so? Answer:
As answered by @SvenYargs, "operation" is fine. However, you may say: > > "The **transplantation** would take place in the States". > > > Comparing the 2 nouns "transplant" and "transplantation", my feeling is that the noun "transplant" better fits to the therapeutic method and that "transplatation" relates more to the operation.
An operation is generally understood to be a procedure that is performed by a surgeon. And a surgeon is the person who generally does the cutting, as you put it. So with that in mind, I would agree with the person who gave you the advice.
Question: This is a comprehension cloze question for 11 year olds: > > His only hope for cure was a bone marrow transplant. His brother was chosen to donate some of his bone marrow. The \_\_\_\_\_\_\_\_ would take place in the States. > > > Was told that 'transplant' and 'procedure' can be accepted but 'operation' cannot because patient won't be cut. Is it really so? Answer:
Eh, kinda. ---------- If these were all given as multiple choice answers, > > A. Transplant B. Procedure C. Operation D. [Sth Obviously Wrong] > > > then—having just looked up [what actually occurs during a bone marrow transplant](https://www.hopkinsmedicine.org/health/treatment-tests-and-therapies/bone-marrow-transplantation)—**B *is* the best answer**. A isn't wrong but repeats the word too quickly to sound as good as a synonym. C is what I would've chosen, based on my misunderstanding that marrow was actually transplanted from a bone in one person to a bone in another. As is, apparently the only thing they do is extract marrow through a long needle and then inject it into the recipient's bloodstream, waiting weeks for it to find its way to some bone and start doing something useful. That really does comport better with *procedure* than *operation*, although [*operation* is not actually synonymous with *surgery*](http://www.differencebetween.net/science/health/difference-between-surgery-and-operation) and it's a ridiculously fine point to make with 11-year-old ESL students, unless it's a premed magnet program for [Doogie Howser](https://de.wikipedia.org/wiki/Doogie_Howser,_M.D.) clones.
An operation is generally understood to be a procedure that is performed by a surgeon. And a surgeon is the person who generally does the cutting, as you put it. So with that in mind, I would agree with the person who gave you the advice.
Question: This is a comprehension cloze question for 11 year olds: > > His only hope for cure was a bone marrow transplant. His brother was chosen to donate some of his bone marrow. The \_\_\_\_\_\_\_\_ would take place in the States. > > > Was told that 'transplant' and 'procedure' can be accepted but 'operation' cannot because patient won't be cut. Is it really so? Answer:
The relevant definition of *operation* in *Merriam-Webster's Eleventh Collegiate Dictionary* (2003) doesn't mention cutting as a prerequisite: > > **operation** *n* ... **4 :** a procedure performed on a living body usu. with instruments esp. for the repair of damage or the restoration of health > > > Under the *Eleventh Collegiate*'s definition, a bone marrow transplant would certainly be an operation; in fact, it might be viewed as two operations—one on the donor and one on the recipient. Any more-precise notion of the meaning of *operation* as a medical term of art involves a more sophisticated understanding of the term than Merriam-Webster seems to possess, and I think it is asking a lot of an eleven-year-old to be expected to possess it. This is not to say that the operation in question may not also be characterized as a procedure.
As answered by @SvenYargs, "operation" is fine. However, you may say: > > "The **transplantation** would take place in the States". > > > Comparing the 2 nouns "transplant" and "transplantation", my feeling is that the noun "transplant" better fits to the therapeutic method and that "transplatation" relates more to the operation.
Question: This is a comprehension cloze question for 11 year olds: > > His only hope for cure was a bone marrow transplant. His brother was chosen to donate some of his bone marrow. The \_\_\_\_\_\_\_\_ would take place in the States. > > > Was told that 'transplant' and 'procedure' can be accepted but 'operation' cannot because patient won't be cut. Is it really so? Answer:
The relevant definition of *operation* in *Merriam-Webster's Eleventh Collegiate Dictionary* (2003) doesn't mention cutting as a prerequisite: > > **operation** *n* ... **4 :** a procedure performed on a living body usu. with instruments esp. for the repair of damage or the restoration of health > > > Under the *Eleventh Collegiate*'s definition, a bone marrow transplant would certainly be an operation; in fact, it might be viewed as two operations—one on the donor and one on the recipient. Any more-precise notion of the meaning of *operation* as a medical term of art involves a more sophisticated understanding of the term than Merriam-Webster seems to possess, and I think it is asking a lot of an eleven-year-old to be expected to possess it. This is not to say that the operation in question may not also be characterized as a procedure.
Eh, kinda. ---------- If these were all given as multiple choice answers, > > A. Transplant B. Procedure C. Operation D. [Sth Obviously Wrong] > > > then—having just looked up [what actually occurs during a bone marrow transplant](https://www.hopkinsmedicine.org/health/treatment-tests-and-therapies/bone-marrow-transplantation)—**B *is* the best answer**. A isn't wrong but repeats the word too quickly to sound as good as a synonym. C is what I would've chosen, based on my misunderstanding that marrow was actually transplanted from a bone in one person to a bone in another. As is, apparently the only thing they do is extract marrow through a long needle and then inject it into the recipient's bloodstream, waiting weeks for it to find its way to some bone and start doing something useful. That really does comport better with *procedure* than *operation*, although [*operation* is not actually synonymous with *surgery*](http://www.differencebetween.net/science/health/difference-between-surgery-and-operation) and it's a ridiculously fine point to make with 11-year-old ESL students, unless it's a premed magnet program for [Doogie Howser](https://de.wikipedia.org/wiki/Doogie_Howser,_M.D.) clones.
Question: This is a comprehension cloze question for 11 year olds: > > His only hope for cure was a bone marrow transplant. His brother was chosen to donate some of his bone marrow. The \_\_\_\_\_\_\_\_ would take place in the States. > > > Was told that 'transplant' and 'procedure' can be accepted but 'operation' cannot because patient won't be cut. Is it really so? Answer:
Eh, kinda. ---------- If these were all given as multiple choice answers, > > A. Transplant B. Procedure C. Operation D. [Sth Obviously Wrong] > > > then—having just looked up [what actually occurs during a bone marrow transplant](https://www.hopkinsmedicine.org/health/treatment-tests-and-therapies/bone-marrow-transplantation)—**B *is* the best answer**. A isn't wrong but repeats the word too quickly to sound as good as a synonym. C is what I would've chosen, based on my misunderstanding that marrow was actually transplanted from a bone in one person to a bone in another. As is, apparently the only thing they do is extract marrow through a long needle and then inject it into the recipient's bloodstream, waiting weeks for it to find its way to some bone and start doing something useful. That really does comport better with *procedure* than *operation*, although [*operation* is not actually synonymous with *surgery*](http://www.differencebetween.net/science/health/difference-between-surgery-and-operation) and it's a ridiculously fine point to make with 11-year-old ESL students, unless it's a premed magnet program for [Doogie Howser](https://de.wikipedia.org/wiki/Doogie_Howser,_M.D.) clones.
As answered by @SvenYargs, "operation" is fine. However, you may say: > > "The **transplantation** would take place in the States". > > > Comparing the 2 nouns "transplant" and "transplantation", my feeling is that the noun "transplant" better fits to the therapeutic method and that "transplatation" relates more to the operation.
Question: I have a digital elevation model and a shapefile containing point features for the location of wind turbines. These two layers appear to be aligned in QGIS but when I open them in openWind, they are not aligned. I am guessing this has something to do with CRS but I am unsure how to align these layers? Answer:
You may need to include a [Collect Values](http://resources.arcgis.com/en/help/main/10.2/index.html#//004000000005000000) tool between the Iterate output and the next processing step (CreateFeaturesFromText). [Example from ArcMap's Help Page](http://resources.arcgis.com/en/help/main/10.2/index.html#/Examples_of_using_Model_Only_tools_in_ModelBuilder/00400000001m000000/GUID-9F197B15-27F6-46EA-BAC5-7A722C5A3C4E/) (in a different model, so just illustrating the principle) ![enter image description here](https://i.stack.imgur.com/gYMiq.png)
It appears as though I had to use the Iterate Tables rather than Iterate Files, and then it worked just fine.
Question: I have a `Vote` domain class from my grails application containing properties like `article_id` and `note` I want to HQL query the `Vote` domain class in order to retrieve the 5 best rated articles having at least 10 votes. I tried : ``` SELECT v.article_id, avg(v.note), count(*) FROM vote v where count(*) >= 10 group by v.article_id order by avg(v.note) desc limit 5; ``` But unfortunately the insertion of `where count(*) >= 10` throws an error. How can I do that in a simple way? Thank you for your help. Answer:
From the comments, you say that you are inserting these into a map like so: ``` modelMap[id] = Model(id, model, SOLDIER); ``` `std::map::operator[]` requires that the mapped type be default constructible. When you call `operator[]` on a map, if there is no mapped value with the given key, the map default constructs a new object, maps it to the given key, and returns a reference to that object. You can get around this by using `std::map::insert()`: ``` modelMap.insert(std::make_pair(id, Model(id, model, SOLDIER)); ```
You do: ``` Model soldier(id, model, SOLDIER); //1 modelMap[id] = soldier; //2 ``` What happens here? 1. New object is created, using consructor you have provided. 2. The ~~so-called copy-constructor~~ copy assignment operator is called to copy `soldier` to `modelMap[id]`. You haven't defined your own ~~copy-constructor~~ copy assignment operator so one default is created for you by compiler, it is in most cases just copying byte-by-byte whole data-structure to the new memory address. However you have vector of pointers in your class, so compiler should call copy-constructor of vector... And I don't know (maybe someone with greater experience would know exactly what happens now) what is the result ~~copy-constructor, I don't know if standard clearly defines 'default copy-constructor'.~~ So it is possible, that the whole structure is copied to the `modelMap[]` but with some random data. ~~If you create a copy-constructor (its declaration in your case will look something like `Model::Model(const Model& myModel);`, copy-constructor always takes reference to object of its type as an argument)~~ If you override copy assignment operator (best, if you make both things), you have control over everything that is done while copying your object to another variable/object. Download eg. Bruce Eckel's *Thinking in C++, V. 1* [1], or search somewhere on the Net how to do it (probably this will be good, didn't read whole article, <http://www.learncpp.com/cpp-tutorial/911-the-copy-constructor-and-overloading-the-assignment-operator/>). [1] Downloadable on his website, mindview.net, as a new user I can paste only one link, so cannot link it here myself :P.
Question: I have a `Vote` domain class from my grails application containing properties like `article_id` and `note` I want to HQL query the `Vote` domain class in order to retrieve the 5 best rated articles having at least 10 votes. I tried : ``` SELECT v.article_id, avg(v.note), count(*) FROM vote v where count(*) >= 10 group by v.article_id order by avg(v.note) desc limit 5; ``` But unfortunately the insertion of `where count(*) >= 10` throws an error. How can I do that in a simple way? Thank you for your help. Answer:
This lines: ``` modelMap[id] = soldier; ``` First default constructs the Model inside the map. The returned reference is then used with the assignment operator to copy the value of soldier into the value contained inside the map. To test if it is working try: ``` Model soldier(id, model, SOLDIER); std::cout << "TYPE(" << soldier.type << ") HEALTH(" << soldier.health << ")" std::endl; modelMap[id] = soldier; std::cout << "TYPE(" << modelMap[id].type << " HEALTH(" << modelMap[id].health << ")" std::endl; ``` If your class is not designed to be default constructible. Then do not have a default constructor (this will just lead to problems). Declare a default constructor in the private part of the class (no need for a body). Without a default constructor you will not be able to use the operator[] on map. But you can get around this by using insert: ``` modelMap.insert(std::map<XX, Model>::value_type(id, soldier)); ```
From the comments, you say that you are inserting these into a map like so: ``` modelMap[id] = Model(id, model, SOLDIER); ``` `std::map::operator[]` requires that the mapped type be default constructible. When you call `operator[]` on a map, if there is no mapped value with the given key, the map default constructs a new object, maps it to the given key, and returns a reference to that object. You can get around this by using `std::map::insert()`: ``` modelMap.insert(std::make_pair(id, Model(id, model, SOLDIER)); ```
Question: I have a `Vote` domain class from my grails application containing properties like `article_id` and `note` I want to HQL query the `Vote` domain class in order to retrieve the 5 best rated articles having at least 10 votes. I tried : ``` SELECT v.article_id, avg(v.note), count(*) FROM vote v where count(*) >= 10 group by v.article_id order by avg(v.note) desc limit 5; ``` But unfortunately the insertion of `where count(*) >= 10` throws an error. How can I do that in a simple way? Thank you for your help. Answer:
This lines: ``` modelMap[id] = soldier; ``` First default constructs the Model inside the map. The returned reference is then used with the assignment operator to copy the value of soldier into the value contained inside the map. To test if it is working try: ``` Model soldier(id, model, SOLDIER); std::cout << "TYPE(" << soldier.type << ") HEALTH(" << soldier.health << ")" std::endl; modelMap[id] = soldier; std::cout << "TYPE(" << modelMap[id].type << " HEALTH(" << modelMap[id].health << ")" std::endl; ``` If your class is not designed to be default constructible. Then do not have a default constructor (this will just lead to problems). Declare a default constructor in the private part of the class (no need for a body). Without a default constructor you will not be able to use the operator[] on map. But you can get around this by using insert: ``` modelMap.insert(std::map<XX, Model>::value_type(id, soldier)); ```
You do: ``` Model soldier(id, model, SOLDIER); //1 modelMap[id] = soldier; //2 ``` What happens here? 1. New object is created, using consructor you have provided. 2. The ~~so-called copy-constructor~~ copy assignment operator is called to copy `soldier` to `modelMap[id]`. You haven't defined your own ~~copy-constructor~~ copy assignment operator so one default is created for you by compiler, it is in most cases just copying byte-by-byte whole data-structure to the new memory address. However you have vector of pointers in your class, so compiler should call copy-constructor of vector... And I don't know (maybe someone with greater experience would know exactly what happens now) what is the result ~~copy-constructor, I don't know if standard clearly defines 'default copy-constructor'.~~ So it is possible, that the whole structure is copied to the `modelMap[]` but with some random data. ~~If you create a copy-constructor (its declaration in your case will look something like `Model::Model(const Model& myModel);`, copy-constructor always takes reference to object of its type as an argument)~~ If you override copy assignment operator (best, if you make both things), you have control over everything that is done while copying your object to another variable/object. Download eg. Bruce Eckel's *Thinking in C++, V. 1* [1], or search somewhere on the Net how to do it (probably this will be good, didn't read whole article, <http://www.learncpp.com/cpp-tutorial/911-the-copy-constructor-and-overloading-the-assignment-operator/>). [1] Downloadable on his website, mindview.net, as a new user I can paste only one link, so cannot link it here myself :P.
Question: i have list of element when i click in one of them, i fill the template then i copy it to the new DIV, i got an empty template, when i use `$scope.$apply()` i got an error. ``` $scope.tache_list.forEach(element => { $scope.var1 = element; $scope.$apply(); $('#div2').append($("#div1").html()); }); ``` i got `Error $rootScope:inprog` , what i can do ? [![Error rootScope](https://i.stack.imgur.com/geK6t.png)](https://i.stack.imgur.com/geK6t.png) Answer:
Wrap your $scope.$apply call inside a $timeout function. ``` $timeout(function(){ $scope.$apply() }); ``` Reason: Digest cycle will be moved to event loop and execute when the existing cycle completes.
Please take a look at the following [article](http://jimhoskins.com/2012/12/17/angularjs-and-apply.html) about $digest and $apply Your `inprogress` error is because you call `$apply()` from inside an `$apply block`. You only want to call the $apply from `outside` angular code that starts a new turn. So if you have a `setTimeout()` in your forEach you can call $apply inside the setTimeout to tell angular you want it to update.
Question: i have list of element when i click in one of them, i fill the template then i copy it to the new DIV, i got an empty template, when i use `$scope.$apply()` i got an error. ``` $scope.tache_list.forEach(element => { $scope.var1 = element; $scope.$apply(); $('#div2').append($("#div1").html()); }); ``` i got `Error $rootScope:inprog` , what i can do ? [![Error rootScope](https://i.stack.imgur.com/geK6t.png)](https://i.stack.imgur.com/geK6t.png) Answer:
Please take a look at the following [article](http://jimhoskins.com/2012/12/17/angularjs-and-apply.html) about $digest and $apply Your `inprogress` error is because you call `$apply()` from inside an `$apply block`. You only want to call the $apply from `outside` angular code that starts a new turn. So if you have a `setTimeout()` in your forEach you can call $apply inside the setTimeout to tell angular you want it to update.
i resovle this probleme by ``` $timeout(function(){ $scope.$apply() }) .then(function(){ ... }); ``` thanks for all.
Question: i have list of element when i click in one of them, i fill the template then i copy it to the new DIV, i got an empty template, when i use `$scope.$apply()` i got an error. ``` $scope.tache_list.forEach(element => { $scope.var1 = element; $scope.$apply(); $('#div2').append($("#div1").html()); }); ``` i got `Error $rootScope:inprog` , what i can do ? [![Error rootScope](https://i.stack.imgur.com/geK6t.png)](https://i.stack.imgur.com/geK6t.png) Answer:
Wrap your $scope.$apply call inside a $timeout function. ``` $timeout(function(){ $scope.$apply() }); ``` Reason: Digest cycle will be moved to event loop and execute when the existing cycle completes.
i resovle this probleme by ``` $timeout(function(){ $scope.$apply() }) .then(function(){ ... }); ``` thanks for all.
Question: Are there efficient practices for leveraging an HTML IDE with Python (No Framework) instead of the typical outputting of hand coded HTML in python programs that you can't use HTML IDE's with? I loved the way PHP, JSP, Classic ASP, and .net allow you to include server side code in HTML with the <% tags. I know some think this is poor form but I personally could stay highly organized with include files while leveraging the WYSIWIG HTML IDE's for presentation polish and experimentation as well as code intelisense. FYI: I have gone the IIS ASP route but it just isn't working anymore for anyone I could find online using the latest versions of IIS(8.0). I'm completely open to other web servers/approaches just so long as its something efficient and would supportable from a reputable remote web hosting provider. Thank You! Tim Answer:
Django (<https://www.djangoproject.com/>) and Flask (<http://flask.pocoo.org/>) both let you use template languages which let you manipulate and customize HTML pages. However, these processes differ from PHP-style systems in that the code in the HTML page is only related to how you view the data in the page. The bulk of the processing happens in the python code, or the controller (MVC frameworks) Django's template language: <https://docs.djangoproject.com/en/dev/topics/templates/> Flask's template language (Jinja2): <http://jinja.pocoo.org/docs/>
Have a look at [Mako](http://www.makotemplates.org) template library. It is very easy to use, and yet powerful ([usage documentation](http://docs.makotemplates.org/en/latest/usage.html)). Also, I believe that other popular template libraries can be used outside of a framework as well.
Question: I have a dll called Test.dll in which I have a class called ABC which has a method FindTYpe. Now, I have a project called TestB and I have added the reference of Test.dll in TestB. Now, if I am trying to find a type XYZ in TestB, from `Test.ABC.FindTYpe()`, it's throwing an exception, `TypeNotLaoded Exception`. Please have a look at the problem and tell me how can I resolve it. Answer:
You'll need to post your code for FindType(). My guess is that you're doing something like; ``` System.Reflection.Assembly.GetExecutingAssembly().GetTypes() ``` to find a list of types to search through, and the type in TestB.dll isn't in Test.dll, so the item isn't found. You might want to try something like this instead; ``` /// <summary> /// Returns all types in the current AppDomain /// </summary> public static IEnumerable<Type> LoadedType() { return AppDomain .CurrentDomain .GetAssemblies() .SelectMany(assembly => assembly.GetTypes()); } ``` which should give you the all types loaded into the current application domain -- which, unless you're doing anything odd with appdomains, will be the list of all types loaded into your program. None of the code has been tested, but it should help you find the classes and methods you'll need to use.
Mos probably the type **XYZ** that you are trying to find is not loaded or not present in the paths your app looks for assemblies. The Test.dll and ABC should be present it you added the reference in your project to Test.dll.
Question: I have a dll called Test.dll in which I have a class called ABC which has a method FindTYpe. Now, I have a project called TestB and I have added the reference of Test.dll in TestB. Now, if I am trying to find a type XYZ in TestB, from `Test.ABC.FindTYpe()`, it's throwing an exception, `TypeNotLaoded Exception`. Please have a look at the problem and tell me how can I resolve it. Answer:
You'll need to post your code for FindType(). My guess is that you're doing something like; ``` System.Reflection.Assembly.GetExecutingAssembly().GetTypes() ``` to find a list of types to search through, and the type in TestB.dll isn't in Test.dll, so the item isn't found. You might want to try something like this instead; ``` /// <summary> /// Returns all types in the current AppDomain /// </summary> public static IEnumerable<Type> LoadedType() { return AppDomain .CurrentDomain .GetAssemblies() .SelectMany(assembly => assembly.GetTypes()); } ``` which should give you the all types loaded into the current application domain -- which, unless you're doing anything odd with appdomains, will be the list of all types loaded into your program. None of the code has been tested, but it should help you find the classes and methods you'll need to use.
What does the code look like in FindType? Assuming you are creating the type from the type name (a string), then you must be sure to supply the "assembly qualified" type name, not just the "local" type name. e.g. to retrieve the type you are about to create: ``` Type testB = Type.GetType("TestB.XYZ, TestB"); ``` rather than ``` Type testB = Type.GetType("TestB"); ``` Can you give some more specifics, like some code snippets?
Question: I am currently using Heroku's Memcached in a Rails 3 app and would like to move over to Elasticache because the pricing is much more favorable. Is this possible? Is the configuration relatively straightforward? Is there anything that I should be aware of as regards the performance? Answer:
**DANGER: I do NOT recommend using this solution for production use. While this does work, @btucker pointed out that it allows *any* Heroku-hosted app to access your ElastiCache cluster.** Yes you can. The setup is similar to the guide Heroku has on [Amazon RDS](https://devcenter.heroku.com/articles/amazon_rds). The steps that differ go like this: 1. Follow the "[Get Started with Amazon ElastiCache](http://docs.amazonwebservices.com/AmazonElastiCache/latest/GettingStartedGuide/Welcome.html)" guide to create a cache cluster and node 2. Install the [ElastiCache Command Line Toolkit](http://aws.amazon.com/developertools/2310261897259567) 3. Allow Heroku's servers ingress to your ElastiCache cluster like the RDS guide explains but replace the `rds-` commands with `elasticache-` ones: ``` elasticache-authorize-cache-security-group-ingress \ --cache-security-group-name default \ --ec2-security-group-name default \ --ec2-security-group-owner-id 098166147350 \ # If your AWS_CREDENTIAL_FILE environment setting is configured, # this option is not necessary. --aws-credential-file ../credential-file-path.template ``` 4. Set a Heroku config value for your production app with your cluster's hostname: ``` heroku config:set MEMCACHE_SERVERS=elasticachehostname.amazonaws.com ``` After that, follow the [Memcache Rails setup](https://devcenter.heroku.com/articles/memcache#rails-setup), and you're set.
No, it isn't recommended you use Elasticache as there is no authentication mechanism with it. As such, **anyone** can access your cache! This is normally fine as you would use AWS security rules to restrict what machines can access it to yours. However, this obviously doesn't work with Heroku since your app is run on a randomly chosen machine of Herokus. You could deploy memcache yourself with SASL authentication on an EC2 machine. ElastiCache doesn't really give you anything more than an EC2 machine with memcache pre-installed anyway. **There is another option: [MemCachier](http://www.memcachier.com/)** *(Full disclaimer, I work for MemCachier).* There is another memcache provider on Heroku that is significantly cheaper than the membase provided one. It's called [MemCachier](http://www.memcachier.com/), addon home page is [here](https://addons.heroku.com/memcachier). It's comparable in price to ElasticCache depending on your cache size and if you use reserved instances or not (at the very large cache sizes ElatiCache is cheaper). **Update (June, 2013)**: The membase memcache addon has shutdown, so MemCachier is the only provider of Memcache on Heroku. Please reach out to me if you need any help even if you go with ElastiCache.
Question: I am currently using Heroku's Memcached in a Rails 3 app and would like to move over to Elasticache because the pricing is much more favorable. Is this possible? Is the configuration relatively straightforward? Is there anything that I should be aware of as regards the performance? Answer:
No, it isn't recommended you use Elasticache as there is no authentication mechanism with it. As such, **anyone** can access your cache! This is normally fine as you would use AWS security rules to restrict what machines can access it to yours. However, this obviously doesn't work with Heroku since your app is run on a randomly chosen machine of Herokus. You could deploy memcache yourself with SASL authentication on an EC2 machine. ElastiCache doesn't really give you anything more than an EC2 machine with memcache pre-installed anyway. **There is another option: [MemCachier](http://www.memcachier.com/)** *(Full disclaimer, I work for MemCachier).* There is another memcache provider on Heroku that is significantly cheaper than the membase provided one. It's called [MemCachier](http://www.memcachier.com/), addon home page is [here](https://addons.heroku.com/memcachier). It's comparable in price to ElasticCache depending on your cache size and if you use reserved instances or not (at the very large cache sizes ElatiCache is cheaper). **Update (June, 2013)**: The membase memcache addon has shutdown, so MemCachier is the only provider of Memcache on Heroku. Please reach out to me if you need any help even if you go with ElastiCache.
It's worth noting that while @ssorallen's answer above will work as described, it also allows *ANY* heroku-deployed app to access your memcached server. So if you store anything at all confidential, or you're concerned about other people making use of your ElatiCache cluster, don't do it. In the context of RDS you have the access control built into the database, but memcached has no such authentication supported by ElastiCache. So opening up the security group to all of Heroku is a pretty big risk.
Question: I am currently using Heroku's Memcached in a Rails 3 app and would like to move over to Elasticache because the pricing is much more favorable. Is this possible? Is the configuration relatively straightforward? Is there anything that I should be aware of as regards the performance? Answer:
No, it isn't recommended you use Elasticache as there is no authentication mechanism with it. As such, **anyone** can access your cache! This is normally fine as you would use AWS security rules to restrict what machines can access it to yours. However, this obviously doesn't work with Heroku since your app is run on a randomly chosen machine of Herokus. You could deploy memcache yourself with SASL authentication on an EC2 machine. ElastiCache doesn't really give you anything more than an EC2 machine with memcache pre-installed anyway. **There is another option: [MemCachier](http://www.memcachier.com/)** *(Full disclaimer, I work for MemCachier).* There is another memcache provider on Heroku that is significantly cheaper than the membase provided one. It's called [MemCachier](http://www.memcachier.com/), addon home page is [here](https://addons.heroku.com/memcachier). It's comparable in price to ElasticCache depending on your cache size and if you use reserved instances or not (at the very large cache sizes ElatiCache is cheaper). **Update (June, 2013)**: The membase memcache addon has shutdown, so MemCachier is the only provider of Memcache on Heroku. Please reach out to me if you need any help even if you go with ElastiCache.
There are several Heroku addons that will kinda solve this problem. They provide a SOCKS5 proxy with a static IP address that you can whitelist. * <https://elements.heroku.com/addons/proximo> * <https://elements.heroku.com/addons/quotaguardstatic> * <https://elements.heroku.com/addons/fixie-socks> You can also do this yourself by setting up your own SOCKS5 proxy on ec2. Note the caveats here though: <http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/Access.Outside.html> It's slower, unencrypted, and some NAT monkey business will be required to get it working.
Question: I am currently using Heroku's Memcached in a Rails 3 app and would like to move over to Elasticache because the pricing is much more favorable. Is this possible? Is the configuration relatively straightforward? Is there anything that I should be aware of as regards the performance? Answer:
No, it isn't recommended you use Elasticache as there is no authentication mechanism with it. As such, **anyone** can access your cache! This is normally fine as you would use AWS security rules to restrict what machines can access it to yours. However, this obviously doesn't work with Heroku since your app is run on a randomly chosen machine of Herokus. You could deploy memcache yourself with SASL authentication on an EC2 machine. ElastiCache doesn't really give you anything more than an EC2 machine with memcache pre-installed anyway. **There is another option: [MemCachier](http://www.memcachier.com/)** *(Full disclaimer, I work for MemCachier).* There is another memcache provider on Heroku that is significantly cheaper than the membase provided one. It's called [MemCachier](http://www.memcachier.com/), addon home page is [here](https://addons.heroku.com/memcachier). It's comparable in price to ElasticCache depending on your cache size and if you use reserved instances or not (at the very large cache sizes ElatiCache is cheaper). **Update (June, 2013)**: The membase memcache addon has shutdown, so MemCachier is the only provider of Memcache on Heroku. Please reach out to me if you need any help even if you go with ElastiCache.
If you are using Heroku Private spaces, then it should be possible to do using VPC peering. Follow the instructions here so that your AWS VPC and Heroku VPC can access each other's resources: <https://devcenter.heroku.com/articles/private-space-peering> Once you have the above setup working, just create an elastic cache cluster in the AWS VPC and allow access from the dyno CIDR ranges in the AWS security group or to the complete Heroku VPC CIDR and your dynos will be able to access elastic cache URLs. I was able to get a working setup for Redis, and it should work for any other resource in the AWS VPC.
Question: I am currently using Heroku's Memcached in a Rails 3 app and would like to move over to Elasticache because the pricing is much more favorable. Is this possible? Is the configuration relatively straightforward? Is there anything that I should be aware of as regards the performance? Answer:
**DANGER: I do NOT recommend using this solution for production use. While this does work, @btucker pointed out that it allows *any* Heroku-hosted app to access your ElastiCache cluster.** Yes you can. The setup is similar to the guide Heroku has on [Amazon RDS](https://devcenter.heroku.com/articles/amazon_rds). The steps that differ go like this: 1. Follow the "[Get Started with Amazon ElastiCache](http://docs.amazonwebservices.com/AmazonElastiCache/latest/GettingStartedGuide/Welcome.html)" guide to create a cache cluster and node 2. Install the [ElastiCache Command Line Toolkit](http://aws.amazon.com/developertools/2310261897259567) 3. Allow Heroku's servers ingress to your ElastiCache cluster like the RDS guide explains but replace the `rds-` commands with `elasticache-` ones: ``` elasticache-authorize-cache-security-group-ingress \ --cache-security-group-name default \ --ec2-security-group-name default \ --ec2-security-group-owner-id 098166147350 \ # If your AWS_CREDENTIAL_FILE environment setting is configured, # this option is not necessary. --aws-credential-file ../credential-file-path.template ``` 4. Set a Heroku config value for your production app with your cluster's hostname: ``` heroku config:set MEMCACHE_SERVERS=elasticachehostname.amazonaws.com ``` After that, follow the [Memcache Rails setup](https://devcenter.heroku.com/articles/memcache#rails-setup), and you're set.
It's worth noting that while @ssorallen's answer above will work as described, it also allows *ANY* heroku-deployed app to access your memcached server. So if you store anything at all confidential, or you're concerned about other people making use of your ElatiCache cluster, don't do it. In the context of RDS you have the access control built into the database, but memcached has no such authentication supported by ElastiCache. So opening up the security group to all of Heroku is a pretty big risk.
Question: I am currently using Heroku's Memcached in a Rails 3 app and would like to move over to Elasticache because the pricing is much more favorable. Is this possible? Is the configuration relatively straightforward? Is there anything that I should be aware of as regards the performance? Answer:
**DANGER: I do NOT recommend using this solution for production use. While this does work, @btucker pointed out that it allows *any* Heroku-hosted app to access your ElastiCache cluster.** Yes you can. The setup is similar to the guide Heroku has on [Amazon RDS](https://devcenter.heroku.com/articles/amazon_rds). The steps that differ go like this: 1. Follow the "[Get Started with Amazon ElastiCache](http://docs.amazonwebservices.com/AmazonElastiCache/latest/GettingStartedGuide/Welcome.html)" guide to create a cache cluster and node 2. Install the [ElastiCache Command Line Toolkit](http://aws.amazon.com/developertools/2310261897259567) 3. Allow Heroku's servers ingress to your ElastiCache cluster like the RDS guide explains but replace the `rds-` commands with `elasticache-` ones: ``` elasticache-authorize-cache-security-group-ingress \ --cache-security-group-name default \ --ec2-security-group-name default \ --ec2-security-group-owner-id 098166147350 \ # If your AWS_CREDENTIAL_FILE environment setting is configured, # this option is not necessary. --aws-credential-file ../credential-file-path.template ``` 4. Set a Heroku config value for your production app with your cluster's hostname: ``` heroku config:set MEMCACHE_SERVERS=elasticachehostname.amazonaws.com ``` After that, follow the [Memcache Rails setup](https://devcenter.heroku.com/articles/memcache#rails-setup), and you're set.
There are several Heroku addons that will kinda solve this problem. They provide a SOCKS5 proxy with a static IP address that you can whitelist. * <https://elements.heroku.com/addons/proximo> * <https://elements.heroku.com/addons/quotaguardstatic> * <https://elements.heroku.com/addons/fixie-socks> You can also do this yourself by setting up your own SOCKS5 proxy on ec2. Note the caveats here though: <http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/Access.Outside.html> It's slower, unencrypted, and some NAT monkey business will be required to get it working.
Question: I am currently using Heroku's Memcached in a Rails 3 app and would like to move over to Elasticache because the pricing is much more favorable. Is this possible? Is the configuration relatively straightforward? Is there anything that I should be aware of as regards the performance? Answer:
**DANGER: I do NOT recommend using this solution for production use. While this does work, @btucker pointed out that it allows *any* Heroku-hosted app to access your ElastiCache cluster.** Yes you can. The setup is similar to the guide Heroku has on [Amazon RDS](https://devcenter.heroku.com/articles/amazon_rds). The steps that differ go like this: 1. Follow the "[Get Started with Amazon ElastiCache](http://docs.amazonwebservices.com/AmazonElastiCache/latest/GettingStartedGuide/Welcome.html)" guide to create a cache cluster and node 2. Install the [ElastiCache Command Line Toolkit](http://aws.amazon.com/developertools/2310261897259567) 3. Allow Heroku's servers ingress to your ElastiCache cluster like the RDS guide explains but replace the `rds-` commands with `elasticache-` ones: ``` elasticache-authorize-cache-security-group-ingress \ --cache-security-group-name default \ --ec2-security-group-name default \ --ec2-security-group-owner-id 098166147350 \ # If your AWS_CREDENTIAL_FILE environment setting is configured, # this option is not necessary. --aws-credential-file ../credential-file-path.template ``` 4. Set a Heroku config value for your production app with your cluster's hostname: ``` heroku config:set MEMCACHE_SERVERS=elasticachehostname.amazonaws.com ``` After that, follow the [Memcache Rails setup](https://devcenter.heroku.com/articles/memcache#rails-setup), and you're set.
If you are using Heroku Private spaces, then it should be possible to do using VPC peering. Follow the instructions here so that your AWS VPC and Heroku VPC can access each other's resources: <https://devcenter.heroku.com/articles/private-space-peering> Once you have the above setup working, just create an elastic cache cluster in the AWS VPC and allow access from the dyno CIDR ranges in the AWS security group or to the complete Heroku VPC CIDR and your dynos will be able to access elastic cache URLs. I was able to get a working setup for Redis, and it should work for any other resource in the AWS VPC.
Question: I am currently using Heroku's Memcached in a Rails 3 app and would like to move over to Elasticache because the pricing is much more favorable. Is this possible? Is the configuration relatively straightforward? Is there anything that I should be aware of as regards the performance? Answer:
It's worth noting that while @ssorallen's answer above will work as described, it also allows *ANY* heroku-deployed app to access your memcached server. So if you store anything at all confidential, or you're concerned about other people making use of your ElatiCache cluster, don't do it. In the context of RDS you have the access control built into the database, but memcached has no such authentication supported by ElastiCache. So opening up the security group to all of Heroku is a pretty big risk.
There are several Heroku addons that will kinda solve this problem. They provide a SOCKS5 proxy with a static IP address that you can whitelist. * <https://elements.heroku.com/addons/proximo> * <https://elements.heroku.com/addons/quotaguardstatic> * <https://elements.heroku.com/addons/fixie-socks> You can also do this yourself by setting up your own SOCKS5 proxy on ec2. Note the caveats here though: <http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/Access.Outside.html> It's slower, unencrypted, and some NAT monkey business will be required to get it working.
Question: I am currently using Heroku's Memcached in a Rails 3 app and would like to move over to Elasticache because the pricing is much more favorable. Is this possible? Is the configuration relatively straightforward? Is there anything that I should be aware of as regards the performance? Answer:
It's worth noting that while @ssorallen's answer above will work as described, it also allows *ANY* heroku-deployed app to access your memcached server. So if you store anything at all confidential, or you're concerned about other people making use of your ElatiCache cluster, don't do it. In the context of RDS you have the access control built into the database, but memcached has no such authentication supported by ElastiCache. So opening up the security group to all of Heroku is a pretty big risk.
If you are using Heroku Private spaces, then it should be possible to do using VPC peering. Follow the instructions here so that your AWS VPC and Heroku VPC can access each other's resources: <https://devcenter.heroku.com/articles/private-space-peering> Once you have the above setup working, just create an elastic cache cluster in the AWS VPC and allow access from the dyno CIDR ranges in the AWS security group or to the complete Heroku VPC CIDR and your dynos will be able to access elastic cache URLs. I was able to get a working setup for Redis, and it should work for any other resource in the AWS VPC.
Question: I have a cable modem from Spectrum (Ubee ddw36c) in bridge mode (you have to pay $5/month extra for router mode) so only one port is active which has the internet connection. I have this connected to my router (Netgear R6700v2) by long cable to another rooom and everything works fine.It's in another location because this is the best location for all other wired devices and for best wifi signal. I want to connect my network printer (etherne only, no wi-fi) to the network which is located near the cable modem. I connected a switch to the modem with wired connections out to the router and the printer. The printer isn't getting the right IP address from the router. Do I need to have a router near the cable modem and connect the printer to it and then configure the wifi router as an AP and connect it to this router? Is this how I can get my printer connected to my local network. Right now the printer is getting some IP address that isn't on my LAN. It's 68.175.XXX.XX which seems to be a time warner IP. But it's not the same as my public IP address which is 72.227.XX.XXX which is also a time warner IP. Is there a way to get my printer on my network without getting another router? Answer:
The problem is you split your network in the wrong spot. You put the switch between the modem and the router. Anything in this area will get an IP address from your ISP, not the router. You will need to run another cable from the router back to where the printer is (and either plug int into the switch, or into the printer directly). Then you will be on the same "internal" network that everything else is on.
With the current setup, you can't get correct IP address since the cable modem's DHCP server is handling IP addresses (which in this case you always get one from your ISP). The easiest workaround is having the printer directly connected to the router (i.e move the printer to the router room) then you can get correct IP address at the same time still having access to internet connectivity via cable modem. The reason being this time the router's DHCP server is issuing the local IP addresses If the router has extra ports then this option is a better choice. Alternatively you may have to try bridging as suggested in comments.
Question: I have a cable modem from Spectrum (Ubee ddw36c) in bridge mode (you have to pay $5/month extra for router mode) so only one port is active which has the internet connection. I have this connected to my router (Netgear R6700v2) by long cable to another rooom and everything works fine.It's in another location because this is the best location for all other wired devices and for best wifi signal. I want to connect my network printer (etherne only, no wi-fi) to the network which is located near the cable modem. I connected a switch to the modem with wired connections out to the router and the printer. The printer isn't getting the right IP address from the router. Do I need to have a router near the cable modem and connect the printer to it and then configure the wifi router as an AP and connect it to this router? Is this how I can get my printer connected to my local network. Right now the printer is getting some IP address that isn't on my LAN. It's 68.175.XXX.XX which seems to be a time warner IP. But it's not the same as my public IP address which is 72.227.XX.XXX which is also a time warner IP. Is there a way to get my printer on my network without getting another router? Answer:
The problem is you split your network in the wrong spot. You put the switch between the modem and the router. Anything in this area will get an IP address from your ISP, not the router. You will need to run another cable from the router back to where the printer is (and either plug int into the switch, or into the printer directly). Then you will be on the same "internal" network that everything else is on.
As others have pointed out, the way you have configured the network is putting your printer outside of your local network and directly connected to the internet. This is problematic from many regards, not the least of which is that anyone can hack into your printer and play around with it, potentially without you even knowing it. Putting a router between your internet connection and the printer would help with this security aspect. You cannot decide what the IP address of your printer is when your cable modem is essentially directly connected to the printer, your cable company decides that. As others have mentioned, this is an automatic feature of the cable modem called DHCP, which assigns addresses as needed and this can and will change over time. You can control your internal network DHCP assignments by settings within your router but unless you pay extra to your cable company you likely cannot get a static IP address from your modem. I would suggest that if you absolutely cannot run another wire from a point beyond your router to the printer then get a wireless access point and use that to connect it via wifi. With a reasonably secure wifi network this definitely helps from the security standpoint. Other options would be one of the many plug-in type connections, as the printer does not need a huge amount of bandwidth to do its job. Then you will get an IP address on your network (typically 192.168.x.x or 10.x.x.x) and the printer will be behind the firewall in your router and directly connected to your network subnet. From the technical standpoint, your computers on the network will use the switch (layer 2 addressing - using the MAC address instead of IP address) to connect to the printer instead of requiring a router to translate the packet to a different subnet and forward it (layer 3 addressing) and any access to the printer from the outside internet can be controlled by your router and thus potential hackers can be blocked even before they see the printer. If you set your printer to 10.x.x.x on its control panel then it cannot be addressed at all since your cable modem is connected essentially to the internet and not a local LAN and 10.x.x.x is not able to be routed over the internet. (<https://en.wikipedia.org/wiki/Reserved_IP_addresses> and <https://en.wikipedia.org/wiki/Martian_packet>)
Question: At first I heard it and thought i could soar like a bird! And oh what i heard! I’ll zoom so fast, my image will be blurred. And now I see it, it’s flat as can be! Oh woe is me. And how lonely, just one single tree. --- What is this riddle referring to? **Hints:** > > The answer is a single word > > > Answer:
I think the word you're looking for is > > plain. > > > "thought I could soar like a bird" > > You misheard it as "plane". Planes (aeroplanes) fly. > > > "I'll zoom so fast, my image will be blurred." > > Just a reference to the rapid motion of aeroplanes? Or perhaps also a reference to the focal plane of a camera lens. (The reference to *zooming* suggests it might be.) > > > "it's flat as can be!" > > "Plain" means, among other things, flat. Of course you should have suspected this even when you had only heard the word and thought it was "plane": a plane (in the mathematical sense) is flat :-). > > > "just one single tree" > > A plane is also a kind of tree, but we're back to "plain" here so perhaps it's a plain ol' plane tree: just one single boring plane tree. Or (and this turns out to be the questioner's intention) I find myself on a plain, where by definition there are few trees. > > >
This is more like a poem then a riddle. It could be > > A Dream > > > At first I heard it and thought i could soar like a bird! > > At start you saw something exciting in the dream thats what *"i heard it"* is referring to. And then you decided to fly into the dream like a bird. > > > And oh what i heard! > > Suddenly you saw someone in the dream > > > I’ll zoom so fast, my image will be blurred. > > Then decided to see him clearly(zoom) but its blurred. Well all dreams are a blurred image. > > > And now I see it, it’s flat as can be! > > Then suddenly wake up from a dream and sorted out that was not real. May be flat here refers to coming to the actual flat world. > > > Oh woe is me. And how lonely, just one single tree. > > After waking up from dream you found yourself all alone again. *a single tree* represents loneliness. > > >
Question: I'm trying to acquire the most recent entry into DynamoDB or to parse out the results I get, so I can skim the most recent item off the top. This is my code ``` from __future__ import print_function # Python 2/3 compatibility import boto3 import json import decimal from boto3.dynamodb.conditions import Key, Attr # Helper class to convert a DynamoDB item to JSON. class DecimalEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, decimal.Decimal): if o % 1 > 0: return float(o) else: return int(o) return super(DecimalEncoder, self).default(o) dynamodb = boto3.resource('dynamodb', region_name='us-west-2', endpoint_url="https://foo.foo.foo/aws") table = dynamodb.Table('footable') response = table.scan( Select="ALL_ATTRIBUTES", ) for i in response['Items']: print(json.dumps(i, cls=DecimalEncoder)) ``` My results are a lot of the following that I'd like to either parse or if someone knows the code to just select the top entry that would be great. ``` {"MinorID": 123, "Location": "123westsideave"} {"MinorID": 321, "Location": "456nowhererd"} {"MinorID": 314, "Location": "123westsideave"} ``` Answer:
at the end of my code where it says "print(json.dumps(i, cls=DecimalEncoder))" I changed that to "d = ast.literal\_eval((json.dumps(i, cls=DecimalEncoder)))" I also added import ast at the top. It worked beautifully. ``` import ast table = dynamodb.Table('footable') response = table.scan( Select="ALL_ATTRIBUTES", ) for i in response['Items']: d = ast.literal_eval((json.dumps(i, cls=DecimalEncoder))) ```
``` import boto3 import json import decimal from boto3.dynamodb.conditions import Key, Attr # Helper class to convert a DynamoDB item to JSON. class DecimalEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, decimal.Decimal): return str(o) if isinstance(o, set): #<---resolving sets as lists return list(o) return super(DecimalEncoder, self).default(o) dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('mytable') response = table.query( KeyConditionExpression=Key('object_type').eq("employee") ) print(json.dumps((response), indent=4, cls=DecimalEncoder)) ```
Question: I want to develop a application. Say for example on Phone7/iPhone/android, this application shall get data from a server. My problem is that I dont know where to start. For the first I got a mac mini that I would love to use as the server, but I got no server operating system on it, does this mean I have to develop my own application that runs on the mac that these mobile apps can connect to? I would love to use my mac as the server, so I later can host my website from this and not the very restricted host I got per day. I hope you guys can point me in the right direction! :) Answer:
``` class Conversation < ActiveRecord::Base has_many :conversation_users has_many :users, :through => :conversation_users has_many :messages # NEXT LINE IS CHANGED! accepts_nested_attributes_for :conversation_users accepts_nested_attributes_for :messages end ``` Controller ``` def new @conversation = Conversation.new 2.times{ users = @conversation.conversation_users.build } messages = @conversation.messages.build end ``` And form ``` <%= form_for([current_user, @conversation]) do |f| %> <%= f.fields_for :conversation_users do |builder| %> <%= builder.text_field :user_id %> <%= builder.hidden_field :conversation_id %> <% end %> ... <% end %> ``` That's it.
Replace: ```    <% f.fields_for :users do |builder| %> ``` With: ```    <%= f.fields_for :users do |builder| %> ``` Same missing '=' a bit lower.
Question: I want to develop a application. Say for example on Phone7/iPhone/android, this application shall get data from a server. My problem is that I dont know where to start. For the first I got a mac mini that I would love to use as the server, but I got no server operating system on it, does this mean I have to develop my own application that runs on the mac that these mobile apps can connect to? I would love to use my mac as the server, so I later can host my website from this and not the very restricted host I got per day. I hope you guys can point me in the right direction! :) Answer:
``` class Conversation < ActiveRecord::Base has_many :conversation_users has_many :users, :through => :conversation_users has_many :messages # NEXT LINE IS CHANGED! accepts_nested_attributes_for :conversation_users accepts_nested_attributes_for :messages end ``` Controller ``` def new @conversation = Conversation.new 2.times{ users = @conversation.conversation_users.build } messages = @conversation.messages.build end ``` And form ``` <%= form_for([current_user, @conversation]) do |f| %> <%= f.fields_for :conversation_users do |builder| %> <%= builder.text_field :user_id %> <%= builder.hidden_field :conversation_id %> <% end %> ... <% end %> ``` That's it.
``` <% form_for([current_user, @conversation]) do |f| %> ``` should be ``` <%= form_for([current_user, @conversation]) do |f| %> ``` And ``` <% f.fields_for :messages do |builder| %> # and <% f.fields_for :users do |builder| %> ``` should be ``` <%= f.fields_for :messages do |builder| %> # and <%= f.fields_for :users do |builder| %> ```
Question: If I have 2 `int` arrays a and b and they contain data like this.. ``` a[0] = 1 a[1] = 3 a[2] = 7 b[0] = 6 b[1] = 3 b[2] = 5 ``` How can I check if all the pairs of numbers are unique e.g. that each combination of `a[i]` and `b[i]` at the same index is not repeated in the rest of the array... So the above data would pass but if I introduced this below it would fail.. ``` a[24] = 7 b[24] = 5 ``` Because this combination already exists in the array at index 2. Can I do this in LINQ? Answer:
If the order of the values in the pairs over the two arrays is significant (i.e. `a[0] == 1, b[0] == 2` is considered different from `a[0] == 2, b[0] == 1`) then one way to check for uniqueness using Linq is as follows: ``` bool unique = a.Zip(b).Distinct().Count() == a.Length; ``` If the order of the values in the pairs is NOT significant, it's slightly more fiddly: ``` bool unique = a.Zip(b).DistinctBy( x => (Math.Min(x.First, x.Second), Math.Max(x.First,x.Second))) .Count() == a.Length; ``` These solutions assume that missing values in one of the arrays will be ignored. (Note: `DistinctBy()` is only available in .Net 6.0 or later, or via a NuGet package.)
try this sample : ``` int [] aa = a.Distinct().ToArray(); ``` or : ``` public static bool HasDuplicates<T>(IList<T> items) { Dictionary<T, bool> map = new Dictionary<T, bool>(); for (int i = 0; i < items.Count; i++) { if (map.ContainsKey(items[i])) { return true; // has duplicates } map.Add(items[i], true); } return false; // no duplicates } ``` and call : ``` string[] strings = new[] { "1", "2", "3" }; Utility.HasDuplicates(strings)// this will return false int[] items=new []{1,2,3,1}; Utility.HasDuplicates(items)// this will return true ```
Question: If I have 2 `int` arrays a and b and they contain data like this.. ``` a[0] = 1 a[1] = 3 a[2] = 7 b[0] = 6 b[1] = 3 b[2] = 5 ``` How can I check if all the pairs of numbers are unique e.g. that each combination of `a[i]` and `b[i]` at the same index is not repeated in the rest of the array... So the above data would pass but if I introduced this below it would fail.. ``` a[24] = 7 b[24] = 5 ``` Because this combination already exists in the array at index 2. Can I do this in LINQ? Answer:
I've managed to work this out and solve this with : ``` a.Zip(b, (aPos, bPos) => new { aPosition = aPos, bPosition = bPos }).Distinct().Count() ``` This will tell me how many distinct sets of both values at the same index and so I can work the rest out from here. Apologies if my question wasn't clear.
try this sample : ``` int [] aa = a.Distinct().ToArray(); ``` or : ``` public static bool HasDuplicates<T>(IList<T> items) { Dictionary<T, bool> map = new Dictionary<T, bool>(); for (int i = 0; i < items.Count; i++) { if (map.ContainsKey(items[i])) { return true; // has duplicates } map.Add(items[i], true); } return false; // no duplicates } ``` and call : ``` string[] strings = new[] { "1", "2", "3" }; Utility.HasDuplicates(strings)// this will return false int[] items=new []{1,2,3,1}; Utility.HasDuplicates(items)// this will return true ```
Question: If I have 2 `int` arrays a and b and they contain data like this.. ``` a[0] = 1 a[1] = 3 a[2] = 7 b[0] = 6 b[1] = 3 b[2] = 5 ``` How can I check if all the pairs of numbers are unique e.g. that each combination of `a[i]` and `b[i]` at the same index is not repeated in the rest of the array... So the above data would pass but if I introduced this below it would fail.. ``` a[24] = 7 b[24] = 5 ``` Because this combination already exists in the array at index 2. Can I do this in LINQ? Answer:
If the order of the values in the pairs over the two arrays is significant (i.e. `a[0] == 1, b[0] == 2` is considered different from `a[0] == 2, b[0] == 1`) then one way to check for uniqueness using Linq is as follows: ``` bool unique = a.Zip(b).Distinct().Count() == a.Length; ``` If the order of the values in the pairs is NOT significant, it's slightly more fiddly: ``` bool unique = a.Zip(b).DistinctBy( x => (Math.Min(x.First, x.Second), Math.Max(x.First,x.Second))) .Count() == a.Length; ``` These solutions assume that missing values in one of the arrays will be ignored. (Note: `DistinctBy()` is only available in .Net 6.0 or later, or via a NuGet package.)
I've managed to work this out and solve this with : ``` a.Zip(b, (aPos, bPos) => new { aPosition = aPos, bPosition = bPos }).Distinct().Count() ``` This will tell me how many distinct sets of both values at the same index and so I can work the rest out from here. Apologies if my question wasn't clear.
Question: Given two sample dataframes: ``` df0 = pd.DataFrame([('a', 1, 1000), ('b', 2, 1200), ('d', 100, 1500)], columns=['L','A','ADA']) df1 = pd.DataFrame([('a', 1, 2, 1000), ('b', 2, 100, 1200), ('d', 100, 2, 1500)], columns=['L','A','A','ADA']) ``` I would like to replace values in all columns named `A` if the value is greater than `10`. The snippet ``` df = df0 df.loc[df['A'] > 10, 'A'] = np.nan ``` Works, perfectly, while the same applied to second dataframe do not works ``` df = df1 df.loc[df['A'] > 10, 'A'] = np.nan ``` since `df['A']` returns two columns. Is there any approach that can handle both cases? While renaming the column is a option (I'd rather not), that is how the data is formatted (I can't control this), renaming the data in actual code base leads to many issues downhill. I'm looking for a solution that can handle this case. If have two columns with same name is a issue, what is the reason to pandas accept this? Answer:
You can use [`numpy.where`](https://numpy.org/doc/stable/reference/generated/numpy.where.html) to replace all your `duplicate` columns: ``` In [2405]: df1 Out[2405]: L A A ADA 0 a 1 2 1000 1 b 2 100 1200 2 d 100 2 1500 In [2405]: import numpy as np In [2406]: df1.A = np.where(df1.A.gt(10), np.nan, df1.A) In [2407]: df1 Out[2407]: L A A ADA 0 a 1.0 2.0 1000 1 b 2.0 NaN 1200 2 d NaN 2.0 1500 ```
If you want to absolutely retain the duplicate column names, then please try the following. Here, we are trying to access the index of the column and then manipulating it. ``` df = df1 df['A'] = df['A'].astype(float) df.iloc[:,1].values[df.iloc[:,1] > 10] = np.nan df.iloc[:,2].values[df.iloc[:,2] > 10] = np.nan ```
Question: I am thinking of using base64 encoded images for a site I am working on to optimize the load time. Anyways, before I start, I was wondering: what are the advantages and disadvantages of doing this? At the moment, I don't see any disadvantage but also I noticed that it is not a technique used very often and that makes me wonder if I didn't miss something. After googleing the subject I didn't find anything clear so I decided to ask here. Answer:
It's only useful for very tiny images. Base64 encoded files are larger than the original. The advantage lies in not having to open another connection and make a HTTP request to the server for the image. This benefit is lost very quickly so there's only an advantage for large numbers of very tiny individual images.
> > the actual length of MIME-compliant Base64-encoded binary data is > usually about 137% of the original data length, though for very short > messages the overhead can be much higher due to the overhead of the > headers. Very roughly, the final size of Base64-encoded binary data is > equal to 1.37 times the original data size + 814 bytes (for headers). > > > In other words, the size of the decoded data can be approximated with this formula: > > > ``` bytes = (string_length(encoded_string) - 814) / 1.37 ``` Source: <http://en.wikipedia.org/wiki/Base64#MIME>
Question: I am thinking of using base64 encoded images for a site I am working on to optimize the load time. Anyways, before I start, I was wondering: what are the advantages and disadvantages of doing this? At the moment, I don't see any disadvantage but also I noticed that it is not a technique used very often and that makes me wonder if I didn't miss something. After googleing the subject I didn't find anything clear so I decided to ask here. Answer:
It's only useful for very tiny images. Base64 encoded files are larger than the original. The advantage lies in not having to open another connection and make a HTTP request to the server for the image. This benefit is lost very quickly so there's only an advantage for large numbers of very tiny individual images.
Some of downsides as below are already mentioned in this post at [How much faster is it to use inline/base64 images for a web site than just linking to the hard file?](https://stackoverflow.com/questions/1574961/how-much-faster-is-it-to-use-inline-base64-images-for-a-web-site-than-just-linki) * Most forms of caching are beaten which could hurt a lot if the image is viewed often - say, a logo that is displayed on every page, which could normally be cached by the browser. * More CPU usage.
Question: I am thinking of using base64 encoded images for a site I am working on to optimize the load time. Anyways, before I start, I was wondering: what are the advantages and disadvantages of doing this? At the moment, I don't see any disadvantage but also I noticed that it is not a technique used very often and that makes me wonder if I didn't miss something. After googleing the subject I didn't find anything clear so I decided to ask here. Answer:
It's only useful for very tiny images. Base64 encoded files are larger than the original. The advantage lies in not having to open another connection and make a HTTP request to the server for the image. This benefit is lost very quickly so there's only an advantage for large numbers of very tiny individual images.
also the response time of the HTML page will increase, because images loads asyn in normal scenario. even if images loads late you can start seeing text. Another advantage of CDN would lost if only media is being cached in CDN that advantage will be lost.