prompt
stringlengths
48
2.37k
chosen
stringlengths
7
4.28k
rejected
stringlengths
11
4.44k
Question: I want to make a drop down using the data given in the BootStrap.groovy. My City domain class ``` package city.model class City { String cityName static constraints = { cityName(maxSize: 50) } } ``` In my Service class ``` public class CityService { def citySelect(String cityName) //this is just a sample { City city = new City() city.cityName = city.findByCityName(cityName) } } ``` controller ``` public class CityController { def cityService def def selCity() { def selectCity = cityService.citySelect(params.cityName){ if(selectCity != null){ render view // my view } else{ render view // error select again view } } } ``` BootStrap.groovy ``` import city.City; class BootStrap { def init = { servletContext -> for(String cityName in ['Addis Ababa', 'Semera','Asosa','Gondar', 'Jijiga','Harar', 'Dire Dawa', 'Bahir Dar', 'Hawassa', 'Arba Minch', 'Adama', 'Mekelle']) { City.findOrSaveByCityName(cityName).save() } } def destroy = { } } ``` i used this ``` <g:select name="cities" from="${City.list()}" optionKey="id" optionValue="cityName"/> in my view but showing error cannot envoke method list on null object ``` What is wrong within mu code and what should i do to make it work. please any suggestions Answer:
Maybe you have misunderstood the point of Bootstrap. Bootstrap as per the naming convention is the part that is triggered when your site is booting up. You would typically use it to ensure required db table records are generated before it has booted up i.e. admin account or in your case generation of some cities. You would not be using Bootstrap to interact with the records you generated in the way of editing or selecting. Once this has all be done and saved - you would have also used the Controllers/Views to list/view/update/add cities. You would create your g:select tags in these views and matching controllers that would query the records you have saved via bootstrap **E2A:** Ok Just read your comment Either use an import on the top of your gsp ``` <%@ page import="city.City" %> ``` or call full packaged path to City domainClass **city.City.list** ``` <g:select name="cities" from="${city.City.list()}" optionKey="id" optionValue="cityName"/> ```
To create a list of the Cities you inserted into the Database in the Bootstrap.groovy (in a view i.e [viewName].gsp) Mark up is like so ``` <g:select name="city" from="${city.model.City.list()}" value="${city.name}" noSelection="['':'-Please select the City-']" optionKey="id"/> ``` However, the Bootstrap should be for initialization of Database and Application defaults, Also to perform start (Startup in the init closure while shutdown in the destroy Closure).
Question: I want to make a drop down using the data given in the BootStrap.groovy. My City domain class ``` package city.model class City { String cityName static constraints = { cityName(maxSize: 50) } } ``` In my Service class ``` public class CityService { def citySelect(String cityName) //this is just a sample { City city = new City() city.cityName = city.findByCityName(cityName) } } ``` controller ``` public class CityController { def cityService def def selCity() { def selectCity = cityService.citySelect(params.cityName){ if(selectCity != null){ render view // my view } else{ render view // error select again view } } } ``` BootStrap.groovy ``` import city.City; class BootStrap { def init = { servletContext -> for(String cityName in ['Addis Ababa', 'Semera','Asosa','Gondar', 'Jijiga','Harar', 'Dire Dawa', 'Bahir Dar', 'Hawassa', 'Arba Minch', 'Adama', 'Mekelle']) { City.findOrSaveByCityName(cityName).save() } } def destroy = { } } ``` i used this ``` <g:select name="cities" from="${City.list()}" optionKey="id" optionValue="cityName"/> in my view but showing error cannot envoke method list on null object ``` What is wrong within mu code and what should i do to make it work. please any suggestions Answer:
``` <g:select name="city" from="${city.model.City.list()}" optionValue="${cityName}" noSelection="['':'-Please select the City-']" optionKey="id"/> ``` this could work fine.
This should work: ``` <g:select name="cities" from="${city.model.City.list()}" optionKey="id" optionValue="cityName"/> ``` However, executing queries like `city.model.City.list()` in a GSP is not a recommended practice. Instead you should retrieve your data (the list of cities) in a controller action or a service and pass that via the model to the GSP.
Question: I want to make a drop down using the data given in the BootStrap.groovy. My City domain class ``` package city.model class City { String cityName static constraints = { cityName(maxSize: 50) } } ``` In my Service class ``` public class CityService { def citySelect(String cityName) //this is just a sample { City city = new City() city.cityName = city.findByCityName(cityName) } } ``` controller ``` public class CityController { def cityService def def selCity() { def selectCity = cityService.citySelect(params.cityName){ if(selectCity != null){ render view // my view } else{ render view // error select again view } } } ``` BootStrap.groovy ``` import city.City; class BootStrap { def init = { servletContext -> for(String cityName in ['Addis Ababa', 'Semera','Asosa','Gondar', 'Jijiga','Harar', 'Dire Dawa', 'Bahir Dar', 'Hawassa', 'Arba Minch', 'Adama', 'Mekelle']) { City.findOrSaveByCityName(cityName).save() } } def destroy = { } } ``` i used this ``` <g:select name="cities" from="${City.list()}" optionKey="id" optionValue="cityName"/> in my view but showing error cannot envoke method list on null object ``` What is wrong within mu code and what should i do to make it work. please any suggestions Answer:
``` <g:select name="city" from="${city.model.City.list()}" optionValue="${cityName}" noSelection="['':'-Please select the City-']" optionKey="id"/> ``` this could work fine.
To create a list of the Cities you inserted into the Database in the Bootstrap.groovy (in a view i.e [viewName].gsp) Mark up is like so ``` <g:select name="city" from="${city.model.City.list()}" value="${city.name}" noSelection="['':'-Please select the City-']" optionKey="id"/> ``` However, the Bootstrap should be for initialization of Database and Application defaults, Also to perform start (Startup in the init closure while shutdown in the destroy Closure).
Question: I have the following array: ``` let arr = [ {"id": 123, "lastUpdate": 1543229793}, {"id": 456, "lastUpdate": 1545269320}, {"id": 123, "lastUpdate": 1552184795} ] ``` I need to filter the array based on the same ID, but also check the "lastUpdate" timestamp and keep only the newer entries. The result should be: ``` [ {"id": 456, "lastUpdate": 1545269320}, {"id": 123, "lastUpdate": 1552184795} ] ``` I have tried the following: ``` arr = arr.filter((e, index, self) => index === self.findIndex((t) => ( t.id === intent.id && t.lastUpdate > e.lastUpdate )) ) ``` However, this filters everything for me and the resulting array is empty. I think something is wrong with the last part of above `&& t.lastUpdate > e.lastUpdate`. Many thanks for any tips! Answer:
You can achieve it by looking for items that don't have an item2 where the update was later ``` arr.filter(item => { return !arr.some(item2 => item.id === item2.id && item.lastUpdate < item2.lastUpdate) }); ``` What that code does is : For each item in the array it look if in the array there is an item with the same id where the lastUpdate is superior to its own. If there is one it return true (Array.some returns a boolean). We negate that value and use it to filter.
You could do it step by step by converting to a set, sorting then getting the first item for each id: ```js let arr = [ {"id": 123, "lastUpdate": 1543229793}, {"id": 456, "lastUpdate": 1545269320}, {"id": 123, "lastUpdate": 1552184795} ] // Get the ids by making a set of ids and then converting to array let ids = [ ...new Set(arr.map((e) => e.id)) ]; // Sort the original by lastUpdate descending arr.sort((a, b) => b.lastUpdate - a.lastUpdate); // Get array of first item from arr by id let res = ids.map(id => arr.find((e) => e.id == id)); console.log(res); ```
Question: I have the following array: ``` let arr = [ {"id": 123, "lastUpdate": 1543229793}, {"id": 456, "lastUpdate": 1545269320}, {"id": 123, "lastUpdate": 1552184795} ] ``` I need to filter the array based on the same ID, but also check the "lastUpdate" timestamp and keep only the newer entries. The result should be: ``` [ {"id": 456, "lastUpdate": 1545269320}, {"id": 123, "lastUpdate": 1552184795} ] ``` I have tried the following: ``` arr = arr.filter((e, index, self) => index === self.findIndex((t) => ( t.id === intent.id && t.lastUpdate > e.lastUpdate )) ) ``` However, this filters everything for me and the resulting array is empty. I think something is wrong with the last part of above `&& t.lastUpdate > e.lastUpdate`. Many thanks for any tips! Answer:
Hi there if you are looking for a performant solution you can use an object :) ``` let arr = [{"id": 123,"lastUpdate": 1543229793}, {"id": 456,"lastUpdate": 1545269320}, {"id": 123, "lastUpdate": 1552184795}]; let newArr = {} arr.forEach(el => { if(!newArr[el.id] || newArr[el.id].lastUpdate < el.lastUpdate){ newArr[el.id] = el } }) console.log(Object.values(newArr)); ```
You can achieve it by looking for items that don't have an item2 where the update was later ``` arr.filter(item => { return !arr.some(item2 => item.id === item2.id && item.lastUpdate < item2.lastUpdate) }); ``` What that code does is : For each item in the array it look if in the array there is an item with the same id where the lastUpdate is superior to its own. If there is one it return true (Array.some returns a boolean). We negate that value and use it to filter.
Question: I have the following array: ``` let arr = [ {"id": 123, "lastUpdate": 1543229793}, {"id": 456, "lastUpdate": 1545269320}, {"id": 123, "lastUpdate": 1552184795} ] ``` I need to filter the array based on the same ID, but also check the "lastUpdate" timestamp and keep only the newer entries. The result should be: ``` [ {"id": 456, "lastUpdate": 1545269320}, {"id": 123, "lastUpdate": 1552184795} ] ``` I have tried the following: ``` arr = arr.filter((e, index, self) => index === self.findIndex((t) => ( t.id === intent.id && t.lastUpdate > e.lastUpdate )) ) ``` However, this filters everything for me and the resulting array is empty. I think something is wrong with the last part of above `&& t.lastUpdate > e.lastUpdate`. Many thanks for any tips! Answer:
Hi there if you are looking for a performant solution you can use an object :) ``` let arr = [{"id": 123,"lastUpdate": 1543229793}, {"id": 456,"lastUpdate": 1545269320}, {"id": 123, "lastUpdate": 1552184795}]; let newArr = {} arr.forEach(el => { if(!newArr[el.id] || newArr[el.id].lastUpdate < el.lastUpdate){ newArr[el.id] = el } }) console.log(Object.values(newArr)); ```
You could do it step by step by converting to a set, sorting then getting the first item for each id: ```js let arr = [ {"id": 123, "lastUpdate": 1543229793}, {"id": 456, "lastUpdate": 1545269320}, {"id": 123, "lastUpdate": 1552184795} ] // Get the ids by making a set of ids and then converting to array let ids = [ ...new Set(arr.map((e) => e.id)) ]; // Sort the original by lastUpdate descending arr.sort((a, b) => b.lastUpdate - a.lastUpdate); // Get array of first item from arr by id let res = ids.map(id => arr.find((e) => e.id == id)); console.log(res); ```
Question: I've seen 22-inch beauty dishes used with Canon speedlights for portraits. However I'm not sure if a single speedlight is powerful enough for a large beauty dish. Should I be using it with a monolight strobe instead? Answer:
It depends entirely on the guide number of your flash, the distance to your subject, the brightness of your environment, whether you're using just a single or multiple flashes and I'm sure lots of other things. I have seen large beauty dishes used without problem but it depends on your own circumstances.
A beauty dish is mainly used to focus back the light of a strobe [![enter image description here](https://i.stack.imgur.com/EFpE3.png)](https://i.stack.imgur.com/EFpE3.png) It's basically like putting a flash 5cm away from the face of your subject, but without having the real flash in the photo [![enter image description here](https://i.stack.imgur.com/H2g6U.png)](https://i.stack.imgur.com/H2g6U.png) It gives you that nice fallof of the light [![enter image description here](https://i.stack.imgur.com/QpXVJ.png)](https://i.stack.imgur.com/QpXVJ.png) It can only focus one light to one location to make one subject look good. If it's bigger, it will allow you to focus your light further away from your flash, but you shouldn't need more power, because in theory you need the same amount of focused light on your subject's face, and none is lost. [![enter image description here](https://i.stack.imgur.com/0EfNQ.png)](https://i.stack.imgur.com/0EfNQ.png) In practice though, we're not using perfect mirrors, and some light will be lost. Still, you'll want to keep it close, or you'd get the same light as a bare flash. [![enter image description here](https://i.stack.imgur.com/Zmz7P.png)](https://i.stack.imgur.com/Zmz7P.png) And if it's close, well, you don't need a crazy powerful strobe
Question: How can I map a DataReader object into a class object by using generics? For example I need to do the following: ``` public class Mapper<T> { public static List<T> MapObject(IDataReader dr) { List<T> objects = new List<T>(); while (dr.Read()) { //Mapping goes here... } return objects; } } ``` And later I need to call this class-method like the following: ``` IDataReder dataReader = DBUtil.Fetchdata("SELECT * FROM Book"); List<Book> bookList = Mapper<Book>.MapObject(dataReder); foreach (Book b in bookList) { Console.WriteLine(b.ID + ", " + b.BookName); } ``` Note that, the Mapper - class should be able to map object of any type represented by T. Answer:
Well, i don't know if it fits here, but you could be using the yield keyword ``` public static IEnumerable<T> MapObject(IDataReader dr, Func<IDataReader, T> convertFunction) { while (dr.Read()) { yield return convertFunction(dr); } } ```
You could use this LateBinder class I wrote: <http://codecube.net/2008/12/new-latebinder/>. I wrote another post with usage: <http://codecube.net/2008/12/using-the-latebinder/>
Question: How can I map a DataReader object into a class object by using generics? For example I need to do the following: ``` public class Mapper<T> { public static List<T> MapObject(IDataReader dr) { List<T> objects = new List<T>(); while (dr.Read()) { //Mapping goes here... } return objects; } } ``` And later I need to call this class-method like the following: ``` IDataReder dataReader = DBUtil.Fetchdata("SELECT * FROM Book"); List<Book> bookList = Mapper<Book>.MapObject(dataReder); foreach (Book b in bookList) { Console.WriteLine(b.ID + ", " + b.BookName); } ``` Note that, the Mapper - class should be able to map object of any type represented by T. Answer:
I use [ValueInjecter](http://valueinjecter.codeplex.com/) for this I'm doing like this: ``` while (dr.Read()) { var o = new User(); o.InjectFrom<DataReaderInjection>(dr); yield return o; } ``` you gonna need this ValueInjection for this to work: ``` public class DataReaderInjection : KnownSourceValueInjection<IDataReader> { protected override void Inject(IDataReader source, object target, PropertyDescriptorCollection targetProps) { for (var i = 0; i < source.FieldCount; i++) { var activeTarget = targetProps.GetByName(source.GetName(i), true); if (activeTarget == null) continue; var value = source.GetValue(i); if (value == DBNull.Value) continue; activeTarget.SetValue(target, value); } } } ```
What about using [Fluent Ado.net](http://fluentado.codeplex.com/) ?
Question: How can I map a DataReader object into a class object by using generics? For example I need to do the following: ``` public class Mapper<T> { public static List<T> MapObject(IDataReader dr) { List<T> objects = new List<T>(); while (dr.Read()) { //Mapping goes here... } return objects; } } ``` And later I need to call this class-method like the following: ``` IDataReder dataReader = DBUtil.Fetchdata("SELECT * FROM Book"); List<Book> bookList = Mapper<Book>.MapObject(dataReder); foreach (Book b in bookList) { Console.WriteLine(b.ID + ", " + b.BookName); } ``` Note that, the Mapper - class should be able to map object of any type represented by T. Answer:
Well, i don't know if it fits here, but you could be using the yield keyword ``` public static IEnumerable<T> MapObject(IDataReader dr, Func<IDataReader, T> convertFunction) { while (dr.Read()) { yield return convertFunction(dr); } } ```
What about using [Fluent Ado.net](http://fluentado.codeplex.com/) ?
Question: How can I map a DataReader object into a class object by using generics? For example I need to do the following: ``` public class Mapper<T> { public static List<T> MapObject(IDataReader dr) { List<T> objects = new List<T>(); while (dr.Read()) { //Mapping goes here... } return objects; } } ``` And later I need to call this class-method like the following: ``` IDataReder dataReader = DBUtil.Fetchdata("SELECT * FROM Book"); List<Book> bookList = Mapper<Book>.MapObject(dataReder); foreach (Book b in bookList) { Console.WriteLine(b.ID + ", " + b.BookName); } ``` Note that, the Mapper - class should be able to map object of any type represented by T. Answer:
I use [ValueInjecter](http://valueinjecter.codeplex.com/) for this I'm doing like this: ``` while (dr.Read()) { var o = new User(); o.InjectFrom<DataReaderInjection>(dr); yield return o; } ``` you gonna need this ValueInjection for this to work: ``` public class DataReaderInjection : KnownSourceValueInjection<IDataReader> { protected override void Inject(IDataReader source, object target, PropertyDescriptorCollection targetProps) { for (var i = 0; i < source.FieldCount; i++) { var activeTarget = targetProps.GetByName(source.GetName(i), true); if (activeTarget == null) continue; var value = source.GetValue(i); if (value == DBNull.Value) continue; activeTarget.SetValue(target, value); } } } ```
This is going to be very hard to do for the reason that you are basically trying to map two unknowns together. In your generic object the type is unknown, and in your datareader the table is unknown. So what I would suggest is you create some kind of column attribute to attach to the properties of you entity. And then look through those property attributes and try to look up the data from those attributes in the datareader. Your biggest problem is going to be, what happens if one of the properties isn't found in the reader, or vice-versa, one of the columns in the reader isn't found in the entity. Good luck, but if you want to do something like this, you probably want a ORM or at the very least some kind of Active Record implementation.
Question: How can I map a DataReader object into a class object by using generics? For example I need to do the following: ``` public class Mapper<T> { public static List<T> MapObject(IDataReader dr) { List<T> objects = new List<T>(); while (dr.Read()) { //Mapping goes here... } return objects; } } ``` And later I need to call this class-method like the following: ``` IDataReder dataReader = DBUtil.Fetchdata("SELECT * FROM Book"); List<Book> bookList = Mapper<Book>.MapObject(dataReder); foreach (Book b in bookList) { Console.WriteLine(b.ID + ", " + b.BookName); } ``` Note that, the Mapper - class should be able to map object of any type represented by T. Answer:
I use [ValueInjecter](http://valueinjecter.codeplex.com/) for this I'm doing like this: ``` while (dr.Read()) { var o = new User(); o.InjectFrom<DataReaderInjection>(dr); yield return o; } ``` you gonna need this ValueInjection for this to work: ``` public class DataReaderInjection : KnownSourceValueInjection<IDataReader> { protected override void Inject(IDataReader source, object target, PropertyDescriptorCollection targetProps) { for (var i = 0; i < source.FieldCount; i++) { var activeTarget = targetProps.GetByName(source.GetName(i), true); if (activeTarget == null) continue; var value = source.GetValue(i); if (value == DBNull.Value) continue; activeTarget.SetValue(target, value); } } } ```
I would recommend that you'd use [AutoMapper](http://automapper.codeplex.com/) for this.
Question: How can I map a DataReader object into a class object by using generics? For example I need to do the following: ``` public class Mapper<T> { public static List<T> MapObject(IDataReader dr) { List<T> objects = new List<T>(); while (dr.Read()) { //Mapping goes here... } return objects; } } ``` And later I need to call this class-method like the following: ``` IDataReder dataReader = DBUtil.Fetchdata("SELECT * FROM Book"); List<Book> bookList = Mapper<Book>.MapObject(dataReder); foreach (Book b in bookList) { Console.WriteLine(b.ID + ", " + b.BookName); } ``` Note that, the Mapper - class should be able to map object of any type represented by T. Answer:
Well, i don't know if it fits here, but you could be using the yield keyword ``` public static IEnumerable<T> MapObject(IDataReader dr, Func<IDataReader, T> convertFunction) { while (dr.Read()) { yield return convertFunction(dr); } } ```
This is going to be very hard to do for the reason that you are basically trying to map two unknowns together. In your generic object the type is unknown, and in your datareader the table is unknown. So what I would suggest is you create some kind of column attribute to attach to the properties of you entity. And then look through those property attributes and try to look up the data from those attributes in the datareader. Your biggest problem is going to be, what happens if one of the properties isn't found in the reader, or vice-versa, one of the columns in the reader isn't found in the entity. Good luck, but if you want to do something like this, you probably want a ORM or at the very least some kind of Active Record implementation.
Question: How can I map a DataReader object into a class object by using generics? For example I need to do the following: ``` public class Mapper<T> { public static List<T> MapObject(IDataReader dr) { List<T> objects = new List<T>(); while (dr.Read()) { //Mapping goes here... } return objects; } } ``` And later I need to call this class-method like the following: ``` IDataReder dataReader = DBUtil.Fetchdata("SELECT * FROM Book"); List<Book> bookList = Mapper<Book>.MapObject(dataReder); foreach (Book b in bookList) { Console.WriteLine(b.ID + ", " + b.BookName); } ``` Note that, the Mapper - class should be able to map object of any type represented by T. Answer:
Well, i don't know if it fits here, but you could be using the yield keyword ``` public static IEnumerable<T> MapObject(IDataReader dr, Func<IDataReader, T> convertFunction) { while (dr.Read()) { yield return convertFunction(dr); } } ```
I don't think you'll be able to get around defining the relationship between fields in some form. Take a look at this article and pay particular attention to how the mapping is defined, it may work for you. <http://www.c-sharpcorner.com/UploadFile/rmcochran/elegant_dal05212006130957PM/elegant_dal.aspx>
Question: How can I map a DataReader object into a class object by using generics? For example I need to do the following: ``` public class Mapper<T> { public static List<T> MapObject(IDataReader dr) { List<T> objects = new List<T>(); while (dr.Read()) { //Mapping goes here... } return objects; } } ``` And later I need to call this class-method like the following: ``` IDataReder dataReader = DBUtil.Fetchdata("SELECT * FROM Book"); List<Book> bookList = Mapper<Book>.MapObject(dataReder); foreach (Book b in bookList) { Console.WriteLine(b.ID + ", " + b.BookName); } ``` Note that, the Mapper - class should be able to map object of any type represented by T. Answer:
I use [ValueInjecter](http://valueinjecter.codeplex.com/) for this I'm doing like this: ``` while (dr.Read()) { var o = new User(); o.InjectFrom<DataReaderInjection>(dr); yield return o; } ``` you gonna need this ValueInjection for this to work: ``` public class DataReaderInjection : KnownSourceValueInjection<IDataReader> { protected override void Inject(IDataReader source, object target, PropertyDescriptorCollection targetProps) { for (var i = 0; i < source.FieldCount; i++) { var activeTarget = targetProps.GetByName(source.GetName(i), true); if (activeTarget == null) continue; var value = source.GetValue(i); if (value == DBNull.Value) continue; activeTarget.SetValue(target, value); } } } ```
I don't think you'll be able to get around defining the relationship between fields in some form. Take a look at this article and pay particular attention to how the mapping is defined, it may work for you. <http://www.c-sharpcorner.com/UploadFile/rmcochran/elegant_dal05212006130957PM/elegant_dal.aspx>
Question: How can I map a DataReader object into a class object by using generics? For example I need to do the following: ``` public class Mapper<T> { public static List<T> MapObject(IDataReader dr) { List<T> objects = new List<T>(); while (dr.Read()) { //Mapping goes here... } return objects; } } ``` And later I need to call this class-method like the following: ``` IDataReder dataReader = DBUtil.Fetchdata("SELECT * FROM Book"); List<Book> bookList = Mapper<Book>.MapObject(dataReder); foreach (Book b in bookList) { Console.WriteLine(b.ID + ", " + b.BookName); } ``` Note that, the Mapper - class should be able to map object of any type represented by T. Answer:
Well, i don't know if it fits here, but you could be using the yield keyword ``` public static IEnumerable<T> MapObject(IDataReader dr, Func<IDataReader, T> convertFunction) { while (dr.Read()) { yield return convertFunction(dr); } } ```
I would recommend that you'd use [AutoMapper](http://automapper.codeplex.com/) for this.
Question: How can I map a DataReader object into a class object by using generics? For example I need to do the following: ``` public class Mapper<T> { public static List<T> MapObject(IDataReader dr) { List<T> objects = new List<T>(); while (dr.Read()) { //Mapping goes here... } return objects; } } ``` And later I need to call this class-method like the following: ``` IDataReder dataReader = DBUtil.Fetchdata("SELECT * FROM Book"); List<Book> bookList = Mapper<Book>.MapObject(dataReder); foreach (Book b in bookList) { Console.WriteLine(b.ID + ", " + b.BookName); } ``` Note that, the Mapper - class should be able to map object of any type represented by T. Answer:
Well, i don't know if it fits here, but you could be using the yield keyword ``` public static IEnumerable<T> MapObject(IDataReader dr, Func<IDataReader, T> convertFunction) { while (dr.Read()) { yield return convertFunction(dr); } } ```
Have a look at <http://CapriSoft.CodePlex.com>
Question: Every time i am trying to run the following PHP code on 000Webhost, i keep getting this error -- mysqli\_num\_rows() expects parameter 1 to be mysqli\_result. The same code had been run successfully without errors on my localhost, XAMPP, i have looked through many examples and only found out that this error is caused by an error in the query, but as mentioned, the query works perfectly on my localhost. The error is indicated in the code. Any help would be appreciated. ``` <?php session_start(); //decalre variables $DeviceID =""; $productID =""; //connect to database $db = mysqli_connect('localhost','id5655845_grocerywatch1234','123456','id5655845_grocerywatch1234'); //validate product id and device id are avaliable if(isset($_POST['validate_user'])){ $DeviceID = mysqli_real_escape_string($db,$_POST['DeviceID']); $productID = mysqli_real_escape_string($db,$_POST['productID']); $query = "SELECT * FROM configuration WHERE DeviceID='$DeviceID' AND productID='$productID'"; $result1 = mysqli_query($db,$query); echo $query; //error indicated on the following line. if(mysqli_num_rows($result1) == 1){ $_SESSION['DeviceID'] = $DeviceID; $_SESSION['success'] = "You are now logged in"; header('location: register.php'); } else{ echo "Device Not registered"; echo "Product Doesnt Exist"; } } ``` Answer:
I think your query is likely failing. The return value for `mysqli_query` is `False` on failure, otherwise it is `mysqli_result`. See [docs here](http://php.net/manual/en/mysqli.query.php) Fix by properly formatting string: ``` ... $query = "SELECT * FROM configuration WHERE DeviceID='".$DeviceID."' AND productID='".$productID."'"; $result1 = mysqli_query($db,$query); echo $query; if ($result1 == false){ echo "Error has occurred!"; } elseif (mysqli_num_rows($result1) == 1){ $_SESSION['DeviceID'] = $DeviceID; $_SESSION['success'] = "You are now logged in"; header('Location: register.php'); } else{ echo "Device Not registered"; echo "Product Doesnt Exist"; } ```
The query either returned no rows or is erroneus, thus FALSE is returned. Change it to ``` if (!$dbc || mysqli_num_rows($dbc) == 0) ``` > > Return Values > > > Returns TRUE on success or FALSE on failure. For SELECT, SHOW, > DESCRIBE or EXPLAIN mysqli\_query() will return a result object. > > >
Question: Is there a way to do something like this using FluentAssertions ``` response.Satisfy(r => r.Property1== "something" && r.Property2== "anotherthing")); ``` I am trying to avoid writing multiple Assert statements. This was possible with <https://sharptestex.codeplex.com/> which I was using for the longest time. But SharpTestEx does not support .Net Core. Answer:
You should be able to use general purpose `Match` assertion to verify multiple properties of the subject via a predicate ``` response.Should() .Match<MyResponseObject>((x) => x.Property1 == "something" && x.Property2 == "anotherthing" ); ```
I use an extension function for this that works similarly to [`SatisfyRespectively()`](https://github.com/fluentassertions/fluentassertions/blob/c79b57af493ad4bcb29247678453138261301df1/Src/FluentAssertions/Collections/SelfReferencingCollectionAssertions.cs#L695): ```cs public static class FluentAssertionsExt { public static AndConstraint<ObjectAssertions> Satisfy( this ObjectAssertions parent, Action<MyClass> inspector) { inspector((MyClass)parent.Subject); return new AndConstraint<ObjectAssertions>(parent); } } ``` Here is how I use it: ```cs [TestMethod] public void FindsMethodGeneratedForLambda() => Method(x => x.Lambda()) .CollectGeneratedMethods(visited: empty) .Should().ContainSingle().Which .Should().Satisfy(m => m.Name.Should().Match("<Lambda>*")) .And.Satisfy(m => m.DeclaringType.Name.Should().Be("<>c")); [TestMethod] public void FindsMethodGeneratedForClosure() => Method(x => x.Closure(0)) .CollectGeneratedMethods(visited: empty) .Should().HaveCount(2).And.SatisfyRespectively( fst => fst.Should() .Satisfy(m => m.Name.Should().Be(".ctor")) .And.Satisfy(m => m.DeclaringType.Name.Should().Match("<>c__DisplayClass*")), snd => snd.Should() .Satisfy(m => m.Name.Should().Match("<Closure>*")) .And.Satisfy(m => m.DeclaringType.Name.Should().Match("<>c__DisplayClass*"))); ``` Unfortunately this doesn't generalize very well due to FluentAssertions' design, so you might have to provide multiple overloads of this method with different types in place of `MyClass`. I think the truly correct way however is to implement an `*Assertions` type for the type you want to run such assertions against. The documentation provides [an example](https://fluentassertions.com/extensibility/): ```cs public static class DirectoryInfoExtensions { public static DirectoryInfoAssertions Should(this DirectoryInfo instance) { return new DirectoryInfoAssertions(instance); } } public class DirectoryInfoAssertions : ReferenceTypeAssertions<DirectoryInfo, DirectoryInfoAssertions> { public DirectoryInfoAssertions(DirectoryInfo instance) { Subject = instance; } protected override string Identifier => "directory"; public AndConstraint<DirectoryInfoAssertions> ContainFile( string filename, string because = "", params object[] becauseArgs) { Execute.Assertion .BecauseOf(because, becauseArgs) .ForCondition(!string.IsNullOrEmpty(filename)) .FailWith("You can't assert a file exist if you don't pass a proper name") .Then .Given(() => Subject.GetFiles()) .ForCondition(files => files.Any(fileInfo => fileInfo.Name.Equals(filename))) .FailWith("Expected {context:directory} to contain {0}{reason}, but found {1}.", _ => filename, files => files.Select(file => file.Name)); return new AndConstraint<DirectoryInfoAssertions>(this); } } ```
Question: Is there a way to do something like this using FluentAssertions ``` response.Satisfy(r => r.Property1== "something" && r.Property2== "anotherthing")); ``` I am trying to avoid writing multiple Assert statements. This was possible with <https://sharptestex.codeplex.com/> which I was using for the longest time. But SharpTestEx does not support .Net Core. Answer:
You should be able to use general purpose `Match` assertion to verify multiple properties of the subject via a predicate ``` response.Should() .Match<MyResponseObject>((x) => x.Property1 == "something" && x.Property2 == "anotherthing" ); ```
Assuming you use xUnit, you can just solve it by inheriting from the right base class. There is no need for an implementation change in your tests. Here is how this works: ``` public class UnitTest1 : TestBase { [Fact] public void Test1() { string x = "A"; string y = "B"; string expectedX = "a"; string expectedY = "b"; x.Should().Be(expectedX); y.Should().Be(expectedY); } } public class TestBase : IDisposable { private AssertionScope scope; public TestBase() { scope = new AssertionScope(); } public void Dispose() { scope.Dispose(); } } ``` Alternatively, you can just wrap your expectations into a ValueTuple. Here is how: ``` [Fact] public void Test2() { string x = "A"; string y = "B"; string expectedX = "a"; string expectedY = "b"; (x, y).Should().Be((expectedX, expectedY)); } ```
Question: Is there a way to do something like this using FluentAssertions ``` response.Satisfy(r => r.Property1== "something" && r.Property2== "anotherthing")); ``` I am trying to avoid writing multiple Assert statements. This was possible with <https://sharptestex.codeplex.com/> which I was using for the longest time. But SharpTestEx does not support .Net Core. Answer:
The `.Match()` solution does not return a good error message. So if you want to have a good error and **only one** assert then use: ``` result.Should().BeEquivalentTo(new MyResponseObject() { Property1 = "something", Property2 = "anotherthing" }); ``` **Anonymous objects** (*use with care!*) If you want to only check certain members then use: ``` result.Should().BeEquivalentTo(new { Property1 = "something", Property2 = "anotherthing" }, options => options.ExcludingMissingMembers()); ``` > > Note: You will miss (new) members when testing like this. So only use if you > really want to check only certain members now and in the future. Not > using the exclude option will force you to edit your test when a new > property is added and that can be a good thing > > > **Multiple asserts** > > *Note*: **All given solutions gives you one line asserts. In my opinion there is nothing wrong with multiple lines of asserts as long > as it is one assert functionally.** > > > If you want this because you want multiple errors at once, consider wrapping your multi line assertions in an `AssertionScope`. ``` using (new AssertionScope()) { result.Property1.Should().Be("something"); result.Property2.Should().Be("anotherthing"); } ``` Above statement will now give both errors at once, if they both fail. <https://fluentassertions.com/introduction#assertion-scopes>
I use an extension function for this that works similarly to [`SatisfyRespectively()`](https://github.com/fluentassertions/fluentassertions/blob/c79b57af493ad4bcb29247678453138261301df1/Src/FluentAssertions/Collections/SelfReferencingCollectionAssertions.cs#L695): ```cs public static class FluentAssertionsExt { public static AndConstraint<ObjectAssertions> Satisfy( this ObjectAssertions parent, Action<MyClass> inspector) { inspector((MyClass)parent.Subject); return new AndConstraint<ObjectAssertions>(parent); } } ``` Here is how I use it: ```cs [TestMethod] public void FindsMethodGeneratedForLambda() => Method(x => x.Lambda()) .CollectGeneratedMethods(visited: empty) .Should().ContainSingle().Which .Should().Satisfy(m => m.Name.Should().Match("<Lambda>*")) .And.Satisfy(m => m.DeclaringType.Name.Should().Be("<>c")); [TestMethod] public void FindsMethodGeneratedForClosure() => Method(x => x.Closure(0)) .CollectGeneratedMethods(visited: empty) .Should().HaveCount(2).And.SatisfyRespectively( fst => fst.Should() .Satisfy(m => m.Name.Should().Be(".ctor")) .And.Satisfy(m => m.DeclaringType.Name.Should().Match("<>c__DisplayClass*")), snd => snd.Should() .Satisfy(m => m.Name.Should().Match("<Closure>*")) .And.Satisfy(m => m.DeclaringType.Name.Should().Match("<>c__DisplayClass*"))); ``` Unfortunately this doesn't generalize very well due to FluentAssertions' design, so you might have to provide multiple overloads of this method with different types in place of `MyClass`. I think the truly correct way however is to implement an `*Assertions` type for the type you want to run such assertions against. The documentation provides [an example](https://fluentassertions.com/extensibility/): ```cs public static class DirectoryInfoExtensions { public static DirectoryInfoAssertions Should(this DirectoryInfo instance) { return new DirectoryInfoAssertions(instance); } } public class DirectoryInfoAssertions : ReferenceTypeAssertions<DirectoryInfo, DirectoryInfoAssertions> { public DirectoryInfoAssertions(DirectoryInfo instance) { Subject = instance; } protected override string Identifier => "directory"; public AndConstraint<DirectoryInfoAssertions> ContainFile( string filename, string because = "", params object[] becauseArgs) { Execute.Assertion .BecauseOf(because, becauseArgs) .ForCondition(!string.IsNullOrEmpty(filename)) .FailWith("You can't assert a file exist if you don't pass a proper name") .Then .Given(() => Subject.GetFiles()) .ForCondition(files => files.Any(fileInfo => fileInfo.Name.Equals(filename))) .FailWith("Expected {context:directory} to contain {0}{reason}, but found {1}.", _ => filename, files => files.Select(file => file.Name)); return new AndConstraint<DirectoryInfoAssertions>(this); } } ```
Question: Is there a way to do something like this using FluentAssertions ``` response.Satisfy(r => r.Property1== "something" && r.Property2== "anotherthing")); ``` I am trying to avoid writing multiple Assert statements. This was possible with <https://sharptestex.codeplex.com/> which I was using for the longest time. But SharpTestEx does not support .Net Core. Answer:
The `.Match()` solution does not return a good error message. So if you want to have a good error and **only one** assert then use: ``` result.Should().BeEquivalentTo(new MyResponseObject() { Property1 = "something", Property2 = "anotherthing" }); ``` **Anonymous objects** (*use with care!*) If you want to only check certain members then use: ``` result.Should().BeEquivalentTo(new { Property1 = "something", Property2 = "anotherthing" }, options => options.ExcludingMissingMembers()); ``` > > Note: You will miss (new) members when testing like this. So only use if you > really want to check only certain members now and in the future. Not > using the exclude option will force you to edit your test when a new > property is added and that can be a good thing > > > **Multiple asserts** > > *Note*: **All given solutions gives you one line asserts. In my opinion there is nothing wrong with multiple lines of asserts as long > as it is one assert functionally.** > > > If you want this because you want multiple errors at once, consider wrapping your multi line assertions in an `AssertionScope`. ``` using (new AssertionScope()) { result.Property1.Should().Be("something"); result.Property2.Should().Be("anotherthing"); } ``` Above statement will now give both errors at once, if they both fail. <https://fluentassertions.com/introduction#assertion-scopes>
Assuming you use xUnit, you can just solve it by inheriting from the right base class. There is no need for an implementation change in your tests. Here is how this works: ``` public class UnitTest1 : TestBase { [Fact] public void Test1() { string x = "A"; string y = "B"; string expectedX = "a"; string expectedY = "b"; x.Should().Be(expectedX); y.Should().Be(expectedY); } } public class TestBase : IDisposable { private AssertionScope scope; public TestBase() { scope = new AssertionScope(); } public void Dispose() { scope.Dispose(); } } ``` Alternatively, you can just wrap your expectations into a ValueTuple. Here is how: ``` [Fact] public void Test2() { string x = "A"; string y = "B"; string expectedX = "a"; string expectedY = "b"; (x, y).Should().Be((expectedX, expectedY)); } ```
Question: When user is typing in `UITextfield`, and he stops for 2 seconds, the cursor is still on `UITextfield`, so how we can identify this event? i.e. I want to check the whether the editing is end or not without resigning the first responser from that `UITextField`. What is the way to do that? Answer:
Yes, we can check that! with `UITextField` delegate, `- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string` ``` - (void) callMeAfterTwoSeconds { NSLog(@"I'll call after two seconds of inactivity!"); } - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { [NSRunLoop cancelPreviousPerformRequestsWithTarget:self]; [self performSelector:@selector(callMeAfterTwoSeconds) withObject:nil afterDelay:2.0]; return YES; } ``` While you're typing (tapping keys from keyboard), it will cancel previous calls for the `callMeAfterTwoSeconds` function, once you stop, it sets it to call after 2 seconds delay, and yes, it will call after 2 seconds. **Update:** Even you can pass that textfield as object to `performSelector` to know which textfield is inactive, for that your `callMeAfterTwoSeconds` function will be like, ``` - (void) callMeAfterTwoSeconds:(UITextField *)textfield { if(textfield == txtUserName) { NSLog(@"User textfield has NO activity from last two seconds!"); } } ```
Go to the connections inspector of your `UITextField` and connect the "Editing Changed" from the Sent Events list to a predefined `IBAction` of your choice. Alternatively you can do it programmatically if you are not working with Storyboard. ``` [youTextField addTarget:self action:@selector(textFieldInputDidChange:) forControlEvents:UIControlEventEditingChanged]; ``` Now the `IBAction` you've just connected will be fired every time the user changes a character in the `UITextField`. Create a [timer](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html) as ivar. Now every time `IBAction` gets called, start the timer, if it will hit 2sec without being restarted by a new call you know the user hasn't entered/deleted values in the `UITextField`.
Question: When user is typing in `UITextfield`, and he stops for 2 seconds, the cursor is still on `UITextfield`, so how we can identify this event? i.e. I want to check the whether the editing is end or not without resigning the first responser from that `UITextField`. What is the way to do that? Answer:
Go to the connections inspector of your `UITextField` and connect the "Editing Changed" from the Sent Events list to a predefined `IBAction` of your choice. Alternatively you can do it programmatically if you are not working with Storyboard. ``` [youTextField addTarget:self action:@selector(textFieldInputDidChange:) forControlEvents:UIControlEventEditingChanged]; ``` Now the `IBAction` you've just connected will be fired every time the user changes a character in the `UITextField`. Create a [timer](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html) as ivar. Now every time `IBAction` gets called, start the timer, if it will hit 2sec without being restarted by a new call you know the user hasn't entered/deleted values in the `UITextField`.
I don't think that calling `[NSRunLoop cancelPreviousPerformRequestsWithTarget:self]` is a good practice. Instead I would do: ``` [self.searchTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged]; //or select the textfield in the storyboard, go to connections inspector and choose the target for 'Editing Changed' - (IBAction)textFieldDidChange:(id)sender { [self performSelector:@selector(editingChanged:) withObject:self.searchTextField.text afterDelay:2.0]; } - (void)editingChanged:(NSString *)text { if ([text isEqualToString:self.searchTextField.text]) { //do your thing } } ``` this way the user can type and it will trigger a call to `editingChanged:`, then you can double check if the value changed meanwhile, and if it didn't then the user stopped typing for 2 seconds.
Question: When user is typing in `UITextfield`, and he stops for 2 seconds, the cursor is still on `UITextfield`, so how we can identify this event? i.e. I want to check the whether the editing is end or not without resigning the first responser from that `UITextField`. What is the way to do that? Answer:
Go to the connections inspector of your `UITextField` and connect the "Editing Changed" from the Sent Events list to a predefined `IBAction` of your choice. Alternatively you can do it programmatically if you are not working with Storyboard. ``` [youTextField addTarget:self action:@selector(textFieldInputDidChange:) forControlEvents:UIControlEventEditingChanged]; ``` Now the `IBAction` you've just connected will be fired every time the user changes a character in the `UITextField`. Create a [timer](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html) as ivar. Now every time `IBAction` gets called, start the timer, if it will hit 2sec without being restarted by a new call you know the user hasn't entered/deleted values in the `UITextField`.
I did this for a searchBar, but I think it works for an UITextField too. The code is in Swift. :) ``` func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { searchTimer?.invalidate() searchTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("search"), userInfo: nil, repeats: false) } func search() { println("search \(searchBar.text)") } ```
Question: When user is typing in `UITextfield`, and he stops for 2 seconds, the cursor is still on `UITextfield`, so how we can identify this event? i.e. I want to check the whether the editing is end or not without resigning the first responser from that `UITextField`. What is the way to do that? Answer:
Yes, we can check that! with `UITextField` delegate, `- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string` ``` - (void) callMeAfterTwoSeconds { NSLog(@"I'll call after two seconds of inactivity!"); } - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { [NSRunLoop cancelPreviousPerformRequestsWithTarget:self]; [self performSelector:@selector(callMeAfterTwoSeconds) withObject:nil afterDelay:2.0]; return YES; } ``` While you're typing (tapping keys from keyboard), it will cancel previous calls for the `callMeAfterTwoSeconds` function, once you stop, it sets it to call after 2 seconds delay, and yes, it will call after 2 seconds. **Update:** Even you can pass that textfield as object to `performSelector` to know which textfield is inactive, for that your `callMeAfterTwoSeconds` function will be like, ``` - (void) callMeAfterTwoSeconds:(UITextField *)textfield { if(textfield == txtUserName) { NSLog(@"User textfield has NO activity from last two seconds!"); } } ```
I don't think that calling `[NSRunLoop cancelPreviousPerformRequestsWithTarget:self]` is a good practice. Instead I would do: ``` [self.searchTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged]; //or select the textfield in the storyboard, go to connections inspector and choose the target for 'Editing Changed' - (IBAction)textFieldDidChange:(id)sender { [self performSelector:@selector(editingChanged:) withObject:self.searchTextField.text afterDelay:2.0]; } - (void)editingChanged:(NSString *)text { if ([text isEqualToString:self.searchTextField.text]) { //do your thing } } ``` this way the user can type and it will trigger a call to `editingChanged:`, then you can double check if the value changed meanwhile, and if it didn't then the user stopped typing for 2 seconds.
Question: When user is typing in `UITextfield`, and he stops for 2 seconds, the cursor is still on `UITextfield`, so how we can identify this event? i.e. I want to check the whether the editing is end or not without resigning the first responser from that `UITextField`. What is the way to do that? Answer:
Yes, we can check that! with `UITextField` delegate, `- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string` ``` - (void) callMeAfterTwoSeconds { NSLog(@"I'll call after two seconds of inactivity!"); } - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { [NSRunLoop cancelPreviousPerformRequestsWithTarget:self]; [self performSelector:@selector(callMeAfterTwoSeconds) withObject:nil afterDelay:2.0]; return YES; } ``` While you're typing (tapping keys from keyboard), it will cancel previous calls for the `callMeAfterTwoSeconds` function, once you stop, it sets it to call after 2 seconds delay, and yes, it will call after 2 seconds. **Update:** Even you can pass that textfield as object to `performSelector` to know which textfield is inactive, for that your `callMeAfterTwoSeconds` function will be like, ``` - (void) callMeAfterTwoSeconds:(UITextField *)textfield { if(textfield == txtUserName) { NSLog(@"User textfield has NO activity from last two seconds!"); } } ```
I did this for a searchBar, but I think it works for an UITextField too. The code is in Swift. :) ``` func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { searchTimer?.invalidate() searchTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("search"), userInfo: nil, repeats: false) } func search() { println("search \(searchBar.text)") } ```
Question: When user is typing in `UITextfield`, and he stops for 2 seconds, the cursor is still on `UITextfield`, so how we can identify this event? i.e. I want to check the whether the editing is end or not without resigning the first responser from that `UITextField`. What is the way to do that? Answer:
I did this for a searchBar, but I think it works for an UITextField too. The code is in Swift. :) ``` func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { searchTimer?.invalidate() searchTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("search"), userInfo: nil, repeats: false) } func search() { println("search \(searchBar.text)") } ```
I don't think that calling `[NSRunLoop cancelPreviousPerformRequestsWithTarget:self]` is a good practice. Instead I would do: ``` [self.searchTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged]; //or select the textfield in the storyboard, go to connections inspector and choose the target for 'Editing Changed' - (IBAction)textFieldDidChange:(id)sender { [self performSelector:@selector(editingChanged:) withObject:self.searchTextField.text afterDelay:2.0]; } - (void)editingChanged:(NSString *)text { if ([text isEqualToString:self.searchTextField.text]) { //do your thing } } ``` this way the user can type and it will trigger a call to `editingChanged:`, then you can double check if the value changed meanwhile, and if it didn't then the user stopped typing for 2 seconds.
Question: I am struggling at understanding how is called the time signature in funk where the eighth note is divided in 3 and only the 1st and 3rd are played...sixteenth note triplets. In jazz it would be eighth note triplets I guess. Is that shuffle ? Thanks for your clarification. Answer:
Two "rules" immediately come to mind that composers in the later nineteenth century (like Wagner) began to "break": "Illegal" Six-Four Chords ------------------------- In the common-practice style, there are four types of acceptable six-four (second-inversion) chords. Because the fourth was a dissonance, chords with this fourth in the bass (like second-inversion triads) had to be treated with special care. These six-four chords were only acceptable if the bass of the six-four chord was either a) passing between two pitches a third apart, b) a pedal tone connecting two of the same pitch, or c) arpeggiating a given harmony. (The fourth type of six-four, the "cadential" six-four, is a subset of the pedal six-four.) But in the nineteenth century, composers began relaxing these rules. Even as early as Mendelssohn we encounter six-four chords whose bass pitches are approached and left by leap in nontraditional ways, which would otherwise be unheard of in the Classical style. Resolving Chordal Sevenths -------------------------- Chordal sevenths are dissonances, and as such they must be resolved properly: down by step. But a bit before Wagner we begin to see composers treated these resolutions very loosely, and by the time we get to the late nineteenth century we encounter plenty of composers that no longer choose to resolve (let alone prepare) their chordal sevenths accurately. These days, these resolutions are hit and miss; you can still hear their correct resolutions in something like jazz, but in something like blues the sevenths are often left hanging without a "proper" classical resolution. On "Objection" -------------- But just because these rules were "broken" doesn't necessarily mean that discerning listeners objected to these rules. Rather, the loosening of these rules simply signaled a new musical style, and for that we should be thankful: without that new musical style we wouldn't have so much of the music we have today.
Echoing a comment from @Todd Wilcox earlier, there really are no rules. It's important to recognize that everything we have learned in music theory is *descriptive,* not *prescriptive*. It exists to explain what was done in the past, not what "should be done" now. It has quite a bit of value, of course. With theory we can explain how common-practice music functioned, what things were expected by an audience, and what things might have been surprises. But there has always been a large gap between theory that describes what has been done, and composers who write in the here and now. That said, western tonal music has made a gradual shift from largely consonant [triad-based, mostly major and minor] textures with strictly controlled dissonances in the Renaissance, to chordal sevenths and diminshed chords in the Baroque, towards more and more dissonant music through the Classical and Romantic periods and into the 20th century. All the time some composers have written conservatively within the bounds of what is expected and others have pushed into uncharted territory.
Question: I am struggling at understanding how is called the time signature in funk where the eighth note is divided in 3 and only the 1st and 3rd are played...sixteenth note triplets. In jazz it would be eighth note triplets I guess. Is that shuffle ? Thanks for your clarification. Answer:
It isn't really rules of the 19th century that your are asking about. The "rules" you mention like preparing dissonance and parallel part writing are 17th and 18th century practices. The origin of those rules in the old contrapuntal style of composition for the Church. As music moved into the secular realm, composers gradual adhered less and less to those old conventions. By the early to mid 19th century you can find examples from composers like Berlioz and Chopin which make clear composers were exploring musical possibilities that did not depend on the old Church style. They could explore other styles unapologetically. You might say that rather than there being "rules of the 19th century" the period was about "discarding the rulebook." > > ...we, the discriminating, would object... > > > As far as objections go you might be interested to read about the opposing schools of composers like [Schumann and Brahms versus Liszt and Wagner](https://en.wikipedia.org/wiki/War_of_the_Romantics). Schumann and Brahms were the conservatives and Liszt and Wagner were the "new school" progressives. There was no one large body of listeners the new school departed from in terms of style. And it certainly wasn't a matter of "the discriminating", as in "discriminating taste", where the difference between the two schools could be explained as a matter of good and bad taste. Sure, the rhetoric the two sides used was full of condemnation, but a retrospective view sees it all as partisan politics, two sides jockeying for superiority. The reality is the two sides had different musical aims, different aesthetics, and they used different compositional methods to achieve those aims. So, what I'm trying to get at is the objection to Wagner wasn't *really* about deviating from old 17th and 18th century conventions, it was a partisan opposition to a new school of music on the rise. If you want to get into actual musical devices and the opposing schools, probably the most important thing to look at is *formalism* versus *program music.* It wasn't part writing issues like dissonance treatment or parallelism, all of the composers involve were perfectly capable of following part writing conventions, the issue was much deeper and fundamental: is music experienced in absolute terms through the *internal* relationship of elements, like the *recapitulation* of a subject, or by evoking reactions *external* to the music by sounds that convey scenes, actions, or moods? It's similar to representational versus abstract/non-representation work in the visual arts. Conservative 19th century composers and critics objected to non-formal musical depictions external to the music.
Echoing a comment from @Todd Wilcox earlier, there really are no rules. It's important to recognize that everything we have learned in music theory is *descriptive,* not *prescriptive*. It exists to explain what was done in the past, not what "should be done" now. It has quite a bit of value, of course. With theory we can explain how common-practice music functioned, what things were expected by an audience, and what things might have been surprises. But there has always been a large gap between theory that describes what has been done, and composers who write in the here and now. That said, western tonal music has made a gradual shift from largely consonant [triad-based, mostly major and minor] textures with strictly controlled dissonances in the Renaissance, to chordal sevenths and diminshed chords in the Baroque, towards more and more dissonant music through the Classical and Romantic periods and into the 20th century. All the time some composers have written conservatively within the bounds of what is expected and others have pushed into uncharted territory.
Question: I have a directory of files, some of them image files. Some of those image files are a sequence of images. They could be named `image-000001.png`, `image-000002.png` and so on, or perhaps `001_sequence.png`, `002_sequence.png` etc. How can we identify images that would, to a human, appear by their names to be fairly obviously in a sequence? This would mean identifying only those image filenames that have increasing numbers and all have a similar form of filename. The similar part of the filename would not be pre-defined. Answer:
I am guessing the issue is because of how you call join - ``` list = '_'.join(cur_list) ``` This would join the list cur\_list , with each element having a \_ in between them. So according to your code, you are getting correct result. If you do not want anything inbetween the strings in cur\_list , then use empty string for joining - ``` list = ''.join(cur_list) ```
When I read the following docstring for `join` in my Python 2.7.x installation... ``` S.join(iterable) -> string Return a string which is the concatenation of the strings in the iterable. The separator between elements is S. ``` ... I take it that `'_'.join('abc')` should always return 'a\_b\_c', because a `str` object is iterable. And that's what I get in my Python 2.7.x installation. I would replace your `list = '_'.join(cur_list)` line with this: ``` list += '_' + cur_list ```
Question: As part of the MSDN subscription I just got, I can download MS-DOS 6.22 (wow indeed). [![MSDN Screenshot](https://i.stack.imgur.com/3zAmm.png)](https://i.stack.imgur.com/3zAmm.png) I want to install it to a VirtualBox VM so I can try old games and viruses (due to viruses, I can't install it to DOSBox- some viruses would infect my actual files too), how can I do this? The file you can download is an .exe SFX file which outputs [these files](https://gist.github.com/ardaozkal/cb3f5cf69379c3d1c245c65970e7da9f). Answer:
``` C:\msdos\DISKS\144UPG1.IMG C:\msdos\DISKS\144UPG2.IMG C:\msdos\DISKS\144UPG3.IMG ``` From your listing, I believe these are 1.44 MB images of the installation floppies. In that case, installation is simple: 1. Create the virtual machine you intend to install MS-DOS on. 2. In the "Settings" dialog for the VM, select the "Storage" tab. Click on the "Empty" line below the "Controller: Floppy controller" option. 3. Click on the floppy-disk icon next to the "Floppy Device 0" dropdown menu and select "Choose a virtual floppy disk file" from the menu that appears. 4. Select `144UPG1.IMG`. 5. Boot the VM. It should start up using the virtual floppy as the boot disk. 6. Run the installer: `a:\setup` 7. Follow the prompts. When you need to switch disks, right-click on the floppy-disk icon at the bottom of your VM window, select "Choose a virtual floppy disk file", and select the image corresponding to the disk the installer is asking for.
I understand you asked about MS-DOS, but if FreeDOS would be acceptable, the following website has some handy pre-installed VDI images of FreeDOS. <https://www.lazybrowndog.net/freedos/virtualbox/>
Question: As part of the MSDN subscription I just got, I can download MS-DOS 6.22 (wow indeed). [![MSDN Screenshot](https://i.stack.imgur.com/3zAmm.png)](https://i.stack.imgur.com/3zAmm.png) I want to install it to a VirtualBox VM so I can try old games and viruses (due to viruses, I can't install it to DOSBox- some viruses would infect my actual files too), how can I do this? The file you can download is an .exe SFX file which outputs [these files](https://gist.github.com/ardaozkal/cb3f5cf69379c3d1c245c65970e7da9f). Answer:
``` C:\msdos\DISKS\144UPG1.IMG C:\msdos\DISKS\144UPG2.IMG C:\msdos\DISKS\144UPG3.IMG ``` From your listing, I believe these are 1.44 MB images of the installation floppies. In that case, installation is simple: 1. Create the virtual machine you intend to install MS-DOS on. 2. In the "Settings" dialog for the VM, select the "Storage" tab. Click on the "Empty" line below the "Controller: Floppy controller" option. 3. Click on the floppy-disk icon next to the "Floppy Device 0" dropdown menu and select "Choose a virtual floppy disk file" from the menu that appears. 4. Select `144UPG1.IMG`. 5. Boot the VM. It should start up using the virtual floppy as the boot disk. 6. Run the installer: `a:\setup` 7. Follow the prompts. When you need to switch disks, right-click on the floppy-disk icon at the bottom of your VM window, select "Choose a virtual floppy disk file", and select the image corresponding to the disk the installer is asking for.
I can't tell from your screenshot if you can download them as .img or .iso's, but if you have a .iso version of MS-DOS, you can create your virtual machine, then go to storage and select the CD icon. Find your .iso file and open/attach it. It should then boot-up when you hit "start". It may be necessary to **un-check** the "Enable VT-x/AMD-V" checkbox under the "System" section in the "Acceleration" tab because you may get an error when running or installing DOS with acceleration. You don't need this option anyway because DOS should run pretty fast on your computer.
Question: As part of the MSDN subscription I just got, I can download MS-DOS 6.22 (wow indeed). [![MSDN Screenshot](https://i.stack.imgur.com/3zAmm.png)](https://i.stack.imgur.com/3zAmm.png) I want to install it to a VirtualBox VM so I can try old games and viruses (due to viruses, I can't install it to DOSBox- some viruses would infect my actual files too), how can I do this? The file you can download is an .exe SFX file which outputs [these files](https://gist.github.com/ardaozkal/cb3f5cf69379c3d1c245c65970e7da9f). Answer:
I understand you asked about MS-DOS, but if FreeDOS would be acceptable, the following website has some handy pre-installed VDI images of FreeDOS. <https://www.lazybrowndog.net/freedos/virtualbox/>
I can't tell from your screenshot if you can download them as .img or .iso's, but if you have a .iso version of MS-DOS, you can create your virtual machine, then go to storage and select the CD icon. Find your .iso file and open/attach it. It should then boot-up when you hit "start". It may be necessary to **un-check** the "Enable VT-x/AMD-V" checkbox under the "System" section in the "Acceleration" tab because you may get an error when running or installing DOS with acceleration. You don't need this option anyway because DOS should run pretty fast on your computer.
Question: I am in the process of creating a simple javascript file that counts down from 20 to 0. I am stuck on how to fix it. Here is my code, any help is really appreciated! ```js var count; document.write("Starting Loop" + "<br />"); for (count = 20; count <= 0; count++) { document.write("Current Count : " + count + "<br / >"); //document.write("<br />"); } document.write("Loop stopped!"); ``` Answer:
The three clauses in a for-loop tell the following thing (in order): * What are the initial values? * How long do I keep going? * What do I change each iteration? In your particular case, you're starting the count at 20, you're continuing in the loop as long as the count is less than or equal to 0, and you're adding 1 to the count each time it loops. Since the second clause evaluates to false, the for-loop won't run! What you are looking for should be more like this: ``` for (count = 20; count >= 0; count--) ``` This will start the count at 20, continue as long as the count is greater than or equal to 0, and subtract 1 from the count on each iteration. Putting it all together... ```js var count; document.write("Starting Loop" + "<br />"); for (count = 20; count >= 0; count--) { document.write("Current Count : " + count + "<br / >"); } document.write("Loop stopped!"); ```
You issue is the counter is wrong. You have ``` for(count = 20; count <= 0; count++) ``` This is saying start at `count = 20`, until count is less or equal to zero, add 1 to count each time. That does not make any sense. Here's what you should use. ```js document.write("Starting Loop" + "<br />"); for (var count = 20; count >= 0; count--) { document.write("Current Count : " + count + "<br / >"); //document.write("<br />"); } document.write("Loop stopped!"); ```
Question: I am in the process of creating a simple javascript file that counts down from 20 to 0. I am stuck on how to fix it. Here is my code, any help is really appreciated! ```js var count; document.write("Starting Loop" + "<br />"); for (count = 20; count <= 0; count++) { document.write("Current Count : " + count + "<br / >"); //document.write("<br />"); } document.write("Loop stopped!"); ``` Answer:
You can use `setTimeout` and recursive function. `setTimeout` take two parameter, the function executed and the time in ms before execution. Here you can choose the delay between each iteration. ```js var counter=20; function countdown(counter) { if(counter>0) { counter--; setTimeout(function(){countdown(counter)},1000); console.log(counter); } } countdown(counter); ```
You issue is the counter is wrong. You have ``` for(count = 20; count <= 0; count++) ``` This is saying start at `count = 20`, until count is less or equal to zero, add 1 to count each time. That does not make any sense. Here's what you should use. ```js document.write("Starting Loop" + "<br />"); for (var count = 20; count >= 0; count--) { document.write("Current Count : " + count + "<br / >"); //document.write("<br />"); } document.write("Loop stopped!"); ```
Question: I know some of the tutorials for creating Xcode project templates, for example this one here: <http://robnapier.net/blog/project-templates-364> This is the best one I could find. All others basically repeat the same info, or are no longer up to date, or worse tell me that even they don't know what they're doing. Possibly useful tools that are linked to here and in other places are no longer available. I keep running into roadblocks, and would like to gather as much information as possible on the process of creating Xcode project templates. Info that is most importantly up to date (at least it must be relevant for Xcode 3 or higher). For example, what I'd like to see is: * a description of the TemplateChooser.plist and similar plist files and what these options do (in my case, once I add a TemplateChooser.plist, my project disappears from the Xcode project template list) * how to create a project template that references another .xcodeproj (when I do that, the other .xcodeproj appears in the project template list even though it doesn't use the special naming convention) * processes that can be applied, for example is it possible to run a script during the creating of a project from a template? This would be useful to unzip certain files into the newly created project. If you have the answer or suggestions to any of the issues above, I'd appreciate that. Otherwise any link to good Xcode project template resources would be highly recommended. Especially if there is an official documentation from Apple - I haven't found one yet which seems to imply that project templates are undocumented. Answer:
Have you seen these: <http://www.sodeso.nl/?p=895> <http://www.codeproject.com/KB/iPhone/CreatingXcodeProject.aspx> If you say you have searched, I'm pretty sure you've already seen the links but these are the best resources I could find with my 'googlabilities' You might try contact this guy - <http://linkedin.com/in/mottishneor> he has some related messages around the web The links suggested by FX are also not bad at all!
I don't have a Mac anymore, so this is as much as I can give you without testing this myself. As far as I can tell, Xcode templates are undocumented by Apple. * [This guy](http://briksoftware.com/blog/?p=28) has some [guides](http://briksoftware.com/blog/?p=66) for messing with Xcode templates but the info is pretty sparse. My suggestion for working with templateChooser.plist is to try to only edit that file in the interface builder. * [This guide](http://learngamedev.screenstepslive.com/spaces/learn-cocos2d-public-content/manuals/1601/lessons/13472-Create-a-Xcode-Project-Template-referencing-the-cocos2d-Project) is a good example of how to add a reference to another .xcodeproj. For the reason you were having trouble adding a reference to your project we probably need more information. * If you scroll way down in [this doc](http://www.mactech.com/articles/mactech/Vol.23/23.01/2301XCode/index.html) you can that each template already includes a script called myscript.sh. This script will show up in the scripts menu for projects built with that template. That isn't quite as convenient as running scripts automatically, but it's better than nothing. * In conclusion, Xcode template documentation is a nightmare. It looks like there are a lot of powerful features there, but they are obscured because of lack of user friendlyness and because documentation lags far behind Apples updates of Xcode. It just doesn't seem to be a priority for them. I hope this helps.
Question: I know some of the tutorials for creating Xcode project templates, for example this one here: <http://robnapier.net/blog/project-templates-364> This is the best one I could find. All others basically repeat the same info, or are no longer up to date, or worse tell me that even they don't know what they're doing. Possibly useful tools that are linked to here and in other places are no longer available. I keep running into roadblocks, and would like to gather as much information as possible on the process of creating Xcode project templates. Info that is most importantly up to date (at least it must be relevant for Xcode 3 or higher). For example, what I'd like to see is: * a description of the TemplateChooser.plist and similar plist files and what these options do (in my case, once I add a TemplateChooser.plist, my project disappears from the Xcode project template list) * how to create a project template that references another .xcodeproj (when I do that, the other .xcodeproj appears in the project template list even though it doesn't use the special naming convention) * processes that can be applied, for example is it possible to run a script during the creating of a project from a template? This would be useful to unzip certain files into the newly created project. If you have the answer or suggestions to any of the issues above, I'd appreciate that. Otherwise any link to good Xcode project template resources would be highly recommended. Especially if there is an official documentation from Apple - I haven't found one yet which seems to imply that project templates are undocumented. Answer:
Have you seen these: <http://www.sodeso.nl/?p=895> <http://www.codeproject.com/KB/iPhone/CreatingXcodeProject.aspx> If you say you have searched, I'm pretty sure you've already seen the links but these are the best resources I could find with my 'googlabilities' You might try contact this guy - <http://linkedin.com/in/mottishneor> he has some related messages around the web The links suggested by FX are also not bad at all!
And yet another video link <http://howtomakeiphoneapps.com/2010/10/how-to-make-custom-xcode-templates-with-video/>
Question: I know some of the tutorials for creating Xcode project templates, for example this one here: <http://robnapier.net/blog/project-templates-364> This is the best one I could find. All others basically repeat the same info, or are no longer up to date, or worse tell me that even they don't know what they're doing. Possibly useful tools that are linked to here and in other places are no longer available. I keep running into roadblocks, and would like to gather as much information as possible on the process of creating Xcode project templates. Info that is most importantly up to date (at least it must be relevant for Xcode 3 or higher). For example, what I'd like to see is: * a description of the TemplateChooser.plist and similar plist files and what these options do (in my case, once I add a TemplateChooser.plist, my project disappears from the Xcode project template list) * how to create a project template that references another .xcodeproj (when I do that, the other .xcodeproj appears in the project template list even though it doesn't use the special naming convention) * processes that can be applied, for example is it possible to run a script during the creating of a project from a template? This would be useful to unzip certain files into the newly created project. If you have the answer or suggestions to any of the issues above, I'd appreciate that. Otherwise any link to good Xcode project template resources would be highly recommended. Especially if there is an official documentation from Apple - I haven't found one yet which seems to imply that project templates are undocumented. Answer:
There is indeed little XCode template info out there. What I have found of interest are the following links (I documented myself on the topic, but haven't yet gone any further): * a Google Code search [reveals a few examples](http://www.google.com/codesearch?as_q=file%3ATemplateChooser.plist&btnG=Search+Code&hl=en&as_package=&as_lang=&as_filename=&as_class=&as_function=&as_license=&as_case=), but not much * in particular, I found interesting to look at the code provided by [Three20](http://three20.info/); they have some basic examples, like [here](https://github.com/jeanregisser/three20/blob/master/templates/source/Three20%20Class/Three20%20class/TemplateChooser.plist) * referencing another project worked for me, so maybe you could open a specific question about that giving more details? * there is information scattered on the [Apple mailing-lists](http://www.google.com/#sclient=psy&hl=en&q=TemplateChooser.plist+site%3Aapple.com&aq=f&aqi=&aql=&oq=&gs_rfai=&pbx=1&fp=ca05a7bb65e82229) * there is no official documentation from Apple, as is evidenced by the lack of results to [this query](http://www.google.com/#q=TemplateChooser.plist+site%3Adeveloper.apple.com) I'm sorry if this is not a Enlighting, concise answer. As you said, it's not well documented, and sources are all over the place. I just hope I could highlight some places to find information that your own searches might not have reached :)
I don't have a Mac anymore, so this is as much as I can give you without testing this myself. As far as I can tell, Xcode templates are undocumented by Apple. * [This guy](http://briksoftware.com/blog/?p=28) has some [guides](http://briksoftware.com/blog/?p=66) for messing with Xcode templates but the info is pretty sparse. My suggestion for working with templateChooser.plist is to try to only edit that file in the interface builder. * [This guide](http://learngamedev.screenstepslive.com/spaces/learn-cocos2d-public-content/manuals/1601/lessons/13472-Create-a-Xcode-Project-Template-referencing-the-cocos2d-Project) is a good example of how to add a reference to another .xcodeproj. For the reason you were having trouble adding a reference to your project we probably need more information. * If you scroll way down in [this doc](http://www.mactech.com/articles/mactech/Vol.23/23.01/2301XCode/index.html) you can that each template already includes a script called myscript.sh. This script will show up in the scripts menu for projects built with that template. That isn't quite as convenient as running scripts automatically, but it's better than nothing. * In conclusion, Xcode template documentation is a nightmare. It looks like there are a lot of powerful features there, but they are obscured because of lack of user friendlyness and because documentation lags far behind Apples updates of Xcode. It just doesn't seem to be a priority for them. I hope this helps.
Question: I know some of the tutorials for creating Xcode project templates, for example this one here: <http://robnapier.net/blog/project-templates-364> This is the best one I could find. All others basically repeat the same info, or are no longer up to date, or worse tell me that even they don't know what they're doing. Possibly useful tools that are linked to here and in other places are no longer available. I keep running into roadblocks, and would like to gather as much information as possible on the process of creating Xcode project templates. Info that is most importantly up to date (at least it must be relevant for Xcode 3 or higher). For example, what I'd like to see is: * a description of the TemplateChooser.plist and similar plist files and what these options do (in my case, once I add a TemplateChooser.plist, my project disappears from the Xcode project template list) * how to create a project template that references another .xcodeproj (when I do that, the other .xcodeproj appears in the project template list even though it doesn't use the special naming convention) * processes that can be applied, for example is it possible to run a script during the creating of a project from a template? This would be useful to unzip certain files into the newly created project. If you have the answer or suggestions to any of the issues above, I'd appreciate that. Otherwise any link to good Xcode project template resources would be highly recommended. Especially if there is an official documentation from Apple - I haven't found one yet which seems to imply that project templates are undocumented. Answer:
I don't have a Mac anymore, so this is as much as I can give you without testing this myself. As far as I can tell, Xcode templates are undocumented by Apple. * [This guy](http://briksoftware.com/blog/?p=28) has some [guides](http://briksoftware.com/blog/?p=66) for messing with Xcode templates but the info is pretty sparse. My suggestion for working with templateChooser.plist is to try to only edit that file in the interface builder. * [This guide](http://learngamedev.screenstepslive.com/spaces/learn-cocos2d-public-content/manuals/1601/lessons/13472-Create-a-Xcode-Project-Template-referencing-the-cocos2d-Project) is a good example of how to add a reference to another .xcodeproj. For the reason you were having trouble adding a reference to your project we probably need more information. * If you scroll way down in [this doc](http://www.mactech.com/articles/mactech/Vol.23/23.01/2301XCode/index.html) you can that each template already includes a script called myscript.sh. This script will show up in the scripts menu for projects built with that template. That isn't quite as convenient as running scripts automatically, but it's better than nothing. * In conclusion, Xcode template documentation is a nightmare. It looks like there are a lot of powerful features there, but they are obscured because of lack of user friendlyness and because documentation lags far behind Apples updates of Xcode. It just doesn't seem to be a priority for them. I hope this helps.
And yet another video link <http://howtomakeiphoneapps.com/2010/10/how-to-make-custom-xcode-templates-with-video/>
Question: I know some of the tutorials for creating Xcode project templates, for example this one here: <http://robnapier.net/blog/project-templates-364> This is the best one I could find. All others basically repeat the same info, or are no longer up to date, or worse tell me that even they don't know what they're doing. Possibly useful tools that are linked to here and in other places are no longer available. I keep running into roadblocks, and would like to gather as much information as possible on the process of creating Xcode project templates. Info that is most importantly up to date (at least it must be relevant for Xcode 3 or higher). For example, what I'd like to see is: * a description of the TemplateChooser.plist and similar plist files and what these options do (in my case, once I add a TemplateChooser.plist, my project disappears from the Xcode project template list) * how to create a project template that references another .xcodeproj (when I do that, the other .xcodeproj appears in the project template list even though it doesn't use the special naming convention) * processes that can be applied, for example is it possible to run a script during the creating of a project from a template? This would be useful to unzip certain files into the newly created project. If you have the answer or suggestions to any of the issues above, I'd appreciate that. Otherwise any link to good Xcode project template resources would be highly recommended. Especially if there is an official documentation from Apple - I haven't found one yet which seems to imply that project templates are undocumented. Answer:
There is indeed little XCode template info out there. What I have found of interest are the following links (I documented myself on the topic, but haven't yet gone any further): * a Google Code search [reveals a few examples](http://www.google.com/codesearch?as_q=file%3ATemplateChooser.plist&btnG=Search+Code&hl=en&as_package=&as_lang=&as_filename=&as_class=&as_function=&as_license=&as_case=), but not much * in particular, I found interesting to look at the code provided by [Three20](http://three20.info/); they have some basic examples, like [here](https://github.com/jeanregisser/three20/blob/master/templates/source/Three20%20Class/Three20%20class/TemplateChooser.plist) * referencing another project worked for me, so maybe you could open a specific question about that giving more details? * there is information scattered on the [Apple mailing-lists](http://www.google.com/#sclient=psy&hl=en&q=TemplateChooser.plist+site%3Aapple.com&aq=f&aqi=&aql=&oq=&gs_rfai=&pbx=1&fp=ca05a7bb65e82229) * there is no official documentation from Apple, as is evidenced by the lack of results to [this query](http://www.google.com/#q=TemplateChooser.plist+site%3Adeveloper.apple.com) I'm sorry if this is not a Enlighting, concise answer. As you said, it's not well documented, and sources are all over the place. I just hope I could highlight some places to find information that your own searches might not have reached :)
And yet another video link <http://howtomakeiphoneapps.com/2010/10/how-to-make-custom-xcode-templates-with-video/>
Question: I'm interested in find out what were some of the first uses of mathematical induction in the literature. I am aware that in order to define addition and multiplication axiomatically, mathematical induction in required. However, I am certain that the ancients did their arithmetic happily without a tad of concern about induction. When did induction get mentioned explicitly in the mathematical literature? Definitely this places before about 1800 when the early logicians started formulating axioms for arithmetic. Answer:
There are several questions here, so my answer overlaps with some of the others. 1. First use of induction in some form. I would nominate the "infinite descent" proof that $\sqrt{2}$ is irrational -- suppose that $\sqrt{2}=m/n$, then show that $\sqrt{2}=m'/n'$ for smaller numbers $m',n'$ -- which probably goes back to around 500 BC. 2. First published use of induction in some form. Euclid's infinite descent proof that every natural number has a prime divisor, in the *Elements*. 3. First use of induction in the "base step, induction step" form. I suggest Levi ben Gershon and (more definitely) Pascal, as mentioned in danseetea's answer. 4. First *mention* of "induction". The one suggested by Gerald Edgar is the earliest I know of. 5. First realization that induction is fundamental to arithmetic: Grassmann's *Lehrbuch der Arithmetik* of 1861, where he defines addition and multiplication by induction, and proves their ring properties by induction. This idea was rediscovered, and built into an axiom system by Dedekind, in his *Was sind und was sollen die Zahlen?* of 1888. It became better known as the Peano axiom system, when Peano redeveloped it a couple of years later.
Induction <http://jeff560.tripod.com/i.html> Mathematical Induction <http://jeff560.tripod.com/m.html>
Question: I'm interested in find out what were some of the first uses of mathematical induction in the literature. I am aware that in order to define addition and multiplication axiomatically, mathematical induction in required. However, I am certain that the ancients did their arithmetic happily without a tad of concern about induction. When did induction get mentioned explicitly in the mathematical literature? Definitely this places before about 1800 when the early logicians started formulating axioms for arithmetic. Answer:
There are several questions here, so my answer overlaps with some of the others. 1. First use of induction in some form. I would nominate the "infinite descent" proof that $\sqrt{2}$ is irrational -- suppose that $\sqrt{2}=m/n$, then show that $\sqrt{2}=m'/n'$ for smaller numbers $m',n'$ -- which probably goes back to around 500 BC. 2. First published use of induction in some form. Euclid's infinite descent proof that every natural number has a prime divisor, in the *Elements*. 3. First use of induction in the "base step, induction step" form. I suggest Levi ben Gershon and (more definitely) Pascal, as mentioned in danseetea's answer. 4. First *mention* of "induction". The one suggested by Gerald Edgar is the earliest I know of. 5. First realization that induction is fundamental to arithmetic: Grassmann's *Lehrbuch der Arithmetik* of 1861, where he defines addition and multiplication by induction, and proves their ring properties by induction. This idea was rediscovered, and built into an axiom system by Dedekind, in his *Was sind und was sollen die Zahlen?* of 1888. It became better known as the Peano axiom system, when Peano redeveloped it a couple of years later.
EDIT: I should have read the other posted answer before writing the answer below. Obviously, my suggestion that the name "induction" was coined by Poincare is wrong. I am curious, then, as to when the name "induction" gained popular currency. Was Poincare simply taking an established term and turning it to his own purposes in the philosophy of mathematics? --- In one of his essays (I forget which one, and don't have the reference at hand) Poincare discusses mathematical induction in the formal way that we think of it, and explains that it is this principle that allows mathematical argument to escape the rigid confines of formal tautologies and take flight on mathematical intuition. In fact, he uses the name induction in deliberate analogy with inductive reasoning in science (to be contrasted with the deductive reasoning that underlies logical manipulations of definitions). I don't know how much of his contribution to the formalization of induction is original, and how much he is building on earlier work. The [wikipedia article](http://en.wikipedia.org/wiki/Mathematical_induction) on induction has a small amount of history and mentions Boole, Peano, and Dedekind (all working in the 19th century) and does not mention Poincare, while the [wikipedia article](http://en.wikipedia.org/wiki/Peano_axioms) mentions Grassmann as well. This suggests that Poincare is indeed building on their earlier formulations. (Aside: I didn't see in either article a statement as to where the precise statement induction originated (in a footnote quoting from Boole in the induction article, the term induction does not seem to be used), so it seems conceivable that the actual name "mathematical induction" comes from Poincare.) The wikipedia article on induction mentions Bernoulli as an earlier employer of the "inductive hypothesis". It also mentions the well-known "infinite descent" arguments of Fermat, which are a variation on induction (in fact, they are a direct appeal to the well-ordering of the natural numbers), and mentions several earlier examples, going back to ancient times. None of these earlier examples are explicitly applying induction in our modern sense, though; rather, they are making arguments or calculation which are implicitly of an inductive nature. Summary: I hope that someone who knows more history and has more sources than wikipedia at hand will give a more definitive answer, but my guess is that, while inductive style arguments date back to the beginning of mathematics, the precise logical formulation of inductive arguments dates back to the 19th century (and represents part of the concern for logical foundations that developed in that century), and that the actual name "induction" may originate with Poincare (in the early 20th century).
Question: I'm interested in find out what were some of the first uses of mathematical induction in the literature. I am aware that in order to define addition and multiplication axiomatically, mathematical induction in required. However, I am certain that the ancients did their arithmetic happily without a tad of concern about induction. When did induction get mentioned explicitly in the mathematical literature? Definitely this places before about 1800 when the early logicians started formulating axioms for arithmetic. Answer:
There are several questions here, so my answer overlaps with some of the others. 1. First use of induction in some form. I would nominate the "infinite descent" proof that $\sqrt{2}$ is irrational -- suppose that $\sqrt{2}=m/n$, then show that $\sqrt{2}=m'/n'$ for smaller numbers $m',n'$ -- which probably goes back to around 500 BC. 2. First published use of induction in some form. Euclid's infinite descent proof that every natural number has a prime divisor, in the *Elements*. 3. First use of induction in the "base step, induction step" form. I suggest Levi ben Gershon and (more definitely) Pascal, as mentioned in danseetea's answer. 4. First *mention* of "induction". The one suggested by Gerald Edgar is the earliest I know of. 5. First realization that induction is fundamental to arithmetic: Grassmann's *Lehrbuch der Arithmetik* of 1861, where he defines addition and multiplication by induction, and proves their ring properties by induction. This idea was rediscovered, and built into an axiom system by Dedekind, in his *Was sind und was sollen die Zahlen?* of 1888. It became better known as the Peano axiom system, when Peano redeveloped it a couple of years later.
This is not an answer to your question because you ask for explicit mentioning. However I think this is still relevant to the discussion: some claim Levi ben Gershon (early 14th century) used induction in some sense. I read this in John Stillwell's "Mathematics and its history", p193: > > "Levi ben Gershon comes very close to using mathematical induction, if not actually inventing it .... Rabinovitch (1970) offered an exposition of some of Levi ben Gershon's proofs that certainly seems to show a division into a base step and induction step, but the induction step needs some notational help to become a proof for truly arbitrary n." > > > Rabinovitch (1970) above is "Rabinovitch, N.L. (1970). Rabbi Levi ben Gershon and the origins of mathematical induction. Arch. Hist. Exact Sci., 6, 237-248"
Question: On my website I use jQuery to hook the events of elements, namely hyperlinks. As these hyperlinks only perform actions on the current page, and do not lead anywhere, I have been putting a href attribute of "#" in: ``` <a href="#">My Link</a> ``` However in some browsers this causes the page to scroll right to top which is obviously undesirable behaviour. I've tried using a blank href value, or not including one, but then the mouse does not change to the hand cursor upon hovering. What should I put in there? Answer:
I know this is old but wow, there's such an easy solution. remove the "href" entirely and just add a class that does the following: ``` .no-href { cursor:pointer: } ``` And that's it!
Instead you can simply have the href like below: ``` <a href="javascript:;">My Link</a> ``` It will not scroll to the top.
Question: On my website I use jQuery to hook the events of elements, namely hyperlinks. As these hyperlinks only perform actions on the current page, and do not lead anywhere, I have been putting a href attribute of "#" in: ``` <a href="#">My Link</a> ``` However in some browsers this causes the page to scroll right to top which is obviously undesirable behaviour. I've tried using a blank href value, or not including one, but then the mouse does not change to the hand cursor upon hovering. What should I put in there? Answer:
You should really put a real link in there. I don't want to sound like a pedant, but that's a fairly bad habit to get into. JQuery and Ajax should always be the last thing you implement. If you have a link that goes no-where, you're not doing it right. I'm not busting your balls, I mean that with all the best intention.
Add return false to the end of your click handler, this prevents the browser default handler occurring which attempts to redirect the page: ``` $('a').click(function() { // do stuff return false; }); ```
Question: On my website I use jQuery to hook the events of elements, namely hyperlinks. As these hyperlinks only perform actions on the current page, and do not lead anywhere, I have been putting a href attribute of "#" in: ``` <a href="#">My Link</a> ``` However in some browsers this causes the page to scroll right to top which is obviously undesirable behaviour. I've tried using a blank href value, or not including one, but then the mouse does not change to the hand cursor upon hovering. What should I put in there? Answer:
You should really put a real link in there. I don't want to sound like a pedant, but that's a fairly bad habit to get into. JQuery and Ajax should always be the last thing you implement. If you have a link that goes no-where, you're not doing it right. I'm not busting your balls, I mean that with all the best intention.
I **almost had this problem** and it was very ***deceiving***. I am providing an answer in case someone winds up in my same position. 1. I *thought* I had this problem 2. But, I was using return false and javascript:void(0); 3. Then a distinct difference in problem kept surfacing: 4. I realized it's not going ALL the way to the top - and my problem zone was near the bottom of the page so this jump was strange and annoying. 5. I realized I was using fadeIn() [jQuery library], which for a short time my content was display:none 6. And then my content extended the reach of the page! Causing what looks like a jump! 7. Using visibility hidden toggles now.. Hope this helps the person stuck with jumps!!
Question: On my website I use jQuery to hook the events of elements, namely hyperlinks. As these hyperlinks only perform actions on the current page, and do not lead anywhere, I have been putting a href attribute of "#" in: ``` <a href="#">My Link</a> ``` However in some browsers this causes the page to scroll right to top which is obviously undesirable behaviour. I've tried using a blank href value, or not including one, but then the mouse does not change to the hand cursor upon hovering. What should I put in there? Answer:
``` $('a').click(function (event) { event.preventDefault(); //here you can also do all sort of things }); ``` Then you can put in every `href` whatever you want and jQuery will trigger the `preventDefault()` method and you will not be redirected to that place.
You should really put a real link in there. I don't want to sound like a pedant, but that's a fairly bad habit to get into. JQuery and Ajax should always be the last thing you implement. If you have a link that goes no-where, you're not doing it right. I'm not busting your balls, I mean that with all the best intention.
Question: On my website I use jQuery to hook the events of elements, namely hyperlinks. As these hyperlinks only perform actions on the current page, and do not lead anywhere, I have been putting a href attribute of "#" in: ``` <a href="#">My Link</a> ``` However in some browsers this causes the page to scroll right to top which is obviously undesirable behaviour. I've tried using a blank href value, or not including one, but then the mouse does not change to the hand cursor upon hovering. What should I put in there? Answer:
``` $('a').click(function (event) { event.preventDefault(); //here you can also do all sort of things }); ``` Then you can put in every `href` whatever you want and jQuery will trigger the `preventDefault()` method and you will not be redirected to that place.
Why use a `<a href>`? I solve it like this: `<span class='a'>fake link</span>` And style it with: `.a {text-decoration:underline; cursor:pointer;}` You can easily access it with jQuery: `$(".a").click();`
Question: On my website I use jQuery to hook the events of elements, namely hyperlinks. As these hyperlinks only perform actions on the current page, and do not lead anywhere, I have been putting a href attribute of "#" in: ``` <a href="#">My Link</a> ``` However in some browsers this causes the page to scroll right to top which is obviously undesirable behaviour. I've tried using a blank href value, or not including one, but then the mouse does not change to the hand cursor upon hovering. What should I put in there? Answer:
Wonder why nobody said it here earlier: to prevent `<a href="#">` from scrolling document position to the top, simply use `<a href="#/">` instead. That's mere HTML, no JQuery needed. Using `event.preventDefault();` is just too much!
Instead you can simply have the href like below: ``` <a href="javascript:;">My Link</a> ``` It will not scroll to the top.
Question: On my website I use jQuery to hook the events of elements, namely hyperlinks. As these hyperlinks only perform actions on the current page, and do not lead anywhere, I have been putting a href attribute of "#" in: ``` <a href="#">My Link</a> ``` However in some browsers this causes the page to scroll right to top which is obviously undesirable behaviour. I've tried using a blank href value, or not including one, but then the mouse does not change to the hand cursor upon hovering. What should I put in there? Answer:
Those "anchors" that exist solely to provide a click event, but do not actually link to other content, should really be *button* elements because that's what they really are. It can be styled like so: ``` <button style="border:none; background:transparent; cursor: pointer;">Click me</button> ``` And of course click events can be attached to buttons without worry of the browser jumping to the top, and without adding extraneous javascript such as onclick="return false;" or event.preventDefault() .
I know this is old but wow, there's such an easy solution. remove the "href" entirely and just add a class that does the following: ``` .no-href { cursor:pointer: } ``` And that's it!
Question: On my website I use jQuery to hook the events of elements, namely hyperlinks. As these hyperlinks only perform actions on the current page, and do not lead anywhere, I have been putting a href attribute of "#" in: ``` <a href="#">My Link</a> ``` However in some browsers this causes the page to scroll right to top which is obviously undesirable behaviour. I've tried using a blank href value, or not including one, but then the mouse does not change to the hand cursor upon hovering. What should I put in there? Answer:
Add return false to the end of your click handler, this prevents the browser default handler occurring which attempts to redirect the page: ``` $('a').click(function() { // do stuff return false; }); ```
Wonder why nobody said it here earlier: to prevent `<a href="#">` from scrolling document position to the top, simply use `<a href="#/">` instead. That's mere HTML, no JQuery needed. Using `event.preventDefault();` is just too much!
Question: On my website I use jQuery to hook the events of elements, namely hyperlinks. As these hyperlinks only perform actions on the current page, and do not lead anywhere, I have been putting a href attribute of "#" in: ``` <a href="#">My Link</a> ``` However in some browsers this causes the page to scroll right to top which is obviously undesirable behaviour. I've tried using a blank href value, or not including one, but then the mouse does not change to the hand cursor upon hovering. What should I put in there? Answer:
Add return false to the end of your click handler, this prevents the browser default handler occurring which attempts to redirect the page: ``` $('a').click(function() { // do stuff return false; }); ```
I know this is old but wow, there's such an easy solution. remove the "href" entirely and just add a class that does the following: ``` .no-href { cursor:pointer: } ``` And that's it!
Question: On my website I use jQuery to hook the events of elements, namely hyperlinks. As these hyperlinks only perform actions on the current page, and do not lead anywhere, I have been putting a href attribute of "#" in: ``` <a href="#">My Link</a> ``` However in some browsers this causes the page to scroll right to top which is obviously undesirable behaviour. I've tried using a blank href value, or not including one, but then the mouse does not change to the hand cursor upon hovering. What should I put in there? Answer:
Why use a `<a href>`? I solve it like this: `<span class='a'>fake link</span>` And style it with: `.a {text-decoration:underline; cursor:pointer;}` You can easily access it with jQuery: `$(".a").click();`
you shoud use `<a href="javascript:void(0)" ></a>` instead of `<a href="#" ></a>`
Question: I want to write a testcase but that function is in loop ``` def myfunction(): for file in files: myfun(file, Temp=True) ``` Answer:
Visual Studio provides a way of running a script before and also after a test run. They are intended for use in deploying data for a test and cleaning up after a test. The scripts are specified on the ["Setup and cleanup"](https://msdn.microsoft.com/en-us/library/ee256991.aspx#VSTestSettingsSetupandCleanupScripts) page in the ".testsettings" file. A load test plugin can contain code to run before and after any test cases are executed, also at various stages during test execution. The interface is that events are raised at various points during the execution of a load test. User code can be called when these events occur. The `LoadTestStarting` event is raised before any test cases run. See [here](https://msdn.microsoft.com/en-us/library/ms243153(v=vs.120).aspx) for more info.
If you are willing to use NUnit you have SetUp/TearDown for a per test scope and TestFixtureSetUp/TestFixtureTearDown to do something similar for a class (TestFixture)
Question: I want to write a testcase but that function is in loop ``` def myfunction(): for file in files: myfun(file, Temp=True) ``` Answer:
Visual Studio provides a way of running a script before and also after a test run. They are intended for use in deploying data for a test and cleaning up after a test. The scripts are specified on the ["Setup and cleanup"](https://msdn.microsoft.com/en-us/library/ee256991.aspx#VSTestSettingsSetupandCleanupScripts) page in the ".testsettings" file. A load test plugin can contain code to run before and after any test cases are executed, also at various stages during test execution. The interface is that events are raised at various points during the execution of a load test. User code can be called when these events occur. The `LoadTestStarting` event is raised before any test cases run. See [here](https://msdn.microsoft.com/en-us/library/ms243153(v=vs.120).aspx) for more info.
Maybe a bit of a hack, but you can place your code inside the static constructor of your test class as it will automatically run exactly once before the first instance is created or any static members are referenced: ``` [TestClass] public class Setup : WebTest { static Setup() { // prepare data for test } public override IEnumerator<WebTestRequest> GetRequestEnumerator() { return null; } } ```
Question: I have two collections known to be of the same size: ``` List<Drivers> drivers; List<Car> cars; ``` I need to put driver from the `i` place to `i` car: ``` for (int i = 0; i < drivers.Count; i++) cars[i].AssignDriver(drivers[i]); ``` May I do that without loop? Answer:
Well, on the lowest level - no. You'll need to iterate anyway. But there are some nice libraries that make handling such situations easier. For instance, there are [Interactive Extensions for .NET](http://nuget.org/List/Packages/Ix_Experimental-Main). Although, they are not in production state, they make it possible to do it this way: ``` cars.Zip(drivers, (car, driver) => new { car, driver }) .ForEach(x => x.car.AssignDriver(x.driver)); ```
LINQ is your friend. Take a look at this: <http://msdn.microsoft.com/en-us/library/bb548891.aspx> Note however, that I would consider your existing approach a good one too.
Question: I have two collections known to be of the same size: ``` List<Drivers> drivers; List<Car> cars; ``` I need to put driver from the `i` place to `i` car: ``` for (int i = 0; i < drivers.Count; i++) cars[i].AssignDriver(drivers[i]); ``` May I do that without loop? Answer:
LINQ only for querying object, so you've to live with loop. An other way is to use [List.ForEach](http://msdn.microsoft.com/en-us/library/bwabdf9z%28v=VS.100%29.aspx) method but I would suggest not using it since it confusing sometimes, anyway below is example in educational purposes: ``` drivers.Select((d,i) => new { Index = i, Driver = d }) .ToList() .ForEach(entry => car[entry.Index].AssignDriver(entry.Driver)); ``` Useful links: * [“foreach” vs “ForEach”](http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx)
LINQ is your friend. Take a look at this: <http://msdn.microsoft.com/en-us/library/bb548891.aspx> Note however, that I would consider your existing approach a good one too.
Question: I have two collections known to be of the same size: ``` List<Drivers> drivers; List<Car> cars; ``` I need to put driver from the `i` place to `i` car: ``` for (int i = 0; i < drivers.Count; i++) cars[i].AssignDriver(drivers[i]); ``` May I do that without loop? Answer:
LINQ only for querying object, so you've to live with loop. An other way is to use [List.ForEach](http://msdn.microsoft.com/en-us/library/bwabdf9z%28v=VS.100%29.aspx) method but I would suggest not using it since it confusing sometimes, anyway below is example in educational purposes: ``` drivers.Select((d,i) => new { Index = i, Driver = d }) .ToList() .ForEach(entry => car[entry.Index].AssignDriver(entry.Driver)); ``` Useful links: * [“foreach” vs “ForEach”](http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx)
Well, on the lowest level - no. You'll need to iterate anyway. But there are some nice libraries that make handling such situations easier. For instance, there are [Interactive Extensions for .NET](http://nuget.org/List/Packages/Ix_Experimental-Main). Although, they are not in production state, they make it possible to do it this way: ``` cars.Zip(drivers, (car, driver) => new { car, driver }) .ForEach(x => x.car.AssignDriver(x.driver)); ```
Question: I have a javascript function that uses window.location. It works fine in Firefox and internet Explorer, but not in Chrome. I've tested this on both Ubunutu Hardy and Windows Vista. What is the underlying problem, and how can I circumvent it? Answer:
Try without `window.`. For example, use `location.assign()` instead of `window.location.assign()`.
Just created the following html file and it alerted the window.location for me in Google Chrome 4.0 - are you using an old version? ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Untitled Page</title> </head> <body> </body> </html> <script language="javascript" type="text/javascript"> alert(window.location); </script> ```
Question: I have a javascript function that uses window.location. It works fine in Firefox and internet Explorer, but not in Chrome. I've tested this on both Ubunutu Hardy and Windows Vista. What is the underlying problem, and how can I circumvent it? Answer:
Try appending "return false;" to your javascript call like so... ``` window.location.href='google.com; return false; ```
Just created the following html file and it alerted the window.location for me in Google Chrome 4.0 - are you using an old version? ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Untitled Page</title> </head> <body> </body> </html> <script language="javascript" type="text/javascript"> alert(window.location); </script> ```
Question: I have a javascript function that uses window.location. It works fine in Firefox and internet Explorer, but not in Chrome. I've tested this on both Ubunutu Hardy and Windows Vista. What is the underlying problem, and how can I circumvent it? Answer:
The most common use of `window.location` is to make the browser load a new page. A common error is to assign the URL to the `window.location` object instead of it's property `href`. So, the correct way to do it is: ``` window.location.href = 'http://www.guffa.com'; ```
I was having this problem, and it ended up being that my javascript function was returning true after the window.location tag (due to nested functions). FF and IE never processed that far, while chrome did.
Question: I have a javascript function that uses window.location. It works fine in Firefox and internet Explorer, but not in Chrome. I've tested this on both Ubunutu Hardy and Windows Vista. What is the underlying problem, and how can I circumvent it? Answer:
Resolved the issue. There wasn't a problem with the function or with Chrome. The function should be called by a drupal form element. I was adding the onclick event which called the function to the drupal form itself, instead of a particular form element. Pretty much doing this: ``` $form['testform'] = array( '#type' => 'fieldset', '#collapsible' => TRUE, '#collapsed' => FALSE, '#attributes' => array( 'onchange' => 'testfunc()'), ); ``` Instead of this: ``` $form['testform']['element1'] = array( '#type' => 'select', '#options' => options, '#required' => false, '#attributes' => array( 'onchange' => 'testfunc()'), ); ``` Don't I feel silly.
Just created the following html file and it alerted the window.location for me in Google Chrome 4.0 - are you using an old version? ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Untitled Page</title> </head> <body> </body> </html> <script language="javascript" type="text/javascript"> alert(window.location); </script> ```
Question: I have a javascript function that uses window.location. It works fine in Firefox and internet Explorer, but not in Chrome. I've tested this on both Ubunutu Hardy and Windows Vista. What is the underlying problem, and how can I circumvent it? Answer:
I was having this problem, and it ended up being that my javascript function was returning true after the window.location tag (due to nested functions). FF and IE never processed that far, while chrome did.
Just created the following html file and it alerted the window.location for me in Google Chrome 4.0 - are you using an old version? ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Untitled Page</title> </head> <body> </body> </html> <script language="javascript" type="text/javascript"> alert(window.location); </script> ```
Question: I have a javascript function that uses window.location. It works fine in Firefox and internet Explorer, but not in Chrome. I've tested this on both Ubunutu Hardy and Windows Vista. What is the underlying problem, and how can I circumvent it? Answer:
The most common use of `window.location` is to make the browser load a new page. A common error is to assign the URL to the `window.location` object instead of it's property `href`. So, the correct way to do it is: ``` window.location.href = 'http://www.guffa.com'; ```
Just created the following html file and it alerted the window.location for me in Google Chrome 4.0 - are you using an old version? ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Untitled Page</title> </head> <body> </body> </html> <script language="javascript" type="text/javascript"> alert(window.location); </script> ```
Question: I have a javascript function that uses window.location. It works fine in Firefox and internet Explorer, but not in Chrome. I've tested this on both Ubunutu Hardy and Windows Vista. What is the underlying problem, and how can I circumvent it? Answer:
The most common use of `window.location` is to make the browser load a new page. A common error is to assign the URL to the `window.location` object instead of it's property `href`. So, the correct way to do it is: ``` window.location.href = 'http://www.guffa.com'; ```
Try without `window.`. For example, use `location.assign()` instead of `window.location.assign()`.
Question: I have a javascript function that uses window.location. It works fine in Firefox and internet Explorer, but not in Chrome. I've tested this on both Ubunutu Hardy and Windows Vista. What is the underlying problem, and how can I circumvent it? Answer:
Just created the following html file and it alerted the window.location for me in Google Chrome 4.0 - are you using an old version? ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Untitled Page</title> </head> <body> </body> </html> <script language="javascript" type="text/javascript"> alert(window.location); </script> ```
I had the same problem, and I wasn't careful enough to make sure that the new redirected url contained white spaces (shame on me). So only Chrome stops this new location if the url is not standardized. Make sure you have an UpdatePanel if you are using a Master Page .
Question: I have a javascript function that uses window.location. It works fine in Firefox and internet Explorer, but not in Chrome. I've tested this on both Ubunutu Hardy and Windows Vista. What is the underlying problem, and how can I circumvent it? Answer:
Try appending "return false;" to your javascript call like so... ``` window.location.href='google.com; return false; ```
I had the same problem, and I wasn't careful enough to make sure that the new redirected url contained white spaces (shame on me). So only Chrome stops this new location if the url is not standardized. Make sure you have an UpdatePanel if you are using a Master Page .
Question: I have a javascript function that uses window.location. It works fine in Firefox and internet Explorer, but not in Chrome. I've tested this on both Ubunutu Hardy and Windows Vista. What is the underlying problem, and how can I circumvent it? Answer:
Resolved the issue. There wasn't a problem with the function or with Chrome. The function should be called by a drupal form element. I was adding the onclick event which called the function to the drupal form itself, instead of a particular form element. Pretty much doing this: ``` $form['testform'] = array( '#type' => 'fieldset', '#collapsible' => TRUE, '#collapsed' => FALSE, '#attributes' => array( 'onchange' => 'testfunc()'), ); ``` Instead of this: ``` $form['testform']['element1'] = array( '#type' => 'select', '#options' => options, '#required' => false, '#attributes' => array( 'onchange' => 'testfunc()'), ); ``` Don't I feel silly.
I had the same problem, and I wasn't careful enough to make sure that the new redirected url contained white spaces (shame on me). So only Chrome stops this new location if the url is not standardized. Make sure you have an UpdatePanel if you are using a Master Page .
Question: I have a condition like below which is saved in database. Each condition has an outcome. I display the available outcomes in a combobox. When the user selects an outcome, I have to display the decision tree for this outcome. Example: ``` COND1 AND (COND2 OR COND3 AND COND4 OR (COND5 AND COND6)) ``` A condition shall be like AGE > 10, DOB IS NOT NULL, X IN TABLE(Y) etc. I need to first extract all the conditions separately and then using the AND, OR & Braces, I have to display them like a decision tree in C#. I have planned to use Accord.Net. Is there a simpler one available, becoz Accord.Net has more features which I don't need. Thanks in advance for the help. Answer:
If you don't want the exact CoffeeScript semantics, you can cheat a bit: ``` return item.getFoo ? (item.getFoo().fooParam || {}).bar : undefined; ``` There are a few tricks going on here. 1. The ternary operator is used to test the truthiness of `item.getFoo` 2. If `fooParam` is missing, falsey, or absent, we substitute it with an empty object. CoffeeScript would have bailed out here. 3. We return the value of `bar` regardless of whether it exists. If it does exist, you get the value you want. If it doesn't exist but `fooParam` is set, you get `undefined`. If it doesn't exist because `fooParam` was undefined and we fell back to `{}`, you still get `undefined`. You can write some helpers if the ternary operator gets in the way: ``` function defaultObject(input) { // A helper to put somewhere return input || {}; } return defaultObject((item.getFoo || defaultObject)().fooParam).bar; ``` This is even trickier: `defaultObject` will return `{}` when called with `getFoo`, so you don't need a ternary operator around the function call. If `fooParam` isn't truthy, `defaultObject` will return another empty object, eliminating the need for another `||`. If `fooParam` is truthy, `defaultObject` behaves like the identity function and returns it. I'm sure this could be golfed further down, but I'd recommend avoiding this pattern. Anyone reading your code will be fairly confused and blame you for making a mess in the codebase.
I had this same question recently, and I came here hoping for a better solution than my current one. If you're doing this frequently, it's easier to make a function to do it for you: ``` var qm = function(arg) { if (arg instanceof Object) return arg; return function(){}; }; ``` Then to use it, you wrap your objects in it to make sure no error is raised. It starts to look ugly if there are many **q**uestion **m**arks on a line ``` qm(qm(item.getFoo)().fooParam).bar ```
Question: I have a condition like below which is saved in database. Each condition has an outcome. I display the available outcomes in a combobox. When the user selects an outcome, I have to display the decision tree for this outcome. Example: ``` COND1 AND (COND2 OR COND3 AND COND4 OR (COND5 AND COND6)) ``` A condition shall be like AGE > 10, DOB IS NOT NULL, X IN TABLE(Y) etc. I need to first extract all the conditions separately and then using the AND, OR & Braces, I have to display them like a decision tree in C#. I have planned to use Accord.Net. Is there a simpler one available, becoz Accord.Net has more features which I don't need. Thanks in advance for the help. Answer:
If you don't want the exact CoffeeScript semantics, you can cheat a bit: ``` return item.getFoo ? (item.getFoo().fooParam || {}).bar : undefined; ``` There are a few tricks going on here. 1. The ternary operator is used to test the truthiness of `item.getFoo` 2. If `fooParam` is missing, falsey, or absent, we substitute it with an empty object. CoffeeScript would have bailed out here. 3. We return the value of `bar` regardless of whether it exists. If it does exist, you get the value you want. If it doesn't exist but `fooParam` is set, you get `undefined`. If it doesn't exist because `fooParam` was undefined and we fell back to `{}`, you still get `undefined`. You can write some helpers if the ternary operator gets in the way: ``` function defaultObject(input) { // A helper to put somewhere return input || {}; } return defaultObject((item.getFoo || defaultObject)().fooParam).bar; ``` This is even trickier: `defaultObject` will return `{}` when called with `getFoo`, so you don't need a ternary operator around the function call. If `fooParam` isn't truthy, `defaultObject` will return another empty object, eliminating the need for another `||`. If `fooParam` is truthy, `defaultObject` behaves like the identity function and returns it. I'm sure this could be golfed further down, but I'd recommend avoiding this pattern. Anyone reading your code will be fairly confused and blame you for making a mess in the codebase.
The [optional chaining operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) `?.` was introduced in ES2020. ``` obj.val?.prop obj.val?.[expr] obj.arr?.[index] obj.func?.(args) ``` It is supported by the browsers of 91.81% of internet users as of 29 November 2021 according to <https://caniuse.com/mdn-javascript_operators_optional_chaining>.
Question: I have a condition like below which is saved in database. Each condition has an outcome. I display the available outcomes in a combobox. When the user selects an outcome, I have to display the decision tree for this outcome. Example: ``` COND1 AND (COND2 OR COND3 AND COND4 OR (COND5 AND COND6)) ``` A condition shall be like AGE > 10, DOB IS NOT NULL, X IN TABLE(Y) etc. I need to first extract all the conditions separately and then using the AND, OR & Braces, I have to display them like a decision tree in C#. I have planned to use Accord.Net. Is there a simpler one available, becoz Accord.Net has more features which I don't need. Thanks in advance for the help. Answer:
I had this same question recently, and I came here hoping for a better solution than my current one. If you're doing this frequently, it's easier to make a function to do it for you: ``` var qm = function(arg) { if (arg instanceof Object) return arg; return function(){}; }; ``` Then to use it, you wrap your objects in it to make sure no error is raised. It starts to look ugly if there are many **q**uestion **m**arks on a line ``` qm(qm(item.getFoo)().fooParam).bar ```
The [optional chaining operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) `?.` was introduced in ES2020. ``` obj.val?.prop obj.val?.[expr] obj.arr?.[index] obj.func?.(args) ``` It is supported by the browsers of 91.81% of internet users as of 29 November 2021 according to <https://caniuse.com/mdn-javascript_operators_optional_chaining>.
Question: ![problem](https://i.stack.imgur.com/BprK7.jpg) I tried graphing the equations that form the two isosceles triangles and integrating the bounded area and got 7.456 as my answer after rounding. The answer key has the answer listed as 7.2 However, these type of problems rarely involve calc and I'm sure there is a much simpler way of solving this problem geometrically. Answer:
See the picture below. The thick black square is $6 \times 6$ and the two blue triangles are the ones described by the problem. ![enter image description here](https://i.stack.imgur.com/vtGgo.gif) As we can see, the geometry induces a secondary square lattice. The width $x$ of one such square, highlighted in green, is easily determined as satisfying the relationship $x^2 + (x/3)^2 = 2^2$, or $x = 3 \sqrt{2/5}.$ Therefore, the area of the dark blue shaded region common to both blue triangles is simply $2x^2 = 36/5$. (An alternative computation is to observe that the large black square has area $36$, which is equivalent to ten times the area of a single green square; thus a single green square has area $18/5$, and two such squares, which is equivalent in area to the dark blue shaded region, is $36/5$.)
I was good at contest math in my youth, but sucked at the geometry problems. I always ended up using Cartesian coordinates and reducing it to an algebra problem. Here, setting $A=(0,2)$, $B=(0,-2)$, $C=(6,0)$ and thus $P=(0,0)$, and try to work from there. $AD$ perpendicular and equal in length to $AB$ would mean that $D=(\pm 4,2)$, for example. The condition that $BD$ intersects $AC$ means $D=(4,2)$.
Question: ![problem](https://i.stack.imgur.com/BprK7.jpg) I tried graphing the equations that form the two isosceles triangles and integrating the bounded area and got 7.456 as my answer after rounding. The answer key has the answer listed as 7.2 However, these type of problems rarely involve calc and I'm sure there is a much simpler way of solving this problem geometrically. Answer:
![Special case](https://i.stack.imgur.com/fFZTn.png) It's clear that the altitude of $\triangle ABK$ is 3. Also, $\triangle ABJ\sim\triangle ICJ$, and so the altitudes are in the ratio 1:4, since $\overline{GI}=12$ (by another pair of similar triangles). Hence the altitude of $\triangle ABJ$ is 6/5. So the area of the overlap is $4\times(3-6/5)=36/5$. In fact, we can do this for arbitrary isosceles triangles, with base $2a$ and altitude $b$. ![General case](https://i.stack.imgur.com/6tVXO.png) The altitude of $\triangle ABG$ is $b\frac{\overline{AB}}{\overline{AB}+\overline{CH}}=\frac{2ab}{a+b}$ by the similar triangles $\triangle ABG\sim\triangle HCG$ By the similar triangles $\triangle APE\sim\triangle LHE$, we have $\overline{HL}=\frac{b}{a}(b-a)$. So, like in the previous case, the altitude of $\triangle ABF$ works out nicely to be $\frac{2a^2b}{a^2+b^2}$. So the answer is $2\times\text{Area}(\triangle AFG)=2\times\text{Area}(\triangle ABG)-2\times\text{Area}(\triangle ABF)=2a\left(\frac{2ab}{a+b}-\frac{2a^2b}{a^2+b^2}\right)$. You can check that $a=2,b=6$ gives the answer $36/5$.
I was good at contest math in my youth, but sucked at the geometry problems. I always ended up using Cartesian coordinates and reducing it to an algebra problem. Here, setting $A=(0,2)$, $B=(0,-2)$, $C=(6,0)$ and thus $P=(0,0)$, and try to work from there. $AD$ perpendicular and equal in length to $AB$ would mean that $D=(\pm 4,2)$, for example. The condition that $BD$ intersects $AC$ means $D=(4,2)$.
Question: ![problem](https://i.stack.imgur.com/BprK7.jpg) I tried graphing the equations that form the two isosceles triangles and integrating the bounded area and got 7.456 as my answer after rounding. The answer key has the answer listed as 7.2 However, these type of problems rarely involve calc and I'm sure there is a much simpler way of solving this problem geometrically. Answer:
See the picture below. The thick black square is $6 \times 6$ and the two blue triangles are the ones described by the problem. ![enter image description here](https://i.stack.imgur.com/vtGgo.gif) As we can see, the geometry induces a secondary square lattice. The width $x$ of one such square, highlighted in green, is easily determined as satisfying the relationship $x^2 + (x/3)^2 = 2^2$, or $x = 3 \sqrt{2/5}.$ Therefore, the area of the dark blue shaded region common to both blue triangles is simply $2x^2 = 36/5$. (An alternative computation is to observe that the large black square has area $36$, which is equivalent to ten times the area of a single green square; thus a single green square has area $18/5$, and two such squares, which is equivalent in area to the dark blue shaded region, is $36/5$.)
![Special case](https://i.stack.imgur.com/fFZTn.png) It's clear that the altitude of $\triangle ABK$ is 3. Also, $\triangle ABJ\sim\triangle ICJ$, and so the altitudes are in the ratio 1:4, since $\overline{GI}=12$ (by another pair of similar triangles). Hence the altitude of $\triangle ABJ$ is 6/5. So the area of the overlap is $4\times(3-6/5)=36/5$. In fact, we can do this for arbitrary isosceles triangles, with base $2a$ and altitude $b$. ![General case](https://i.stack.imgur.com/6tVXO.png) The altitude of $\triangle ABG$ is $b\frac{\overline{AB}}{\overline{AB}+\overline{CH}}=\frac{2ab}{a+b}$ by the similar triangles $\triangle ABG\sim\triangle HCG$ By the similar triangles $\triangle APE\sim\triangle LHE$, we have $\overline{HL}=\frac{b}{a}(b-a)$. So, like in the previous case, the altitude of $\triangle ABF$ works out nicely to be $\frac{2a^2b}{a^2+b^2}$. So the answer is $2\times\text{Area}(\triangle AFG)=2\times\text{Area}(\triangle ABG)-2\times\text{Area}(\triangle ABF)=2a\left(\frac{2ab}{a+b}-\frac{2a^2b}{a^2+b^2}\right)$. You can check that $a=2,b=6$ gives the answer $36/5$.
Question: I have spent the weekend considering flying to northern Sweden tomorrow to see the aurora borealis. I live in the US. I have never to Europe or anywhere else outside of mainland North America. The things I've thought of to take into account: * a lot of very warm clothing given the climate I would be heading for. * I'll have to exchange my money somehow, somewhere. * Not sure if my US Visa debit card works in Sweden, but by all accounts it should. I plan on checking with my bank in the morning. * My Verizon phone won't work. I'll need to get a disposable phone there. * Need to find hostels or couch surf. This is everything that's come to mind so far. I'm wondering what other things I might need to know or keep in mind when attempting a visit to a foreign country with no planning like this. If anyone has any Sweden-specific advice, that would be nice, too. *Note: I know it's always better to plan way ahead, but that's exactly the point of this question....under current circumstances it's not possible and if I don't go now I won't be able to again for quite some time. I'm asking precisely for advice about an **unplanned** trip.* Answer:
You don't have to bring a *lot* of warm clothing, but you have to pack sensibly. For example, a wick-dry inner, light natural fibre sweater, a down layer, and a windproof outer will do nicely. Hat, gloves, warm socks, and windproof pants (with long thermal underwear) would also be needed for that weather. A scarf is helpful to keep your neck warm and to cover your nose and mouth if needed, especially if it's windy. Your usual ATM card should work fine in Sweden, there's probably no need to carry much US cash with you. Check with your bank first (tell them you are travelling!), and make sure you have a 4-digit PIN (at one point I had a 6-digit PIN and it was incompatible with a lot of systems around the world). It's a good idea to book at least your *first* night in your initial destination. You can work things out from there (eg. Stockholm should be no problem). If you're going to northern Sweden, there will be far fewer services available due to the lack of population, and you'll *definitely* want to book ahead. Couchsurfing in a remote area is not terribly reliable. These days it's super useful to bring a mobile device with WiFi networking (even if it's a phone and the phone part won't work), as you can find WiFi available in lots of places in the city. And if you have WiFi, you can use Skype (with credit) to call normal phones in Sweden. Travel insurance (eg. in case you get hurt) is strongly recommended. Presumably your passport has at least three months remaining validity (if you're a US citizen you won't need to pre-apply for a visa, but for other passports you might). The absolute minimum you need is your passport and your wallet.
Regarding ATM cards, you should have one with chip, since most ATMs here only accepts those cards.
Question: I have spent the weekend considering flying to northern Sweden tomorrow to see the aurora borealis. I live in the US. I have never to Europe or anywhere else outside of mainland North America. The things I've thought of to take into account: * a lot of very warm clothing given the climate I would be heading for. * I'll have to exchange my money somehow, somewhere. * Not sure if my US Visa debit card works in Sweden, but by all accounts it should. I plan on checking with my bank in the morning. * My Verizon phone won't work. I'll need to get a disposable phone there. * Need to find hostels or couch surf. This is everything that's come to mind so far. I'm wondering what other things I might need to know or keep in mind when attempting a visit to a foreign country with no planning like this. If anyone has any Sweden-specific advice, that would be nice, too. *Note: I know it's always better to plan way ahead, but that's exactly the point of this question....under current circumstances it's not possible and if I don't go now I won't be able to again for quite some time. I'm asking precisely for advice about an **unplanned** trip.* Answer:
You don't have to bring a *lot* of warm clothing, but you have to pack sensibly. For example, a wick-dry inner, light natural fibre sweater, a down layer, and a windproof outer will do nicely. Hat, gloves, warm socks, and windproof pants (with long thermal underwear) would also be needed for that weather. A scarf is helpful to keep your neck warm and to cover your nose and mouth if needed, especially if it's windy. Your usual ATM card should work fine in Sweden, there's probably no need to carry much US cash with you. Check with your bank first (tell them you are travelling!), and make sure you have a 4-digit PIN (at one point I had a 6-digit PIN and it was incompatible with a lot of systems around the world). It's a good idea to book at least your *first* night in your initial destination. You can work things out from there (eg. Stockholm should be no problem). If you're going to northern Sweden, there will be far fewer services available due to the lack of population, and you'll *definitely* want to book ahead. Couchsurfing in a remote area is not terribly reliable. These days it's super useful to bring a mobile device with WiFi networking (even if it's a phone and the phone part won't work), as you can find WiFi available in lots of places in the city. And if you have WiFi, you can use Skype (with credit) to call normal phones in Sweden. Travel insurance (eg. in case you get hurt) is strongly recommended. Presumably your passport has at least three months remaining validity (if you're a US citizen you won't need to pre-apply for a visa, but for other passports you might). The absolute minimum you need is your passport and your wallet.
Adding options about how to travel in Sweden. (I guess you already went....) To see the aurora Abisko is probably the best place to be.There are two main ways of getting up there. * You can go there by night train from Stockholm (which will likely be your entry point when flying from the US). The train passes Arlanda (the main airport) on its way north so no need to get into Stockholm. According to the current timetable it leaves at 18:22 from Arlanda and arrives 12:32 the next day in Abisko. This is the slow and (nice?) option. ![enter image description here](https://i.stack.imgur.com/WivKF.jpg) [Photo](http://www.flickr.com/photos/beefortytwo/12220091234/) by flickr user [beefortytwo](http://www.flickr.com/photos/beefortytwo/). * The fastest is (of course) flying to Kiruna with SAS. It is a ~90 minute flight and then you will need to endure another 90 minutes on a bus to get to Abisko. Or just stay in Kiruna. Aurora should be possible to see there also. A good site for planning your domestic travels in Sweden is [resrobot](http://reseplanerare.resrobot.se/bin/query.exe). More detailed information also available in [this question about travelling from Berlin to Abisko](https://travel.stackexchange.com/questions/19588/how-to-get-to-abisko-sweden-from-berlin).
Question: I have spent the weekend considering flying to northern Sweden tomorrow to see the aurora borealis. I live in the US. I have never to Europe or anywhere else outside of mainland North America. The things I've thought of to take into account: * a lot of very warm clothing given the climate I would be heading for. * I'll have to exchange my money somehow, somewhere. * Not sure if my US Visa debit card works in Sweden, but by all accounts it should. I plan on checking with my bank in the morning. * My Verizon phone won't work. I'll need to get a disposable phone there. * Need to find hostels or couch surf. This is everything that's come to mind so far. I'm wondering what other things I might need to know or keep in mind when attempting a visit to a foreign country with no planning like this. If anyone has any Sweden-specific advice, that would be nice, too. *Note: I know it's always better to plan way ahead, but that's exactly the point of this question....under current circumstances it's not possible and if I don't go now I won't be able to again for quite some time. I'm asking precisely for advice about an **unplanned** trip.* Answer:
Adding options about how to travel in Sweden. (I guess you already went....) To see the aurora Abisko is probably the best place to be.There are two main ways of getting up there. * You can go there by night train from Stockholm (which will likely be your entry point when flying from the US). The train passes Arlanda (the main airport) on its way north so no need to get into Stockholm. According to the current timetable it leaves at 18:22 from Arlanda and arrives 12:32 the next day in Abisko. This is the slow and (nice?) option. ![enter image description here](https://i.stack.imgur.com/WivKF.jpg) [Photo](http://www.flickr.com/photos/beefortytwo/12220091234/) by flickr user [beefortytwo](http://www.flickr.com/photos/beefortytwo/). * The fastest is (of course) flying to Kiruna with SAS. It is a ~90 minute flight and then you will need to endure another 90 minutes on a bus to get to Abisko. Or just stay in Kiruna. Aurora should be possible to see there also. A good site for planning your domestic travels in Sweden is [resrobot](http://reseplanerare.resrobot.se/bin/query.exe). More detailed information also available in [this question about travelling from Berlin to Abisko](https://travel.stackexchange.com/questions/19588/how-to-get-to-abisko-sweden-from-berlin).
Regarding ATM cards, you should have one with chip, since most ATMs here only accepts those cards.
Question: Is there a handy Format() function that works only on Ansi strings? Because everytime I use an AnsiString with Format() I get a warning. And no, I don't want Delphi to convert my AnsiStrings back and forth between Wide and Ansi strings. That is just making things awfully slower. Also, is there a way to force a string constant to be Ansi? check this out ``` function SomeStrFunc(S: AnsiString): AnsiString; overload; function SomeStrFunc(S: String): String; overload; ``` and then when I use SomeStrFunc('ABC') it will call the wide string version. What if I want to use the Ansi version and force Delphi to store 'ABC' constant in AnsiChars. Answer:
There is Ansi version of `Format` function in `System.AnsiStrings` unit
Serg answered your question about an `AnsiString` version of `Format()`. I'll answer your other question. String literals are encoded based on the context they are used, so to force a literal to a particular encoding, you have to tell the compiler which encoding it needs to use, eg: ``` SomeStrFunc(AnsiString('ABC')); ``` Or ``` const cABC: AnsiString = 'ABC'; SomeStrFunc(cABC); ```
Question: I am looking to get netstat for BroadCast, Multicast and Unicast sent and received packets. This can be obtained from "/proc/net/netstat". But the problem here is, it does not give statistics data for different interfaces(like "eth0", "eth2" etc..). It only gives total data for all the interfaces. How to get this data for each interfaces? Answer:
You can get a subset(including multicast) of the information per device from: ``` /proc/net/dev ```
You can get rx and tx broadcast and multicast for each interface from `#ethtool -S ethX` . The same multicast data is there in `/proc/net/dev` file.
Question: I have a server with lots of folders inside `C:\data`. I talk about around 5000 subfolders, whereby each folder has a random name such as `sgshVSHsXx.wjwuhHHS`. Each of those folders contains a subfolder with name `DB` and each of those `DB` folders contains some database files, also with random file names and random file extensions. I need to go through all those `DB` folders and delete every file that is older than 10 days. I presume I could use some VBS for that, but have not much experience with it. Could someone throw some light on this issue? Thanks Answer:
Of course batch or command prompt is suited to this ``` forfiles /p "c:\data" /m * /s /d -10 /c "cmd /c del @path" ``` and is one line.
Save the following as a .vbs file ``` set args = wscript.arguments if args.count <> 2 then wscript.echo "Syntax: " & wscript.scriptname & " <path> <days>" wscript.quit end if path = args(0) killdate = date() - args(1) arFiles = Array() set fso = createobject("scripting.filesystemobject") SelectFiles path, killdate, arFiles, true nDeleted = 0 for n = 0 to ubound(arFiles) on error resume next 'in case of 'in use' files... arFiles(n).delete true if err.number = 0 then nDeleted = nDeleted + 1 end if on error goto 0 next sub SelectFiles(sPath,vKillDate,arFilesToKill,bIncludeSubFolders) on error resume next set folder = fso.getfolder(sPath) set files = folder.files for each file in files dtlastmodified = null on error resume Next dtlastmodified = file.datelastmodified on error goto 0 if not isnull(dtlastmodified) Then if dtlastmodified < vKillDate then count = ubound(arFilesToKill) + 1 redim preserve arFilesToKill(count) set arFilesToKill(count) = file end if end if next if bIncludeSubFolders then for each fldr in folder.subfolders SelectFiles fldr.path,vKillDate,arFilesToKill,true next end if end sub ``` to run: .vbs "" example: c:\delete.vbs "c:\test folder\" 10 Make sure you run from an admin command prompt # source:<http://community.spiceworks.com/scripts/show/282-delete-old-files-with-recursion>
Question: I'm using silverlight Bing map control and I want to highlight country / continent after hovering it with mouse cursor. Is there a better way of doing this than just providing coordinates for a polygon ? It's a looot of work if I would like to highlight all countries in the world. I think there should be some sort of ready solution, but I wasn't able to find one. Answer:
No, there is no way to highlight a country other than providing your own data - either in the form of coordinates to create a Microsoft.Maps.Polygon, or else overlay your own raster tileset on top of the map with the relevant country highlighted. In fact, there is not even such such a thing as a globally-agreed list of *how many* countries there are in the world, let alone where there borders are. See <http://en.wikipedia.org/wiki/List_of_territorial_disputes> for examples I think if the Bing Maps API (or Google Maps etc.) were to provide a set of coordinates representing the boundaries of each country, they would inevitably be exposing themselves to unnecessary political bias.
I was searching for some solutions yesterday and I think this is the best solution so far: <http://www.bing.com/community/site_blogs/b/maps/archive/2010/07/13/data-connector-sql-server-2008-spatial-amp-bing-maps.aspx> Using SQL Server spatial data : <http://www.microsoft.com/sqlserver/2008/en/us/spatial-data.aspx>
Question: OS version: Ubuntu 12.04 I wrote `veditor` in my terminal and got the following message: > > No command 'veditor' found, but there are 39 similar ones > > > My question is how can I **view** those 39 **similar commands**? Answer:
I've seen this same error sometimes on Ubuntu. A working workaround for this is running adb with `sudo` command. For example, if you're pushing `app.apk` on sdcard the command would be ``` sudo adb push app.apk /mnt/sdcard ``` Also, be sure you selected "USB debugging" mode in the Application settings (in GingerBread) or in Development section ( in IceCream Sandwich and above). If adb is already running, you should first kill it with the command `sudo adb kill-server` Hope this will help.
There are some specific things to do for Ubuntu to make USB debugging work, described in [this page on developer.android.com](https://developer.android.com/studio/run/device) about setting up a device for development. What it suggests is to run these two commands in terminal: ``` sudo usermod -aG plugdev $LOGNAME sudo apt-get install android-sdk-platform-tools-common ``` The above package contains udev rules for Android devices. Rebooting may be needed for the changes to take effect.
Question: OS version: Ubuntu 12.04 I wrote `veditor` in my terminal and got the following message: > > No command 'veditor' found, but there are 39 similar ones > > > My question is how can I **view** those 39 **similar commands**? Answer:
I've seen this same error sometimes on Ubuntu. A working workaround for this is running adb with `sudo` command. For example, if you're pushing `app.apk` on sdcard the command would be ``` sudo adb push app.apk /mnt/sdcard ``` Also, be sure you selected "USB debugging" mode in the Application settings (in GingerBread) or in Development section ( in IceCream Sandwich and above). If adb is already running, you should first kill it with the command `sudo adb kill-server` Hope this will help.
Today I encountered the `insufficient permissions for device` error, even though `adb` had been working as expected just a few minutes before. Now I get: ``` $ adb devices List of devices attached ???????????? no permissions $ adb shell error: insufficient permissions for device ``` Shortly before encountering the error, I had disabled `Media device (MTP)`, as I figured I would not need to use `MTP`. However, it appears that USB debugging, or at least some `adb` commands, require that `Media device (MTP)` be enabled. To enable `Media device (MTP)` on Android 4.4, go to: ``` Settings Storage The "..." menu (in the upper right corner) USB computer connection Media device (MTP) ``` When `MTP` is disabled, `lsusb` shows the following: ``` Bus 002 Device 071: ID [idVendor1]:[idProduct1] Google Inc. ``` After enabling `MTP`, lsusb shows the following: ``` Bus 002 Device 072: ID [idVendor2]:[idProduct2] [idVendor string] ``` The idVendor and idProduct do change, based on whether or not `MTP` is enabled or disabled. I am not an Android expert, so it is possible that the above behavior is specific to my particular model of phone.
Question: OS version: Ubuntu 12.04 I wrote `veditor` in my terminal and got the following message: > > No command 'veditor' found, but there are 39 similar ones > > > My question is how can I **view** those 39 **similar commands**? Answer:
These two simple commands solved the problem for me: ``` adb kill-server adb start-server ``` Note that unlike [semi-newbie's answer](https://askubuntu.com/a/349218/4066) I don't need `sudo`.
I have face the same problem and i have resolved this by Adding the path of your\_android\_sdk\_path to the environment variable like ``` sudo export $PATH:/your_android_sdk_path/platform-tools/adb ``` its your wish how you want to add this to your account or system wide by editing these file `~/.bashrc` file or `~/.profile` or `/etc/profile, /etc/bash.bashrc, or /etc/environment` if u want to add to system wide access. and then create the link of that in bin ``` sudo ln -s /your_android_sdk_path/platform-tools/adb /bin/adb ``` if you have used adb devices or any command then first kill the server like ``` adb kill-server ``` then start the server like ``` adb start-server adb devices ``` now you can see your devices are listed properly without an issue
Question: OS version: Ubuntu 12.04 I wrote `veditor` in my terminal and got the following message: > > No command 'veditor' found, but there are 39 similar ones > > > My question is how can I **view** those 39 **similar commands**? Answer:
These two simple commands solved the problem for me: ``` adb kill-server adb start-server ``` Note that unlike [semi-newbie's answer](https://askubuntu.com/a/349218/4066) I don't need `sudo`.
The answer to this problem is here : <https://github.com/snowdream/51-android> As an Android developer i suggest you do NOT use "sudo" to force the use of adb anywhere. It's not what we should do. Rules, policies and restrictions are there for our own safety.
Question: OS version: Ubuntu 12.04 I wrote `veditor` in my terminal and got the following message: > > No command 'veditor' found, but there are 39 similar ones > > > My question is how can I **view** those 39 **similar commands**? Answer:
These two simple commands solved the problem for me: ``` adb kill-server adb start-server ``` Note that unlike [semi-newbie's answer](https://askubuntu.com/a/349218/4066) I don't need `sudo`.
I had the same issue and received that insufficient permissions. What I did was revoke the USB authorities for my laptop. Then stopped and started USB debugging. Plugged it back into the laptop and granted usb debugging authorities.
Question: OS version: Ubuntu 12.04 I wrote `veditor` in my terminal and got the following message: > > No command 'veditor' found, but there are 39 similar ones > > > My question is how can I **view** those 39 **similar commands**? Answer:
These two simple commands solved the problem for me: ``` adb kill-server adb start-server ``` Note that unlike [semi-newbie's answer](https://askubuntu.com/a/349218/4066) I don't need `sudo`.
Yet another possibility: USB tethering also conflicts with adb. Disabling it solves the problem for me.
Question: OS version: Ubuntu 12.04 I wrote `veditor` in my terminal and got the following message: > > No command 'veditor' found, but there are 39 similar ones > > > My question is how can I **view** those 39 **similar commands**? Answer:
[Jorch914's answer on Stack Overflow](https://stackoverflow.com/a/25628891) solved this issue for me: > > Ok So I finally found the problem, apparently on this device you have to set to connect as camera(even after usb debugging is already enabled) > > > [![enter image description here](https://i.stack.imgur.com/NYKi8.png)](https://i.stack.imgur.com/NYKi8.png) > > > Also [this link](http://www.techotopia.com/index.php/Testing_Android_Studio_Apps_on_a_Physical_Android_Device) describes the setting up process > > >
I have face the same problem and i have resolved this by Adding the path of your\_android\_sdk\_path to the environment variable like ``` sudo export $PATH:/your_android_sdk_path/platform-tools/adb ``` its your wish how you want to add this to your account or system wide by editing these file `~/.bashrc` file or `~/.profile` or `/etc/profile, /etc/bash.bashrc, or /etc/environment` if u want to add to system wide access. and then create the link of that in bin ``` sudo ln -s /your_android_sdk_path/platform-tools/adb /bin/adb ``` if you have used adb devices or any command then first kill the server like ``` adb kill-server ``` then start the server like ``` adb start-server adb devices ``` now you can see your devices are listed properly without an issue
Question: OS version: Ubuntu 12.04 I wrote `veditor` in my terminal and got the following message: > > No command 'veditor' found, but there are 39 similar ones > > > My question is how can I **view** those 39 **similar commands**? Answer:
These two simple commands solved the problem for me: ``` adb kill-server adb start-server ``` Note that unlike [semi-newbie's answer](https://askubuntu.com/a/349218/4066) I don't need `sudo`.
Today I encountered the `insufficient permissions for device` error, even though `adb` had been working as expected just a few minutes before. Now I get: ``` $ adb devices List of devices attached ???????????? no permissions $ adb shell error: insufficient permissions for device ``` Shortly before encountering the error, I had disabled `Media device (MTP)`, as I figured I would not need to use `MTP`. However, it appears that USB debugging, or at least some `adb` commands, require that `Media device (MTP)` be enabled. To enable `Media device (MTP)` on Android 4.4, go to: ``` Settings Storage The "..." menu (in the upper right corner) USB computer connection Media device (MTP) ``` When `MTP` is disabled, `lsusb` shows the following: ``` Bus 002 Device 071: ID [idVendor1]:[idProduct1] Google Inc. ``` After enabling `MTP`, lsusb shows the following: ``` Bus 002 Device 072: ID [idVendor2]:[idProduct2] [idVendor string] ``` The idVendor and idProduct do change, based on whether or not `MTP` is enabled or disabled. I am not an Android expert, so it is possible that the above behavior is specific to my particular model of phone.
Question: OS version: Ubuntu 12.04 I wrote `veditor` in my terminal and got the following message: > > No command 'veditor' found, but there are 39 similar ones > > > My question is how can I **view** those 39 **similar commands**? Answer:
Today I encountered the `insufficient permissions for device` error, even though `adb` had been working as expected just a few minutes before. Now I get: ``` $ adb devices List of devices attached ???????????? no permissions $ adb shell error: insufficient permissions for device ``` Shortly before encountering the error, I had disabled `Media device (MTP)`, as I figured I would not need to use `MTP`. However, it appears that USB debugging, or at least some `adb` commands, require that `Media device (MTP)` be enabled. To enable `Media device (MTP)` on Android 4.4, go to: ``` Settings Storage The "..." menu (in the upper right corner) USB computer connection Media device (MTP) ``` When `MTP` is disabled, `lsusb` shows the following: ``` Bus 002 Device 071: ID [idVendor1]:[idProduct1] Google Inc. ``` After enabling `MTP`, lsusb shows the following: ``` Bus 002 Device 072: ID [idVendor2]:[idProduct2] [idVendor string] ``` The idVendor and idProduct do change, based on whether or not `MTP` is enabled or disabled. I am not an Android expert, so it is possible that the above behavior is specific to my particular model of phone.
The answer to this problem is here : <https://github.com/snowdream/51-android> As an Android developer i suggest you do NOT use "sudo" to force the use of adb anywhere. It's not what we should do. Rules, policies and restrictions are there for our own safety.
Question: OS version: Ubuntu 12.04 I wrote `veditor` in my terminal and got the following message: > > No command 'veditor' found, but there are 39 similar ones > > > My question is how can I **view** those 39 **similar commands**? Answer:
Today I encountered the `insufficient permissions for device` error, even though `adb` had been working as expected just a few minutes before. Now I get: ``` $ adb devices List of devices attached ???????????? no permissions $ adb shell error: insufficient permissions for device ``` Shortly before encountering the error, I had disabled `Media device (MTP)`, as I figured I would not need to use `MTP`. However, it appears that USB debugging, or at least some `adb` commands, require that `Media device (MTP)` be enabled. To enable `Media device (MTP)` on Android 4.4, go to: ``` Settings Storage The "..." menu (in the upper right corner) USB computer connection Media device (MTP) ``` When `MTP` is disabled, `lsusb` shows the following: ``` Bus 002 Device 071: ID [idVendor1]:[idProduct1] Google Inc. ``` After enabling `MTP`, lsusb shows the following: ``` Bus 002 Device 072: ID [idVendor2]:[idProduct2] [idVendor string] ``` The idVendor and idProduct do change, based on whether or not `MTP` is enabled or disabled. I am not an Android expert, so it is possible that the above behavior is specific to my particular model of phone.
I had the same issue and received that insufficient permissions. What I did was revoke the USB authorities for my laptop. Then stopped and started USB debugging. Plugged it back into the laptop and granted usb debugging authorities.
Question: In our organization, we have SQL Server VM on Azure with always on availability group with 2 nodes. **Scenario:** 1. We have one procedure called "SP\_xyz" and it contains one select query with few inner joins to get list of credential holders. After some load, this stored procedure (SP) started running slow and hence we have optimized this and put that SP back in production and it was running fine for some time. 2. After couple of months as load increased, again there is slowness issue in this SP and again we analysed this SP and optimized. Now the mystery comes, Just to cross verify the new optimized SP, we created the same SP with \_test in production. The new SP is "SP\_xyz\_Test". 3. When we ran this new \_Test SP in prod with same set of parameters for which old SP (SP\_xyz) was running slow, the new optimized SP gave results in milliseconds against few seconds of older SP. 4. To our surprise, the next movement when we ran the old SP, it also started giving results in milliseconds. This really scared us as where all this kind of issue would be there in production, as we have around 300+ SQL stored procedures. We did analyse few things that we could think of to find the root cause: 1. Index rebuild 2. Stats update Also as we know the SP execution plan would be specific to SP name. But here how the old SP has become faster is what we are wondering. But all these things have been scheduled and were running in production and old SP started running slow. But the movement the new \_test SP ran, it has become very fast. Have we missed anything here, and has anybody has faced this issue before? Answer:
I think with the details you provided ,it is not clear ..But since you are using sqlserver 2016.. you can use querystore to track a statement or stored procedure execution over time A query might have different plans over time and one plan may perform better and one may not ..So when you enable query store, you can see all the plan changes over time in the regressed query section,which can help you analyze why one plan is taking more time than the another..At least its a starting point.. below is a query with different plan(dots represent new plans over time) and place where the plotted on the graph indicates time taken [![enter image description here](https://i.stack.imgur.com/jlFuE.png)](https://i.stack.imgur.com/jlFuE.png)
Not sure whether you got the answer for this. I guess it is typical case of execution plans get outdated due to the dynamic nature of your procedure. Try `recompile` option. ``` CREATE PROCEDURE SP_xyz WITH RECOMPILE AS BEGIN ....... END GO ```
Question: Consider this simple AS3 class. ``` package { import flash.display.Sprite; import flash.display.MovieClip; public class MySprite extends Sprite { private var someMC:MovieClip = new MovieClip(); public function MySprite() { super(); addChild(someMC); } } } ``` And this one: ``` package { import flash.display.Sprite; import flash.display.MovieClip; public class MySprite extends Sprite { private var someMC:MovieClip; public function MySprite() { super(); someMC = new MovieClip(); addChild(someMC); } } } ``` Is this the same thing, or is there more to it? I guess its because in the first example, the MovieClip seems to exist before the contructor is called (when does this occur, what is the benefit or not?). Answer:
It's all the same. The compiler translates your first example into the second. The only difference is that you can control instantiation order when you put the assignment into the constructor.
`Actionscript` is a fairly high-level language that, so long as you don't piss off it's garbage collection, tends to be pretty chill with most of the things you can throw at it. Having said that, even lower level languages tend not to care which way you do it, so it really comes down to a question of style. Personally, I try to only initialize constants and variables that I want to tweak the initial values of often above the constructor; that way they're easily found and changed, and not muddled up by a whole lot of `new` this and `()` that.
Question: I would like to remove with purge all entries of locate and its database. I tried ``` apt-get purge locate ``` and ``` rm /etc/updatedb* ``` But is the database gone also? Where is the updatedb database located on debian squeeze? I would like to delete it manually too, so I can cleanly reinstall it Answer:
I prefer to just strace the process, as it's going to lead you right there. This will be distribution agnostic and works if you don't have the man pages. ``` # strace updatedb 2>&1 |grep ^open|grep db open("/etc/updatedb.conf", O_RDONLY) = 3 open("/var/lib/mlocate/mlocate.db", O_RDWR) = 3 open("/var/lib/mlocate/mlocate.db.bUUaw4", O_RDWR|O_CREAT|O_EXCL, 0600) = 4 ```
on mac --statistics is invalid man locate FILES /var/db/locate.database locate database
Question: I would like to remove with purge all entries of locate and its database. I tried ``` apt-get purge locate ``` and ``` rm /etc/updatedb* ``` But is the database gone also? Where is the updatedb database located on debian squeeze? I would like to delete it manually too, so I can cleanly reinstall it Answer:
`man updatedb` search for 'FILES' mine says: ``` FILES /etc/updatedb.conf A configuration file. See updatedb.conf(5). /var/lib/mlocate/mlocate.db The database updated by default. ```
[REDACTED in 2017]: See above answer: locate --statistics works. If you have an /etc/updatedb.conf, you can look in there. I don't. You can read the man page for locate, which says the default location is /var/cache/locate/locatedb. Mine isn't there. You can use locate itself to search for files named "updatedb" or "locatedb". I'm using Cygwin on Windows 7.
Question: I would like to remove with purge all entries of locate and its database. I tried ``` apt-get purge locate ``` and ``` rm /etc/updatedb* ``` But is the database gone also? Where is the updatedb database located on debian squeeze? I would like to delete it manually too, so I can cleanly reinstall it Answer:
On debian, the locate database is stored by default in ``` /var/cache/locate/locatedb ``` If you use `mlocate` as search indexer: The mlocate database is stored at ``` /var/lib/mlocate/mlocate.db ``` see: [How can I view updatedb database content, and then exclude certain files/paths?](https://serverfault.com/questions/454051/how-can-i-view-updatedb-database-content-and-then-exclude-certain-files-paths)
`man updatedb` search for 'FILES' mine says: ``` FILES /etc/updatedb.conf A configuration file. See updatedb.conf(5). /var/lib/mlocate/mlocate.db The database updated by default. ```
Question: I would like to remove with purge all entries of locate and its database. I tried ``` apt-get purge locate ``` and ``` rm /etc/updatedb* ``` But is the database gone also? Where is the updatedb database located on debian squeeze? I would like to delete it manually too, so I can cleanly reinstall it Answer:
On debian, the locate database is stored by default in ``` /var/cache/locate/locatedb ``` If you use `mlocate` as search indexer: The mlocate database is stored at ``` /var/lib/mlocate/mlocate.db ``` see: [How can I view updatedb database content, and then exclude certain files/paths?](https://serverfault.com/questions/454051/how-can-i-view-updatedb-database-content-and-then-exclude-certain-files-paths)
No need to decompile the executable! Just kindly ask 'locate' :-) For updatedb/locate (GNU findutils) version 4.6.0 try calling ``` locate --statistics ``` For me (on cygwin) this yields someting like ``` Database /var/locatedb is in the GNU LOCATE02 format. Database was last modified at 2017:03:13 22:44:31.849172100 +0100 Locate database size: 6101081 bytes All Filenames: 202075 File names have a cumulative length of 22094021 bytes. Of those file names, 2591 contain whitespace, 0 contain newline characters, and 20 contain characters with the high bit set. Compression ratio 72.39% (higher is better) ```
Question: I would like to remove with purge all entries of locate and its database. I tried ``` apt-get purge locate ``` and ``` rm /etc/updatedb* ``` But is the database gone also? Where is the updatedb database located on debian squeeze? I would like to delete it manually too, so I can cleanly reinstall it Answer:
[REDACTED in 2017]: See above answer: locate --statistics works. If you have an /etc/updatedb.conf, you can look in there. I don't. You can read the man page for locate, which says the default location is /var/cache/locate/locatedb. Mine isn't there. You can use locate itself to search for files named "updatedb" or "locatedb". I'm using Cygwin on Windows 7.
on mac --statistics is invalid man locate FILES /var/db/locate.database locate database
Question: I would like to remove with purge all entries of locate and its database. I tried ``` apt-get purge locate ``` and ``` rm /etc/updatedb* ``` But is the database gone also? Where is the updatedb database located on debian squeeze? I would like to delete it manually too, so I can cleanly reinstall it Answer:
On debian, the locate database is stored by default in ``` /var/cache/locate/locatedb ``` If you use `mlocate` as search indexer: The mlocate database is stored at ``` /var/lib/mlocate/mlocate.db ``` see: [How can I view updatedb database content, and then exclude certain files/paths?](https://serverfault.com/questions/454051/how-can-i-view-updatedb-database-content-and-then-exclude-certain-files-paths)
I prefer to just strace the process, as it's going to lead you right there. This will be distribution agnostic and works if you don't have the man pages. ``` # strace updatedb 2>&1 |grep ^open|grep db open("/etc/updatedb.conf", O_RDONLY) = 3 open("/var/lib/mlocate/mlocate.db", O_RDWR) = 3 open("/var/lib/mlocate/mlocate.db.bUUaw4", O_RDWR|O_CREAT|O_EXCL, 0600) = 4 ```