qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
51,733,971
I'm currently trying to implement a generic method to adapt a DTO that comes from an external service into a model of my servisse and I ran into an issue. First let me just contextualize the problem. Let's say that an external service returns the following DTO to my application. ``` public class ExampleDTO { public int Field1 { get; set; } public int Field2 { get; set; } } ``` And this is my model. ``` public class ExampleModel { public int Field1 { get; set; } public int Field2 { get; set; } } ``` If I wanted to adapt the first class into my model I could just simply write the following method: ``` public ExampleModel Adapt(ExampleDTO source) { if (source == null) return null; var target = new ExampleModel() { Field1 = source.Field1, Field2 = source.Field2 }; return target; } ``` Now let's say that when we get a collection of ExampleDTOs, the service instead of just returning a collection of type ICollection, returns the following class: ``` public class PagedCollectionResultDTO<T> { public List<T> Data { get; set; } public int Page { get; set; } public int PageSize { get; set; } public int Total { get; set; } } ``` Where the list of ExampleDTOs comes on the Data field and the page number, page size and total number of records comes on the rest of the fields. I'm trying to implement a generic method to adapt this class to my own model, which has the same structure. I want to do this independently of the type T of the Data field. ``` public class PagedCollectionResult<T> { public List<T> Data { get; set; } public int Page { get; set; } public int PageSize { get; set; } public int Total { get; set; } public PagedCollectionResult() => (Data, Page, PageSize, Total) = (new List<T>(), 0, 0, 0); } ``` I've tried the following method, where I try to adapt the DTO paged result (S) into the model paged result (T) : ``` public PagedCollectionResult<T> Adapt<S,T>(PagedCollectionResultDTO<S> source) { if (source == null) return null; var target = new PagedCollectionResult<T>(); foreach (var item in source.Data) target.Data.Add(this.Adapt(item)); target.Page = source.Page; target.PageSize = source.PageSize; target.Total = source.Total; return target; } ``` The thing is that I'm getting an error in the line: ``` target.Data.Add(this.Adapt(item)); ``` It says that it can't convert S into ExampleDTO. If I put a restriction for ExampleDTO/ExampleModel on Adapt this isn't generic anymore. Is there a way to call the Adapt(item) method for the specific type? This is my complete TypeAdapter: ``` public class TypeAdapter { public PagedCollectionResult<T> Adapt<S,T>(PagedCollectionResultDTO<S> source) { if (source == null) return null; var target = new PagedCollectionResult<T>(); foreach (var item in source.Data) target.Data.Add(this.Adapt(item)); target.Page = source.Page; target.PageSize = source.PageSize; target.Total = source.Total; return target; } public ExampleModel Adapt(ExampleDTO source) { if (source == null) return null; var target = new ExampleModel() { Field1 = source.Field1, Field2 = source.Field2 }; return target; } } ```
2018/08/07
[ "https://Stackoverflow.com/questions/51733971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6184160/" ]
As I understand it, the solution is broken into two parts, that should work independently from one another. **Part A: generic pattern for object transformation** Create an interface to be implemented by all your models that need to be adapted from an external DTO. ``` public interface IExampleModel<S> { void Adapt(S source); } ``` This interface requires only an `Adapt` method and the generic type `S` describes the type to adapt from. Now build a class for each model that you want to adapt from another type. ``` public class ExampleModel : IExampleModel<ExampleDTO> { public int Field1 { get; set; } public int Field2 { get; set; } public void Adapt(ExampleDTO source) { Field1 = source.Field1; Field2 = source.Field2; } } ``` Your TypeAdapter class: ``` public class TypeAdapter { public PagedCollectionResult<T> Adapt<S,T>(PagedCollectionResultDTO<S> source) where T: IExampleModel<S>, new() { var target = new PagedCollectionResult<T>(); target.Page = source.Page; target.Page = source.PageSize; target.Total = source.Total; target.Data = AdaptList<S,T>(source.Data).ToList(); return target; } protected IEnumerable<T> AdaptList<S,T>(IEnumerable<S> sourceList) where T : IExampleModel<S>, new() { foreach (S sourceItem in sourceList) { T targetItem = new T(); targetItem.Adapt(sourceItem); yield return targetItem; } } } ``` *NOTE 1*: the `PagedCollectionResult` constructor is not required in this approach. *NOTE 2*: I chose to put the `Adapt` method in each model class rather than in the TypeAdapter to satisfy the *open-closed principle*. This way when you want to extend the solution in order to accept a second type transformation, you don't modify any existing classes (i.e. the `TypeModifier`), but add instead a new class. ``` public class ExampleModel2 : IExampleModel<ExampleDTO2> { public int Field1 { get; set; } public int Field2 { get; set; } public void Adapt(ExampleDTO2 source) { Field1 = source.Field1; Field2 = source.Field2; } } ``` Adding this class will extend the solution to include this transformation as well. Ofcourse you can choose your own way if it suits your application better. **Part B: the service call** There isn't a way, that I know of, for the application to extract the target type, given only the source type. You must provide it in the service call. You have no description on what your service call looks like, so I will just give you some hints. If your service call is something like this it would work: ``` public void ServiceCall<S,T>(PagedCollectionResultDTO<S> sourceCollection) where T : IExampleModel<S>, new() { var typeAdapter = new TypeAdapter(); var targetCollection = typeAdapter.Adapt<S,T>(sourceCollection); } ``` If passing the T type in the service call is not possible you might use an if-clause to properly define the target type: ``` public void ServiceCall<S>(PagedCollectionResultDTO<S> sourceCollection) { var typeAdapter = new TypeAdapter(); if (typeof(S) == typeof(ExampleDTO)) { var targetCollection = typeAdapter.Adapt<ExampleDTO, ExampleModel>(sourceCollection as PagedCollectionResultDTO<ExampleDTO>); } else if(typeof(S) == typeof(ExampleDTO2)) { var targetCollection = typeAdapter.Adapt<ExampleDTO2, ExampleModel2>(sourceCollection as PagedCollectionResultDTO<ExampleDTO2>); } } ```
You have two choices here, 1. Generate list of properties of Model and Dto via reflection. and then match their types. ``` class AdapterHelper<T1, T2> { public T1 Adapt(T2 source) { T1 targetItem = Activator.CreateInstance<T1>(); var props = typeof(T1).GetProperties(); var targetProps = typeof(T2).GetProperties(); foreach (var prop in props) { foreach (var targetProp in targetProps) { if (prop.Name == targetProp.Name) { targetProp.SetValue(targetItem, prop.GetValue(source)); //assign } } } return targetItem; } } ``` 2.Use [Automapper](https://www.infoworld.com/article/3192900/application-development/how-to-work-with-automapper-in-c.html)
51,733,971
I'm currently trying to implement a generic method to adapt a DTO that comes from an external service into a model of my servisse and I ran into an issue. First let me just contextualize the problem. Let's say that an external service returns the following DTO to my application. ``` public class ExampleDTO { public int Field1 { get; set; } public int Field2 { get; set; } } ``` And this is my model. ``` public class ExampleModel { public int Field1 { get; set; } public int Field2 { get; set; } } ``` If I wanted to adapt the first class into my model I could just simply write the following method: ``` public ExampleModel Adapt(ExampleDTO source) { if (source == null) return null; var target = new ExampleModel() { Field1 = source.Field1, Field2 = source.Field2 }; return target; } ``` Now let's say that when we get a collection of ExampleDTOs, the service instead of just returning a collection of type ICollection, returns the following class: ``` public class PagedCollectionResultDTO<T> { public List<T> Data { get; set; } public int Page { get; set; } public int PageSize { get; set; } public int Total { get; set; } } ``` Where the list of ExampleDTOs comes on the Data field and the page number, page size and total number of records comes on the rest of the fields. I'm trying to implement a generic method to adapt this class to my own model, which has the same structure. I want to do this independently of the type T of the Data field. ``` public class PagedCollectionResult<T> { public List<T> Data { get; set; } public int Page { get; set; } public int PageSize { get; set; } public int Total { get; set; } public PagedCollectionResult() => (Data, Page, PageSize, Total) = (new List<T>(), 0, 0, 0); } ``` I've tried the following method, where I try to adapt the DTO paged result (S) into the model paged result (T) : ``` public PagedCollectionResult<T> Adapt<S,T>(PagedCollectionResultDTO<S> source) { if (source == null) return null; var target = new PagedCollectionResult<T>(); foreach (var item in source.Data) target.Data.Add(this.Adapt(item)); target.Page = source.Page; target.PageSize = source.PageSize; target.Total = source.Total; return target; } ``` The thing is that I'm getting an error in the line: ``` target.Data.Add(this.Adapt(item)); ``` It says that it can't convert S into ExampleDTO. If I put a restriction for ExampleDTO/ExampleModel on Adapt this isn't generic anymore. Is there a way to call the Adapt(item) method for the specific type? This is my complete TypeAdapter: ``` public class TypeAdapter { public PagedCollectionResult<T> Adapt<S,T>(PagedCollectionResultDTO<S> source) { if (source == null) return null; var target = new PagedCollectionResult<T>(); foreach (var item in source.Data) target.Data.Add(this.Adapt(item)); target.Page = source.Page; target.PageSize = source.PageSize; target.Total = source.Total; return target; } public ExampleModel Adapt(ExampleDTO source) { if (source == null) return null; var target = new ExampleModel() { Field1 = source.Field1, Field2 = source.Field2 }; return target; } } ```
2018/08/07
[ "https://Stackoverflow.com/questions/51733971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6184160/" ]
As I understand it, the solution is broken into two parts, that should work independently from one another. **Part A: generic pattern for object transformation** Create an interface to be implemented by all your models that need to be adapted from an external DTO. ``` public interface IExampleModel<S> { void Adapt(S source); } ``` This interface requires only an `Adapt` method and the generic type `S` describes the type to adapt from. Now build a class for each model that you want to adapt from another type. ``` public class ExampleModel : IExampleModel<ExampleDTO> { public int Field1 { get; set; } public int Field2 { get; set; } public void Adapt(ExampleDTO source) { Field1 = source.Field1; Field2 = source.Field2; } } ``` Your TypeAdapter class: ``` public class TypeAdapter { public PagedCollectionResult<T> Adapt<S,T>(PagedCollectionResultDTO<S> source) where T: IExampleModel<S>, new() { var target = new PagedCollectionResult<T>(); target.Page = source.Page; target.Page = source.PageSize; target.Total = source.Total; target.Data = AdaptList<S,T>(source.Data).ToList(); return target; } protected IEnumerable<T> AdaptList<S,T>(IEnumerable<S> sourceList) where T : IExampleModel<S>, new() { foreach (S sourceItem in sourceList) { T targetItem = new T(); targetItem.Adapt(sourceItem); yield return targetItem; } } } ``` *NOTE 1*: the `PagedCollectionResult` constructor is not required in this approach. *NOTE 2*: I chose to put the `Adapt` method in each model class rather than in the TypeAdapter to satisfy the *open-closed principle*. This way when you want to extend the solution in order to accept a second type transformation, you don't modify any existing classes (i.e. the `TypeModifier`), but add instead a new class. ``` public class ExampleModel2 : IExampleModel<ExampleDTO2> { public int Field1 { get; set; } public int Field2 { get; set; } public void Adapt(ExampleDTO2 source) { Field1 = source.Field1; Field2 = source.Field2; } } ``` Adding this class will extend the solution to include this transformation as well. Ofcourse you can choose your own way if it suits your application better. **Part B: the service call** There isn't a way, that I know of, for the application to extract the target type, given only the source type. You must provide it in the service call. You have no description on what your service call looks like, so I will just give you some hints. If your service call is something like this it would work: ``` public void ServiceCall<S,T>(PagedCollectionResultDTO<S> sourceCollection) where T : IExampleModel<S>, new() { var typeAdapter = new TypeAdapter(); var targetCollection = typeAdapter.Adapt<S,T>(sourceCollection); } ``` If passing the T type in the service call is not possible you might use an if-clause to properly define the target type: ``` public void ServiceCall<S>(PagedCollectionResultDTO<S> sourceCollection) { var typeAdapter = new TypeAdapter(); if (typeof(S) == typeof(ExampleDTO)) { var targetCollection = typeAdapter.Adapt<ExampleDTO, ExampleModel>(sourceCollection as PagedCollectionResultDTO<ExampleDTO>); } else if(typeof(S) == typeof(ExampleDTO2)) { var targetCollection = typeAdapter.Adapt<ExampleDTO2, ExampleModel2>(sourceCollection as PagedCollectionResultDTO<ExampleDTO2>); } } ```
Because you are implementing a generic method, you need to either implement a generic method for transforming S to T (see other answers), or you need to pass in the transformation function. ``` public PagedCollectionResult<T> Adapt<S, T>(PagedCollectionResultDTO<S> source, Func<S, T> adapt) { if (source == null) return null; var target = new PagedCollectionResult<T>(); foreach (var item in source.Data) target.Data.Add(adapt(item)); target.Page = source.Page; target.PageSize = source.PageSize; target.Total = source.Total; return target; } ``` Here is example code to call the above method. ``` static void Main(string[] args) { var src = new PagedCollectionResultDTO<ExampleDTO>(); src.Data = new List<ExampleDTO>{ new ExampleDTO{ Field1 = 1, Field2 = 2 } }; var adapter = new TypeAdapter(); var result = adapter.Adapt(src, AdaptExampleDTO); } public static ExampleModel AdaptExampleDTO(ExampleDTO source) { if (source == null) return null; var target = new ExampleModel() { Field1 = source.Field1, Field2 = source.Field2 }; return target; } ```
51,733,971
I'm currently trying to implement a generic method to adapt a DTO that comes from an external service into a model of my servisse and I ran into an issue. First let me just contextualize the problem. Let's say that an external service returns the following DTO to my application. ``` public class ExampleDTO { public int Field1 { get; set; } public int Field2 { get; set; } } ``` And this is my model. ``` public class ExampleModel { public int Field1 { get; set; } public int Field2 { get; set; } } ``` If I wanted to adapt the first class into my model I could just simply write the following method: ``` public ExampleModel Adapt(ExampleDTO source) { if (source == null) return null; var target = new ExampleModel() { Field1 = source.Field1, Field2 = source.Field2 }; return target; } ``` Now let's say that when we get a collection of ExampleDTOs, the service instead of just returning a collection of type ICollection, returns the following class: ``` public class PagedCollectionResultDTO<T> { public List<T> Data { get; set; } public int Page { get; set; } public int PageSize { get; set; } public int Total { get; set; } } ``` Where the list of ExampleDTOs comes on the Data field and the page number, page size and total number of records comes on the rest of the fields. I'm trying to implement a generic method to adapt this class to my own model, which has the same structure. I want to do this independently of the type T of the Data field. ``` public class PagedCollectionResult<T> { public List<T> Data { get; set; } public int Page { get; set; } public int PageSize { get; set; } public int Total { get; set; } public PagedCollectionResult() => (Data, Page, PageSize, Total) = (new List<T>(), 0, 0, 0); } ``` I've tried the following method, where I try to adapt the DTO paged result (S) into the model paged result (T) : ``` public PagedCollectionResult<T> Adapt<S,T>(PagedCollectionResultDTO<S> source) { if (source == null) return null; var target = new PagedCollectionResult<T>(); foreach (var item in source.Data) target.Data.Add(this.Adapt(item)); target.Page = source.Page; target.PageSize = source.PageSize; target.Total = source.Total; return target; } ``` The thing is that I'm getting an error in the line: ``` target.Data.Add(this.Adapt(item)); ``` It says that it can't convert S into ExampleDTO. If I put a restriction for ExampleDTO/ExampleModel on Adapt this isn't generic anymore. Is there a way to call the Adapt(item) method for the specific type? This is my complete TypeAdapter: ``` public class TypeAdapter { public PagedCollectionResult<T> Adapt<S,T>(PagedCollectionResultDTO<S> source) { if (source == null) return null; var target = new PagedCollectionResult<T>(); foreach (var item in source.Data) target.Data.Add(this.Adapt(item)); target.Page = source.Page; target.PageSize = source.PageSize; target.Total = source.Total; return target; } public ExampleModel Adapt(ExampleDTO source) { if (source == null) return null; var target = new ExampleModel() { Field1 = source.Field1, Field2 = source.Field2 }; return target; } } ```
2018/08/07
[ "https://Stackoverflow.com/questions/51733971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6184160/" ]
As I understand it, the solution is broken into two parts, that should work independently from one another. **Part A: generic pattern for object transformation** Create an interface to be implemented by all your models that need to be adapted from an external DTO. ``` public interface IExampleModel<S> { void Adapt(S source); } ``` This interface requires only an `Adapt` method and the generic type `S` describes the type to adapt from. Now build a class for each model that you want to adapt from another type. ``` public class ExampleModel : IExampleModel<ExampleDTO> { public int Field1 { get; set; } public int Field2 { get; set; } public void Adapt(ExampleDTO source) { Field1 = source.Field1; Field2 = source.Field2; } } ``` Your TypeAdapter class: ``` public class TypeAdapter { public PagedCollectionResult<T> Adapt<S,T>(PagedCollectionResultDTO<S> source) where T: IExampleModel<S>, new() { var target = new PagedCollectionResult<T>(); target.Page = source.Page; target.Page = source.PageSize; target.Total = source.Total; target.Data = AdaptList<S,T>(source.Data).ToList(); return target; } protected IEnumerable<T> AdaptList<S,T>(IEnumerable<S> sourceList) where T : IExampleModel<S>, new() { foreach (S sourceItem in sourceList) { T targetItem = new T(); targetItem.Adapt(sourceItem); yield return targetItem; } } } ``` *NOTE 1*: the `PagedCollectionResult` constructor is not required in this approach. *NOTE 2*: I chose to put the `Adapt` method in each model class rather than in the TypeAdapter to satisfy the *open-closed principle*. This way when you want to extend the solution in order to accept a second type transformation, you don't modify any existing classes (i.e. the `TypeModifier`), but add instead a new class. ``` public class ExampleModel2 : IExampleModel<ExampleDTO2> { public int Field1 { get; set; } public int Field2 { get; set; } public void Adapt(ExampleDTO2 source) { Field1 = source.Field1; Field2 = source.Field2; } } ``` Adding this class will extend the solution to include this transformation as well. Ofcourse you can choose your own way if it suits your application better. **Part B: the service call** There isn't a way, that I know of, for the application to extract the target type, given only the source type. You must provide it in the service call. You have no description on what your service call looks like, so I will just give you some hints. If your service call is something like this it would work: ``` public void ServiceCall<S,T>(PagedCollectionResultDTO<S> sourceCollection) where T : IExampleModel<S>, new() { var typeAdapter = new TypeAdapter(); var targetCollection = typeAdapter.Adapt<S,T>(sourceCollection); } ``` If passing the T type in the service call is not possible you might use an if-clause to properly define the target type: ``` public void ServiceCall<S>(PagedCollectionResultDTO<S> sourceCollection) { var typeAdapter = new TypeAdapter(); if (typeof(S) == typeof(ExampleDTO)) { var targetCollection = typeAdapter.Adapt<ExampleDTO, ExampleModel>(sourceCollection as PagedCollectionResultDTO<ExampleDTO>); } else if(typeof(S) == typeof(ExampleDTO2)) { var targetCollection = typeAdapter.Adapt<ExampleDTO2, ExampleModel2>(sourceCollection as PagedCollectionResultDTO<ExampleDTO2>); } } ```
Thank you all for your responses, they helped me getting in the right direction. I used reflection at runtime to resolve the right adapt method. I learned a few things about reflection thanks to you. I'm sharing the solution in hope I can also give something back. This is what I ended up with. ``` public PagedCollectionResult<T> Adapt<S, T>(PagedCollectionResultDTO<S> source) { if (source == null) { return null; } var target = new PagedCollectionResult<T>(); // Get the type of S at runtime Type[] types = { typeof(S) }; // Find the Adapt method on the TypeAdapter class that accepts an object of type S var adaptMethod = typeof(TypeAdapter).GetMethod("Adapt", types); foreach (var item in source.Data) { // for each item call the adapt method previously resolved and pass the item as parameter var parameters = new object[] { item }; target.Data.Add((T)adaptMethod.Invoke(this, parameters)); } target.Page = source.Page; target.PageSize = source.PageSize; target.Total = source.Total; return target; } ```
32,259,248
Python's argparse lets me define argument names containing a dot in the name. But how can I access these ? ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("inputfile.txt") parser.add_argument("outputfile.txt") args = parser.parse_args(['hello', 'world']) # now args is: # Namespace(inputfile.txt='hello', outputfile.txt='world') # and this does not work print(args.inputfile.txt) >>> AttributeError: 'Namespace' object has no attribute 'inputfile' ``` Obviously attribute names can be created with a dot in their name but how can these be accessed ? Edit: My goal was to let argparse display the inputfile.txt name (e.g. with --help) but call the attribute "inputfile". After trying some of the suggestions the easiest way to accomplish this is using the metavar option: ``` parser.add_argument("inputfile", metavar="inputfile.txt") ```
2015/08/27
[ "https://Stackoverflow.com/questions/32259248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2599567/" ]
Using the dest option, you can assign it to anything: ``` parser = argparse.ArgumentParser() parser.add_argument("inputfile.txt", dest='infile') parser.add_argument("outputfile.txt", dest='out') args = parser.parse_args(['hello', 'world']) # now args is: # Namespace(infile='hello', out='world') ``` Hope that helps.
I strongly recommend you to refactor your code to change the argument name. But, if you won't or can't, this will do the job: ``` args.__dict__['inputfile.txt'] ```
32,259,248
Python's argparse lets me define argument names containing a dot in the name. But how can I access these ? ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("inputfile.txt") parser.add_argument("outputfile.txt") args = parser.parse_args(['hello', 'world']) # now args is: # Namespace(inputfile.txt='hello', outputfile.txt='world') # and this does not work print(args.inputfile.txt) >>> AttributeError: 'Namespace' object has no attribute 'inputfile' ``` Obviously attribute names can be created with a dot in their name but how can these be accessed ? Edit: My goal was to let argparse display the inputfile.txt name (e.g. with --help) but call the attribute "inputfile". After trying some of the suggestions the easiest way to accomplish this is using the metavar option: ``` parser.add_argument("inputfile", metavar="inputfile.txt") ```
2015/08/27
[ "https://Stackoverflow.com/questions/32259248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2599567/" ]
Internally, `argparse` will add all attributes to the `Namespace()` instance with [`setattr`](https://docs.python.org/2/library/functions.html#setattr). Accordingly, you can access the values with [`getattr`](https://docs.python.org/2/library/functions.html#getattr): ``` getattr(args, 'inputfile.txt') ``` However, this is not as intuitive and in general attribute names with dots in them should be avoided. It is recommended to use the [`dest`](https://docs.python.org/3/library/argparse.html#dest) option of [`argparse.add_argument`](https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument) to define your own variable in which to store the value for that argument, as hd1 suggests in their answer.
Using the dest option, you can assign it to anything: ``` parser = argparse.ArgumentParser() parser.add_argument("inputfile.txt", dest='infile') parser.add_argument("outputfile.txt", dest='out') args = parser.parse_args(['hello', 'world']) # now args is: # Namespace(infile='hello', out='world') ``` Hope that helps.
32,259,248
Python's argparse lets me define argument names containing a dot in the name. But how can I access these ? ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("inputfile.txt") parser.add_argument("outputfile.txt") args = parser.parse_args(['hello', 'world']) # now args is: # Namespace(inputfile.txt='hello', outputfile.txt='world') # and this does not work print(args.inputfile.txt) >>> AttributeError: 'Namespace' object has no attribute 'inputfile' ``` Obviously attribute names can be created with a dot in their name but how can these be accessed ? Edit: My goal was to let argparse display the inputfile.txt name (e.g. with --help) but call the attribute "inputfile". After trying some of the suggestions the easiest way to accomplish this is using the metavar option: ``` parser.add_argument("inputfile", metavar="inputfile.txt") ```
2015/08/27
[ "https://Stackoverflow.com/questions/32259248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2599567/" ]
Rename the argument to `inputfile` and use `metavar` to set the display value for the user. ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("inputfile", metavar = "inputfile.txt") parser.add_argument("outputfile", metavar = "outputfile.txt") args = parser.parse_args(['hello', 'world']) # now args is: # Namespace(inputfile='hello', outputfile='world') print(args.inputfile) ```
Using the dest option, you can assign it to anything: ``` parser = argparse.ArgumentParser() parser.add_argument("inputfile.txt", dest='infile') parser.add_argument("outputfile.txt", dest='out') args = parser.parse_args(['hello', 'world']) # now args is: # Namespace(infile='hello', out='world') ``` Hope that helps.
32,259,248
Python's argparse lets me define argument names containing a dot in the name. But how can I access these ? ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("inputfile.txt") parser.add_argument("outputfile.txt") args = parser.parse_args(['hello', 'world']) # now args is: # Namespace(inputfile.txt='hello', outputfile.txt='world') # and this does not work print(args.inputfile.txt) >>> AttributeError: 'Namespace' object has no attribute 'inputfile' ``` Obviously attribute names can be created with a dot in their name but how can these be accessed ? Edit: My goal was to let argparse display the inputfile.txt name (e.g. with --help) but call the attribute "inputfile". After trying some of the suggestions the easiest way to accomplish this is using the metavar option: ``` parser.add_argument("inputfile", metavar="inputfile.txt") ```
2015/08/27
[ "https://Stackoverflow.com/questions/32259248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2599567/" ]
Internally, `argparse` will add all attributes to the `Namespace()` instance with [`setattr`](https://docs.python.org/2/library/functions.html#setattr). Accordingly, you can access the values with [`getattr`](https://docs.python.org/2/library/functions.html#getattr): ``` getattr(args, 'inputfile.txt') ``` However, this is not as intuitive and in general attribute names with dots in them should be avoided. It is recommended to use the [`dest`](https://docs.python.org/3/library/argparse.html#dest) option of [`argparse.add_argument`](https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument) to define your own variable in which to store the value for that argument, as hd1 suggests in their answer.
I strongly recommend you to refactor your code to change the argument name. But, if you won't or can't, this will do the job: ``` args.__dict__['inputfile.txt'] ```
32,259,248
Python's argparse lets me define argument names containing a dot in the name. But how can I access these ? ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("inputfile.txt") parser.add_argument("outputfile.txt") args = parser.parse_args(['hello', 'world']) # now args is: # Namespace(inputfile.txt='hello', outputfile.txt='world') # and this does not work print(args.inputfile.txt) >>> AttributeError: 'Namespace' object has no attribute 'inputfile' ``` Obviously attribute names can be created with a dot in their name but how can these be accessed ? Edit: My goal was to let argparse display the inputfile.txt name (e.g. with --help) but call the attribute "inputfile". After trying some of the suggestions the easiest way to accomplish this is using the metavar option: ``` parser.add_argument("inputfile", metavar="inputfile.txt") ```
2015/08/27
[ "https://Stackoverflow.com/questions/32259248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2599567/" ]
Why not use [FileType](https://docs.python.org/2.7/library/argparse.html#filetype-objects) objects instead? ``` >>> import argparse >>> >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--infile', type=argparse.FileType('r')) _StoreAction(option_strings=['--infile'], dest='infile', nargs=None, const=None, default=None, type=FileType('r'), choices=None, help=None, metavar=None) >>> parser.add_argument('--outfile', type=argparse.FileType('w')) _StoreAction(option_strings=['--outfile'], dest='outfile', nargs=None, const=None, default=None, type=FileType('w'), choices=None, help=None, metavar=None) >>> parser.parse_args(['--infile', 'input.txt', '--outfile', 'output.txt']) Namespace(infile=<open file 'input.txt', mode 'r' at 0x100f99e40>, outfile=<open file 'output.txt', mode 'w' at 0x100f99ed0>) ```
I strongly recommend you to refactor your code to change the argument name. But, if you won't or can't, this will do the job: ``` args.__dict__['inputfile.txt'] ```
32,259,248
Python's argparse lets me define argument names containing a dot in the name. But how can I access these ? ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("inputfile.txt") parser.add_argument("outputfile.txt") args = parser.parse_args(['hello', 'world']) # now args is: # Namespace(inputfile.txt='hello', outputfile.txt='world') # and this does not work print(args.inputfile.txt) >>> AttributeError: 'Namespace' object has no attribute 'inputfile' ``` Obviously attribute names can be created with a dot in their name but how can these be accessed ? Edit: My goal was to let argparse display the inputfile.txt name (e.g. with --help) but call the attribute "inputfile". After trying some of the suggestions the easiest way to accomplish this is using the metavar option: ``` parser.add_argument("inputfile", metavar="inputfile.txt") ```
2015/08/27
[ "https://Stackoverflow.com/questions/32259248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2599567/" ]
Rename the argument to `inputfile` and use `metavar` to set the display value for the user. ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("inputfile", metavar = "inputfile.txt") parser.add_argument("outputfile", metavar = "outputfile.txt") args = parser.parse_args(['hello', 'world']) # now args is: # Namespace(inputfile='hello', outputfile='world') print(args.inputfile) ```
I strongly recommend you to refactor your code to change the argument name. But, if you won't or can't, this will do the job: ``` args.__dict__['inputfile.txt'] ```
32,259,248
Python's argparse lets me define argument names containing a dot in the name. But how can I access these ? ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("inputfile.txt") parser.add_argument("outputfile.txt") args = parser.parse_args(['hello', 'world']) # now args is: # Namespace(inputfile.txt='hello', outputfile.txt='world') # and this does not work print(args.inputfile.txt) >>> AttributeError: 'Namespace' object has no attribute 'inputfile' ``` Obviously attribute names can be created with a dot in their name but how can these be accessed ? Edit: My goal was to let argparse display the inputfile.txt name (e.g. with --help) but call the attribute "inputfile". After trying some of the suggestions the easiest way to accomplish this is using the metavar option: ``` parser.add_argument("inputfile", metavar="inputfile.txt") ```
2015/08/27
[ "https://Stackoverflow.com/questions/32259248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2599567/" ]
Internally, `argparse` will add all attributes to the `Namespace()` instance with [`setattr`](https://docs.python.org/2/library/functions.html#setattr). Accordingly, you can access the values with [`getattr`](https://docs.python.org/2/library/functions.html#getattr): ``` getattr(args, 'inputfile.txt') ``` However, this is not as intuitive and in general attribute names with dots in them should be avoided. It is recommended to use the [`dest`](https://docs.python.org/3/library/argparse.html#dest) option of [`argparse.add_argument`](https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument) to define your own variable in which to store the value for that argument, as hd1 suggests in their answer.
Why not use [FileType](https://docs.python.org/2.7/library/argparse.html#filetype-objects) objects instead? ``` >>> import argparse >>> >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--infile', type=argparse.FileType('r')) _StoreAction(option_strings=['--infile'], dest='infile', nargs=None, const=None, default=None, type=FileType('r'), choices=None, help=None, metavar=None) >>> parser.add_argument('--outfile', type=argparse.FileType('w')) _StoreAction(option_strings=['--outfile'], dest='outfile', nargs=None, const=None, default=None, type=FileType('w'), choices=None, help=None, metavar=None) >>> parser.parse_args(['--infile', 'input.txt', '--outfile', 'output.txt']) Namespace(infile=<open file 'input.txt', mode 'r' at 0x100f99e40>, outfile=<open file 'output.txt', mode 'w' at 0x100f99ed0>) ```
32,259,248
Python's argparse lets me define argument names containing a dot in the name. But how can I access these ? ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("inputfile.txt") parser.add_argument("outputfile.txt") args = parser.parse_args(['hello', 'world']) # now args is: # Namespace(inputfile.txt='hello', outputfile.txt='world') # and this does not work print(args.inputfile.txt) >>> AttributeError: 'Namespace' object has no attribute 'inputfile' ``` Obviously attribute names can be created with a dot in their name but how can these be accessed ? Edit: My goal was to let argparse display the inputfile.txt name (e.g. with --help) but call the attribute "inputfile". After trying some of the suggestions the easiest way to accomplish this is using the metavar option: ``` parser.add_argument("inputfile", metavar="inputfile.txt") ```
2015/08/27
[ "https://Stackoverflow.com/questions/32259248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2599567/" ]
Internally, `argparse` will add all attributes to the `Namespace()` instance with [`setattr`](https://docs.python.org/2/library/functions.html#setattr). Accordingly, you can access the values with [`getattr`](https://docs.python.org/2/library/functions.html#getattr): ``` getattr(args, 'inputfile.txt') ``` However, this is not as intuitive and in general attribute names with dots in them should be avoided. It is recommended to use the [`dest`](https://docs.python.org/3/library/argparse.html#dest) option of [`argparse.add_argument`](https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument) to define your own variable in which to store the value for that argument, as hd1 suggests in their answer.
Rename the argument to `inputfile` and use `metavar` to set the display value for the user. ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("inputfile", metavar = "inputfile.txt") parser.add_argument("outputfile", metavar = "outputfile.txt") args = parser.parse_args(['hello', 'world']) # now args is: # Namespace(inputfile='hello', outputfile='world') print(args.inputfile) ```
32,259,248
Python's argparse lets me define argument names containing a dot in the name. But how can I access these ? ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("inputfile.txt") parser.add_argument("outputfile.txt") args = parser.parse_args(['hello', 'world']) # now args is: # Namespace(inputfile.txt='hello', outputfile.txt='world') # and this does not work print(args.inputfile.txt) >>> AttributeError: 'Namespace' object has no attribute 'inputfile' ``` Obviously attribute names can be created with a dot in their name but how can these be accessed ? Edit: My goal was to let argparse display the inputfile.txt name (e.g. with --help) but call the attribute "inputfile". After trying some of the suggestions the easiest way to accomplish this is using the metavar option: ``` parser.add_argument("inputfile", metavar="inputfile.txt") ```
2015/08/27
[ "https://Stackoverflow.com/questions/32259248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2599567/" ]
Rename the argument to `inputfile` and use `metavar` to set the display value for the user. ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("inputfile", metavar = "inputfile.txt") parser.add_argument("outputfile", metavar = "outputfile.txt") args = parser.parse_args(['hello', 'world']) # now args is: # Namespace(inputfile='hello', outputfile='world') print(args.inputfile) ```
Why not use [FileType](https://docs.python.org/2.7/library/argparse.html#filetype-objects) objects instead? ``` >>> import argparse >>> >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--infile', type=argparse.FileType('r')) _StoreAction(option_strings=['--infile'], dest='infile', nargs=None, const=None, default=None, type=FileType('r'), choices=None, help=None, metavar=None) >>> parser.add_argument('--outfile', type=argparse.FileType('w')) _StoreAction(option_strings=['--outfile'], dest='outfile', nargs=None, const=None, default=None, type=FileType('w'), choices=None, help=None, metavar=None) >>> parser.parse_args(['--infile', 'input.txt', '--outfile', 'output.txt']) Namespace(infile=<open file 'input.txt', mode 'r' at 0x100f99e40>, outfile=<open file 'output.txt', mode 'w' at 0x100f99ed0>) ```
501,248
I was bored recently so I decided to download and install drivers from ASUS site. My motherboard is Asus P5K. After downloading the drivers, I messed up the installation somehow (don't remember the details) and now I don't have sound at all! I'm new to Ubuntu and I don't have a clue how driver setup works. Can you tell me how to bring back the old drivers or how to install this driver? And the first driver worked perfectly, but I was curious about the new driver so I messed up :( P.S, Ubuntu 14.4
2014/07/22
[ "https://askubuntu.com/questions/501248", "https://askubuntu.com", "https://askubuntu.com/users/231422/" ]
I think you should install the *ibus-m17n* package. ``` sudo apt-get install ibus-m17n ``` Then, next time you log in, you should see a bunch of new Sinhala options when running *ibus-setup*. Pick the one of your choice, and hopefully it makes a difference.
To add the functionality of multiple keyboards, first add (as root) to /etc/xdg/lxsession/LXDE/autostart your language choices, for example, for US and French, add @setxkbmap -layout "us,fr". See <http://lxlinux.com/#19> for additional information.
501,248
I was bored recently so I decided to download and install drivers from ASUS site. My motherboard is Asus P5K. After downloading the drivers, I messed up the installation somehow (don't remember the details) and now I don't have sound at all! I'm new to Ubuntu and I don't have a clue how driver setup works. Can you tell me how to bring back the old drivers or how to install this driver? And the first driver worked perfectly, but I was curious about the new driver so I messed up :( P.S, Ubuntu 14.4
2014/07/22
[ "https://askubuntu.com/questions/501248", "https://askubuntu.com", "https://askubuntu.com/users/231422/" ]
I recently had a really hard time making this work and finally solved my problem using `xfce4-xkb-plugin` on Lubuntu 18.04. First install the plugin ``` sudo apt-get install xfce4-xkb-plugin ``` then right-click on the task-bar and click **add/remove panel items** , it will open a **Panel Preferences** window Click the `+Add` button; it will open **Add plugin to panel** window select **Keyboard Layout Handler** and click `+Add` button Now back in the **Panel preferences** window select **Keyboard Layout Handler** and click the `Preferences` button This will open the **Keyboard Layout Handler** preferences window, whereyou need to do the following: Under **Advanced setxkbmap Options** uncheck *keep system layouts* Under **Keyboard Layouts > +Add** select the language you want to add Under **Change Layout Option** choose the keys you want to toggle between the languages Now try it يعمل جيدا معي في اللغة العربية
To add the functionality of multiple keyboards, first add (as root) to /etc/xdg/lxsession/LXDE/autostart your language choices, for example, for US and French, add @setxkbmap -layout "us,fr". See <http://lxlinux.com/#19> for additional information.
501,248
I was bored recently so I decided to download and install drivers from ASUS site. My motherboard is Asus P5K. After downloading the drivers, I messed up the installation somehow (don't remember the details) and now I don't have sound at all! I'm new to Ubuntu and I don't have a clue how driver setup works. Can you tell me how to bring back the old drivers or how to install this driver? And the first driver worked perfectly, but I was curious about the new driver so I messed up :( P.S, Ubuntu 14.4
2014/07/22
[ "https://askubuntu.com/questions/501248", "https://askubuntu.com", "https://askubuntu.com/users/231422/" ]
I think you should install the *ibus-m17n* package. ``` sudo apt-get install ibus-m17n ``` Then, next time you log in, you should see a bunch of new Sinhala options when running *ibus-setup*. Pick the one of your choice, and hopefully it makes a difference.
I recently had a really hard time making this work and finally solved my problem using `xfce4-xkb-plugin` on Lubuntu 18.04. First install the plugin ``` sudo apt-get install xfce4-xkb-plugin ``` then right-click on the task-bar and click **add/remove panel items** , it will open a **Panel Preferences** window Click the `+Add` button; it will open **Add plugin to panel** window select **Keyboard Layout Handler** and click `+Add` button Now back in the **Panel preferences** window select **Keyboard Layout Handler** and click the `Preferences` button This will open the **Keyboard Layout Handler** preferences window, whereyou need to do the following: Under **Advanced setxkbmap Options** uncheck *keep system layouts* Under **Keyboard Layouts > +Add** select the language you want to add Under **Change Layout Option** choose the keys you want to toggle between the languages Now try it يعمل جيدا معي في اللغة العربية
68,690,565
I have following *IProduct* and *ProductResolved* interfaces ``` export interface IProduct { id: number; productName: string; productCode: string; category: string; tags?: string[]; releaseDate: string; price: number; description: string; starRating: number; imageUrl: string; } export interface ProductResolved { product: IProduct; error?: any; } ``` I am trying to used it in *ProductResolver* as follows ``` import { Injectable } from "@angular/core"; import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from "@angular/router"; import { Observable, of } from "rxjs"; import { ProductResolved } from "./product"; import { ProductService } from "./product.service"; @Injectable({ providedIn: 'root' }) export class ProductResolver implements Resolve<ProductResolved> { constructor(private productService: ProductService) { } resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<ProductResolved> { const id = route.paramMap.get('id'); if (isNaN(+!id)) { const message = `Product id was not a number: ${id}`; console.error(message); return of({product : null,error:message}); //error here } return of(); //just for example i have return of() here I will change it later } } ``` while I return (in above code) ``` return of({product : null,error:message}); //error here ``` it gives an error as > > Type 'Observable<{ product: null; error: string; }>' is not assignable to type 'Observable'. > Type '{ product: null; error: string; }' is not assignable to type 'ProductResolved'. > Types of property 'product' are incompatible. > Type 'null' is not assignable to type 'IProduct'.ts(2322) > > > **Note :-** above code seems to be working on typescript version "~3.5.3" but it gives an error on typescript version "~4.3.2" **Question :-** 1. Is there any changes in latest typescript version("~4.3.2") related to above code? 2. What are best practices to handle above scenario according to new typescript standard?(if there are any changes related to that)?
2021/08/07
[ "https://Stackoverflow.com/questions/68690565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12415466/" ]
There are three options to resolve this issue: * modify property product as optional: More information you can find [here](https://exploringjs.com/tackling-ts/ch_typing-objects.html#optional-properties-interfaces) ``` export interface ProductResolved { product?: IProduct; error?: any; } ``` * modify product property which could be IProduct or null: ``` export interface ProductResolved { product: IProduct | null; error?: any; } ``` * modify product property as any: ``` export interface ProductResolved { product: any; error?: any; } ``` * using type assertions as: of({product: null, error: message} as IProduct) More information you can find [here](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions)
you can try with {} instead of null. If that didnt work, just give product?: IProduct
58,379,887
am trying to add a function to a script where a user is ask for code, which i have added. but having one issue of i want to unable when to ask the user code and when to to ask . so i need a php if else and it sql so when i unable to ask code for a user it will ask code and when i disable it wont ask code below is the one i have tried ``` if ((['yes'])) { // Yes <div id="cot_div" align="center"> <p>Please enter your <strong id="code_up">COT</strong> code to continue</p> <form id="form3" name="form3" method="POST" action="inter_suc.php"> <table border="0" id="trans" align="center" > <tr> <td align="center" style="padding:0px"><span id="sprytextfield1"> <input name="cot" type="text" id="cot" size="10" /> <span class="textfieldRequiredMsg"></span></span> <span id="sprytextfield2"> <input name="tax" type="text" id="tax" size="10" /> <span class="textfieldRequiredMsg"></span></span> <span id="sprytextfield3"> <input name="imf" type="text" id="imf" size="10" /> <span class="textfieldRequiredMsg"></span></span><br /> <span id="error"> wrong COT Code</span> </td> </tr> <tr> <td align="center" style="padding:0px"><input type="button" name="go" id="go" value="Go" /> <input type="button" name="go2" id="go2" value="GO" /> <input type="button" name="go3" id="go3" value="GO" /> </td> </tr> } else { // No <div id="cot_div" align="center"> <p>Please enter your <strong id="code_up">COT</strong> code to continue</p> <form id="form3" name="form3" method="POST" action="inter_suc.php"> <table border="0" id="trans" align="center" > <tr> <td align="center" style="padding:0px"><span id="sprytextfield1"> <input name="cot" type="hidden" id="cot" value="<?php echo $_POST['cot'];?>" /> <span class="textfieldRequiredMsg"></span></span> <span id="sprytextfield2"> <input name="tax" type="hidden" id="tax" value="<?php echo $_POST['tax'];?>" /> <span class="textfieldRequiredMsg"></span></span> <span id="sprytextfield3"> <input name="imf" type="hidden" id="imf" value="<?php echo $_POST['imf'];?>" /> <span class="textfieldRequiredMsg"></span></span><br /> <span id="error"> wrong COT Code</span> </td> </tr> <tr> <td align="center" style="padding:0px"><input type="button" name="go" id="go" value="Go" /> <input type="button" name="go2" id="go2" value="GO" /> <input type="button" name="go3" id="go3" value="GO" /> </td> </tr> } ```
2019/10/14
[ "https://Stackoverflow.com/questions/58379887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9043773/" ]
You could use [string formatting](https://docs.python.org/3/library/string.html#formatspec) to pad zeros to strings, e.g. to pad to the left: ``` >>> nums = ['10:30', '9:30', '11:0'] >>> ['{:0>2}:{:0>2}'.format(*n.split(':')) for n in nums] ['10:30', '09:30', '11:00'] ``` Alternatively, converting strings to numbers: ``` >>> ['{:02d}:{:02d}'.format(*map(int, n.split(':'))) for n in nums] ['10:30', '09:30', '11:00'] ```
Here's a way using string formatting: ``` def add_zeros(item: str) -> str: nums = item.split(":") formatted_item = ":".join(f"{int(num):02d}" for num in nums) return formatted_item ``` Then apply it to each item in your list: ``` nums = ["10:30", "9:30", "11:0"] [add_zeros(num) for num in nums] ```
58,379,887
am trying to add a function to a script where a user is ask for code, which i have added. but having one issue of i want to unable when to ask the user code and when to to ask . so i need a php if else and it sql so when i unable to ask code for a user it will ask code and when i disable it wont ask code below is the one i have tried ``` if ((['yes'])) { // Yes <div id="cot_div" align="center"> <p>Please enter your <strong id="code_up">COT</strong> code to continue</p> <form id="form3" name="form3" method="POST" action="inter_suc.php"> <table border="0" id="trans" align="center" > <tr> <td align="center" style="padding:0px"><span id="sprytextfield1"> <input name="cot" type="text" id="cot" size="10" /> <span class="textfieldRequiredMsg"></span></span> <span id="sprytextfield2"> <input name="tax" type="text" id="tax" size="10" /> <span class="textfieldRequiredMsg"></span></span> <span id="sprytextfield3"> <input name="imf" type="text" id="imf" size="10" /> <span class="textfieldRequiredMsg"></span></span><br /> <span id="error"> wrong COT Code</span> </td> </tr> <tr> <td align="center" style="padding:0px"><input type="button" name="go" id="go" value="Go" /> <input type="button" name="go2" id="go2" value="GO" /> <input type="button" name="go3" id="go3" value="GO" /> </td> </tr> } else { // No <div id="cot_div" align="center"> <p>Please enter your <strong id="code_up">COT</strong> code to continue</p> <form id="form3" name="form3" method="POST" action="inter_suc.php"> <table border="0" id="trans" align="center" > <tr> <td align="center" style="padding:0px"><span id="sprytextfield1"> <input name="cot" type="hidden" id="cot" value="<?php echo $_POST['cot'];?>" /> <span class="textfieldRequiredMsg"></span></span> <span id="sprytextfield2"> <input name="tax" type="hidden" id="tax" value="<?php echo $_POST['tax'];?>" /> <span class="textfieldRequiredMsg"></span></span> <span id="sprytextfield3"> <input name="imf" type="hidden" id="imf" value="<?php echo $_POST['imf'];?>" /> <span class="textfieldRequiredMsg"></span></span><br /> <span id="error"> wrong COT Code</span> </td> </tr> <tr> <td align="center" style="padding:0px"><input type="button" name="go" id="go" value="Go" /> <input type="button" name="go2" id="go2" value="GO" /> <input type="button" name="go3" id="go3" value="GO" /> </td> </tr> } ```
2019/10/14
[ "https://Stackoverflow.com/questions/58379887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9043773/" ]
You could use [string formatting](https://docs.python.org/3/library/string.html#formatspec) to pad zeros to strings, e.g. to pad to the left: ``` >>> nums = ['10:30', '9:30', '11:0'] >>> ['{:0>2}:{:0>2}'.format(*n.split(':')) for n in nums] ['10:30', '09:30', '11:00'] ``` Alternatively, converting strings to numbers: ``` >>> ['{:02d}:{:02d}'.format(*map(int, n.split(':'))) for n in nums] ['10:30', '09:30', '11:00'] ```
Here's a solution utilizing `zfill` & `ljust` ``` nums = ["10:30", "9:30", "11:0"] fixed = [] for t in nums: x, y = t.split(':') fixed.append(x.zfill(2) + ':' + y.ljust(2, '0')) print(fixed) ```
58,379,887
am trying to add a function to a script where a user is ask for code, which i have added. but having one issue of i want to unable when to ask the user code and when to to ask . so i need a php if else and it sql so when i unable to ask code for a user it will ask code and when i disable it wont ask code below is the one i have tried ``` if ((['yes'])) { // Yes <div id="cot_div" align="center"> <p>Please enter your <strong id="code_up">COT</strong> code to continue</p> <form id="form3" name="form3" method="POST" action="inter_suc.php"> <table border="0" id="trans" align="center" > <tr> <td align="center" style="padding:0px"><span id="sprytextfield1"> <input name="cot" type="text" id="cot" size="10" /> <span class="textfieldRequiredMsg"></span></span> <span id="sprytextfield2"> <input name="tax" type="text" id="tax" size="10" /> <span class="textfieldRequiredMsg"></span></span> <span id="sprytextfield3"> <input name="imf" type="text" id="imf" size="10" /> <span class="textfieldRequiredMsg"></span></span><br /> <span id="error"> wrong COT Code</span> </td> </tr> <tr> <td align="center" style="padding:0px"><input type="button" name="go" id="go" value="Go" /> <input type="button" name="go2" id="go2" value="GO" /> <input type="button" name="go3" id="go3" value="GO" /> </td> </tr> } else { // No <div id="cot_div" align="center"> <p>Please enter your <strong id="code_up">COT</strong> code to continue</p> <form id="form3" name="form3" method="POST" action="inter_suc.php"> <table border="0" id="trans" align="center" > <tr> <td align="center" style="padding:0px"><span id="sprytextfield1"> <input name="cot" type="hidden" id="cot" value="<?php echo $_POST['cot'];?>" /> <span class="textfieldRequiredMsg"></span></span> <span id="sprytextfield2"> <input name="tax" type="hidden" id="tax" value="<?php echo $_POST['tax'];?>" /> <span class="textfieldRequiredMsg"></span></span> <span id="sprytextfield3"> <input name="imf" type="hidden" id="imf" value="<?php echo $_POST['imf'];?>" /> <span class="textfieldRequiredMsg"></span></span><br /> <span id="error"> wrong COT Code</span> </td> </tr> <tr> <td align="center" style="padding:0px"><input type="button" name="go" id="go" value="Go" /> <input type="button" name="go2" id="go2" value="GO" /> <input type="button" name="go3" id="go3" value="GO" /> </td> </tr> } ```
2019/10/14
[ "https://Stackoverflow.com/questions/58379887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9043773/" ]
You could use [string formatting](https://docs.python.org/3/library/string.html#formatspec) to pad zeros to strings, e.g. to pad to the left: ``` >>> nums = ['10:30', '9:30', '11:0'] >>> ['{:0>2}:{:0>2}'.format(*n.split(':')) for n in nums] ['10:30', '09:30', '11:00'] ``` Alternatively, converting strings to numbers: ``` >>> ['{:02d}:{:02d}'.format(*map(int, n.split(':'))) for n in nums] ['10:30', '09:30', '11:00'] ```
You probably need to think this through a bit, because like mentioned in the commends 11:3 could be 11:03 or 11:30, but none the less, using actual datetime in python you can do the following: ``` from datetime import datetime nums = ["10:30", "9:30", "11:3"] x = [datetime.strptime(x, '%H:%M').strftime('%H:%M') for x in nums] >>> x ['10:30', '09:30', '11:03'] ```
58,379,887
am trying to add a function to a script where a user is ask for code, which i have added. but having one issue of i want to unable when to ask the user code and when to to ask . so i need a php if else and it sql so when i unable to ask code for a user it will ask code and when i disable it wont ask code below is the one i have tried ``` if ((['yes'])) { // Yes <div id="cot_div" align="center"> <p>Please enter your <strong id="code_up">COT</strong> code to continue</p> <form id="form3" name="form3" method="POST" action="inter_suc.php"> <table border="0" id="trans" align="center" > <tr> <td align="center" style="padding:0px"><span id="sprytextfield1"> <input name="cot" type="text" id="cot" size="10" /> <span class="textfieldRequiredMsg"></span></span> <span id="sprytextfield2"> <input name="tax" type="text" id="tax" size="10" /> <span class="textfieldRequiredMsg"></span></span> <span id="sprytextfield3"> <input name="imf" type="text" id="imf" size="10" /> <span class="textfieldRequiredMsg"></span></span><br /> <span id="error"> wrong COT Code</span> </td> </tr> <tr> <td align="center" style="padding:0px"><input type="button" name="go" id="go" value="Go" /> <input type="button" name="go2" id="go2" value="GO" /> <input type="button" name="go3" id="go3" value="GO" /> </td> </tr> } else { // No <div id="cot_div" align="center"> <p>Please enter your <strong id="code_up">COT</strong> code to continue</p> <form id="form3" name="form3" method="POST" action="inter_suc.php"> <table border="0" id="trans" align="center" > <tr> <td align="center" style="padding:0px"><span id="sprytextfield1"> <input name="cot" type="hidden" id="cot" value="<?php echo $_POST['cot'];?>" /> <span class="textfieldRequiredMsg"></span></span> <span id="sprytextfield2"> <input name="tax" type="hidden" id="tax" value="<?php echo $_POST['tax'];?>" /> <span class="textfieldRequiredMsg"></span></span> <span id="sprytextfield3"> <input name="imf" type="hidden" id="imf" value="<?php echo $_POST['imf'];?>" /> <span class="textfieldRequiredMsg"></span></span><br /> <span id="error"> wrong COT Code</span> </td> </tr> <tr> <td align="center" style="padding:0px"><input type="button" name="go" id="go" value="Go" /> <input type="button" name="go2" id="go2" value="GO" /> <input type="button" name="go3" id="go3" value="GO" /> </td> </tr> } ```
2019/10/14
[ "https://Stackoverflow.com/questions/58379887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9043773/" ]
You could use [string formatting](https://docs.python.org/3/library/string.html#formatspec) to pad zeros to strings, e.g. to pad to the left: ``` >>> nums = ['10:30', '9:30', '11:0'] >>> ['{:0>2}:{:0>2}'.format(*n.split(':')) for n in nums] ['10:30', '09:30', '11:00'] ``` Alternatively, converting strings to numbers: ``` >>> ['{:02d}:{:02d}'.format(*map(int, n.split(':'))) for n in nums] ['10:30', '09:30', '11:00'] ```
> > I need to add zero if number is single > > > Using list comprehension ``` nums = ["10:30", "9:30", "11:0"] nums_added = [ i + "0" if len(i.split(":")[1]) == 1 else i for i in nums] print(nums_added) ``` Output: ``` ['10:30', '9:30', '11:00'] ```
58,379,887
am trying to add a function to a script where a user is ask for code, which i have added. but having one issue of i want to unable when to ask the user code and when to to ask . so i need a php if else and it sql so when i unable to ask code for a user it will ask code and when i disable it wont ask code below is the one i have tried ``` if ((['yes'])) { // Yes <div id="cot_div" align="center"> <p>Please enter your <strong id="code_up">COT</strong> code to continue</p> <form id="form3" name="form3" method="POST" action="inter_suc.php"> <table border="0" id="trans" align="center" > <tr> <td align="center" style="padding:0px"><span id="sprytextfield1"> <input name="cot" type="text" id="cot" size="10" /> <span class="textfieldRequiredMsg"></span></span> <span id="sprytextfield2"> <input name="tax" type="text" id="tax" size="10" /> <span class="textfieldRequiredMsg"></span></span> <span id="sprytextfield3"> <input name="imf" type="text" id="imf" size="10" /> <span class="textfieldRequiredMsg"></span></span><br /> <span id="error"> wrong COT Code</span> </td> </tr> <tr> <td align="center" style="padding:0px"><input type="button" name="go" id="go" value="Go" /> <input type="button" name="go2" id="go2" value="GO" /> <input type="button" name="go3" id="go3" value="GO" /> </td> </tr> } else { // No <div id="cot_div" align="center"> <p>Please enter your <strong id="code_up">COT</strong> code to continue</p> <form id="form3" name="form3" method="POST" action="inter_suc.php"> <table border="0" id="trans" align="center" > <tr> <td align="center" style="padding:0px"><span id="sprytextfield1"> <input name="cot" type="hidden" id="cot" value="<?php echo $_POST['cot'];?>" /> <span class="textfieldRequiredMsg"></span></span> <span id="sprytextfield2"> <input name="tax" type="hidden" id="tax" value="<?php echo $_POST['tax'];?>" /> <span class="textfieldRequiredMsg"></span></span> <span id="sprytextfield3"> <input name="imf" type="hidden" id="imf" value="<?php echo $_POST['imf'];?>" /> <span class="textfieldRequiredMsg"></span></span><br /> <span id="error"> wrong COT Code</span> </td> </tr> <tr> <td align="center" style="padding:0px"><input type="button" name="go" id="go" value="Go" /> <input type="button" name="go2" id="go2" value="GO" /> <input type="button" name="go3" id="go3" value="GO" /> </td> </tr> } ```
2019/10/14
[ "https://Stackoverflow.com/questions/58379887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9043773/" ]
You could use [string formatting](https://docs.python.org/3/library/string.html#formatspec) to pad zeros to strings, e.g. to pad to the left: ``` >>> nums = ['10:30', '9:30', '11:0'] >>> ['{:0>2}:{:0>2}'.format(*n.split(':')) for n in nums] ['10:30', '09:30', '11:00'] ``` Alternatively, converting strings to numbers: ``` >>> ['{:02d}:{:02d}'.format(*map(int, n.split(':'))) for n in nums] ['10:30', '09:30', '11:00'] ```
A solution leaning the fact that these look **a lot** like dates could be ... Set up your list ``` nums = ["10:30", "9:30", "11:0"] ``` Iterate through the list converting, grabbing the time and lopping off (technical term) the last 3 characters ``` for item in nums: print(str(datetime.strptime(item, '%H:%M').time())[:-3]) ``` Output from print ``` 10:30 09:30 11:00 ```
52,012,145
I'm trying to code my own bot python selenium bot for instagram to experiment a little. I succeeded to log in and to search an hashtag in the search bar which lead me to the following web page: [![web page](https://i.stack.imgur.com/Ij9bq.png)](https://i.stack.imgur.com/Ij9bq.png) But I can not figure out how to like the photos in the feed, i tried to use a search with xpath and the following path: "//[@id="reactroot"]/section/main/article/div[1](https://i.stack.imgur.com/Ij9bq.png)/div/div/div[1](https://i.stack.imgur.com/Ij9bq.png)/div[1](https://i.stack.imgur.com/Ij9bq.png)/a/div" But it didn't work, does anybody have an idea?
2018/08/24
[ "https://Stackoverflow.com/questions/52012145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6053483/" ]
First of all, in your case it is recommended to use the official Instagram Api for Python ([documentation here on github](https://github.com/facebookarchive/python-instagram)). It would make your bot much simpler, more readable and most of all lighter and faster. So this is my first advice. If you really need using Selenium I also recommend downloading Selenium IDE add-on for Chrome [here](http://here) since it can save you much time, believe me. You can find a nice tutorial [on Youtube](https://www.youtube.com/watch?v=1-pHi9_OO6U). Now let's talk about possible solutions and them implementations. After some research I found that the xpath of the heart icon below left the post behaves like that: The xpath of the icon of the first post is: ``` xpath=//button/span ``` The xpath of the icon of the second post is: ``` xpath=//article[2]/div[2]/section/span/button/span ``` The xpath of the icon of the third post is: ``` xpath=//article[3]/div[2]/section/span/button/span ``` And so on. The first number near "article" corresponds to the number of the post. [![enter image description here](https://i.stack.imgur.com/FeSb4.png)](https://i.stack.imgur.com/FeSb4.png) So you can manage to get the number of the post you desire and then click it: ```py def get_heart_icon_xpath(post_num): """ Return heart icon xpath corresponding to n-post. """ if post_num == 1: return 'xpath=//button/span' else: return f'xpath=//article[{post_num}]/div[2]/section/span/button/span' try: # Get xpath of heart icon of the 19th post. my_xpath = get_heart_icon_xpath(19) heart_icon = driver.find_element_by_xpath(my_xpath) heart_icon.click() print("Task executed successfully") except Exception: print("An error occurred") ``` Hope it helps. Let me know if find other issues.
i'm trying to do the same) Here is a working method. Firstly, we find a class of posts(v1Nh3), then we catch link attribute(href). ``` posts = bot.find_elements_by_class_name('v1Nh3') links = [elem.find_element_by_css_selector('a').get_attribute('href') for elem in posts] ```
52,012,145
I'm trying to code my own bot python selenium bot for instagram to experiment a little. I succeeded to log in and to search an hashtag in the search bar which lead me to the following web page: [![web page](https://i.stack.imgur.com/Ij9bq.png)](https://i.stack.imgur.com/Ij9bq.png) But I can not figure out how to like the photos in the feed, i tried to use a search with xpath and the following path: "//[@id="reactroot"]/section/main/article/div[1](https://i.stack.imgur.com/Ij9bq.png)/div/div/div[1](https://i.stack.imgur.com/Ij9bq.png)/div[1](https://i.stack.imgur.com/Ij9bq.png)/a/div" But it didn't work, does anybody have an idea?
2018/08/24
[ "https://Stackoverflow.com/questions/52012145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6053483/" ]
First of all, in your case it is recommended to use the official Instagram Api for Python ([documentation here on github](https://github.com/facebookarchive/python-instagram)). It would make your bot much simpler, more readable and most of all lighter and faster. So this is my first advice. If you really need using Selenium I also recommend downloading Selenium IDE add-on for Chrome [here](http://here) since it can save you much time, believe me. You can find a nice tutorial [on Youtube](https://www.youtube.com/watch?v=1-pHi9_OO6U). Now let's talk about possible solutions and them implementations. After some research I found that the xpath of the heart icon below left the post behaves like that: The xpath of the icon of the first post is: ``` xpath=//button/span ``` The xpath of the icon of the second post is: ``` xpath=//article[2]/div[2]/section/span/button/span ``` The xpath of the icon of the third post is: ``` xpath=//article[3]/div[2]/section/span/button/span ``` And so on. The first number near "article" corresponds to the number of the post. [![enter image description here](https://i.stack.imgur.com/FeSb4.png)](https://i.stack.imgur.com/FeSb4.png) So you can manage to get the number of the post you desire and then click it: ```py def get_heart_icon_xpath(post_num): """ Return heart icon xpath corresponding to n-post. """ if post_num == 1: return 'xpath=//button/span' else: return f'xpath=//article[{post_num}]/div[2]/section/span/button/span' try: # Get xpath of heart icon of the 19th post. my_xpath = get_heart_icon_xpath(19) heart_icon = driver.find_element_by_xpath(my_xpath) heart_icon.click() print("Task executed successfully") except Exception: print("An error occurred") ``` Hope it helps. Let me know if find other issues.
I implemented a function that likes all the picture from an Instagram page. It could be used on the "Explore" page or simply on an user's profil page. Here's how I did it. First, to navigate to a profil page from Instagram's main page, I create a xPath for the "SearchBox" and a xPath to the element in the dropdown menu results corresponding to the index. ``` def search(self, keyword, index): """ Method that searches for a username and navigates to nth profile in the results where n corresponds to the index""" search_input = "//input[@placeholder=\"Search\"]" navigate_to = "(//div[@class=\"fuqBx\"]//descendant::a)[" + str(index) + "]" try: self.driver.find_element_by_xpath(search_input).send_keys(keyword) self.driver.find_element_by_xpath(navigate_to).click() print("Successfully searched for: " + keyword) except NoSuchElementException: print("Search failed") ``` Then I open the first picture: ``` def open_first_picture(self): """ Method that opens the first picture on an Instagram profile page """ try: self.driver.find_element_by_xpath("(//div[@class=\"eLAPa\"]//parent::a)[1]").click() except NoSuchElementException: print("Profile has no picture") ``` Like each one of them: ``` def like_all_pictures(self): """ Method that likes every picture on an Instagram page.""" # Open the first picture self.open_first_picture() # Create has_picture variable to keep track has_picture = True while has_picture: self.like() # Updating value of has_picture has_picture = self.has_next_picture() # Closing the picture pop up after having liked the last picture try: self.driver.find_element_by_xpath("//button[@class=\"ckWGn\"]").click() print("Liked all pictures of " + self.driver.current_url) except: # If driver fails to find the close button, it will navigate back to the main page print("Couldn't close the picture, navigating back to Instagram's main page.") self.driver.get("https://www.instagram.com/") def like(self): """Method that finds all the like buttons and clicks on each one of them, if they are not already clicked (liked).""" unliked = self.driver.find_elements_by_xpath("//span[@class=\"glyphsSpriteHeart__outline__24__grey_9 u-__7\" and @aria-label=\"Like\"]//parent::button") liked = self.driver.find_elements_by_xpath("//span[@class=\"glyphsSpriteHeart__filled__24__red_5 u-__7\" and @aria-label=\"Unlike\"]") # If there are like buttons if liked: print("Picture has already been liked") elif unliked: try: for button in unliked: button.click() except StaleElementReferenceException: # We face this stale element reference exception when the element we are interacting is destroyed and then recreated again. When this happens the reference of the element in the DOM becomes stale. Hence we are not able to get the reference to the element. print("Failed to like picture: Element is no longer attached to the DOM") ``` This method checks if picture has a "Next" button to the next picture: ``` def has_next_picture(self): """ Helper method that finds if pictures has button \"Next\" to navigate to the next picture. If it does, it will navigate to the next picture.""" next_button = "//a[text()=\"Next\"]" try: self.driver.find_element_by_xpath(next_button).click() return True except NoSuchElementException: print("User has no more pictures") return False ``` If you'd like to learn more feel free to have a look at my Github repo: <https://github.com/mlej8/InstagramBot>
64,403,863
I am trying to model a bag of words. I am having some trouble incrementing the counter inside my dictionary when the word is found in my data (type series): ``` def build_voc(self, data): for document in data: for word in document.split(' '): if word in self.voc: self.voc_ctr[word] = self.voc_ctr[word] + 1 else: self.voc.append(word) self.voc_ctr = 1 ``` I tried indexing it as well this way just to test where the error was: ``` self.voc_ctr[word][0] = self.voc_ctr[word][0] + 1 ``` But it still gives me the same error at that line: > > TypeError: 'int' object is not subscriptable > > > Knowing that this is a function in the same class, where self.voc and self.voc\_ctr are defined: ``` class BV: def __init__(self): self.voc = [] self.voc_ctr = {} def build_voc(self, data): for document in data: for word in document.split(' '): if word in self.voc: self.voc_ctr[word] = self.voc_ctr[word] + 1 else: self.voc.append(word) self.voc_ctr = 1 ``` The error seems to say self.voc\_ctr is an int object, but I defined it as a list so I don't know where I went wrong.
2020/10/17
[ "https://Stackoverflow.com/questions/64403863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5587209/" ]
I presume you realize you're supposed to compare Strings with `equals` and not `==`. However, look at the identity hashCodes for the strings. `abcdef` and `b` have the same one. That is why they are equal using `==` They are referencing the same object from the internal cache. ``` String abcdef = "abcdef"; final String def = "def"; String a = "abc"; a += def; String b = "abc" + def; String c = "abc"; c = c + def; System.out.println("a = " + System.identityHashCode(a) + " abcdef = " + System.identityHashCode(abcdef)); System.out.println("b = " + System.identityHashCode(b) + " abcdef = " + System.identityHashCode(abcdef)); System.out.println("c = " + System.identityHashCode(c) + " abcdef = " + System.identityHashCode(abcdef)); if (abcdef == a) { System.out.println("A"); } if (abcdef == b) { System.out.println("B"); } if (abcdef == c) { System.out.println("C"); } ``` Prints ``` a = 925858445 abcdef = 798154996 b = 798154996 abcdef = 798154996 c = 681842940 abcdef = 798154996 B ```
This is happening because `b` is equal to `"abc" + def`, and `def` is equal to `"def"`. So, essentially, you are comparing `"abcdef"` with `"abcdef"` by using `abcdef == b`. So, in conclusion, it will *not* print nothing, because `"abcdef" == "abcdef"` *always* evaluates to `true`.
64,403,863
I am trying to model a bag of words. I am having some trouble incrementing the counter inside my dictionary when the word is found in my data (type series): ``` def build_voc(self, data): for document in data: for word in document.split(' '): if word in self.voc: self.voc_ctr[word] = self.voc_ctr[word] + 1 else: self.voc.append(word) self.voc_ctr = 1 ``` I tried indexing it as well this way just to test where the error was: ``` self.voc_ctr[word][0] = self.voc_ctr[word][0] + 1 ``` But it still gives me the same error at that line: > > TypeError: 'int' object is not subscriptable > > > Knowing that this is a function in the same class, where self.voc and self.voc\_ctr are defined: ``` class BV: def __init__(self): self.voc = [] self.voc_ctr = {} def build_voc(self, data): for document in data: for word in document.split(' '): if word in self.voc: self.voc_ctr[word] = self.voc_ctr[word] + 1 else: self.voc.append(word) self.voc_ctr = 1 ``` The error seems to say self.voc\_ctr is an int object, but I defined it as a list so I don't know where I went wrong.
2020/10/17
[ "https://Stackoverflow.com/questions/64403863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5587209/" ]
In Java the operator "==" checks if the two operands reference to the same object. Do not use "==" with any objects including Strings. And note Java Strings are immutable. That mean all the operations with them don't modify them but create new objects.
This is happening because `b` is equal to `"abc" + def`, and `def` is equal to `"def"`. So, essentially, you are comparing `"abcdef"` with `"abcdef"` by using `abcdef == b`. So, in conclusion, it will *not* print nothing, because `"abcdef" == "abcdef"` *always* evaluates to `true`.
64,403,863
I am trying to model a bag of words. I am having some trouble incrementing the counter inside my dictionary when the word is found in my data (type series): ``` def build_voc(self, data): for document in data: for word in document.split(' '): if word in self.voc: self.voc_ctr[word] = self.voc_ctr[word] + 1 else: self.voc.append(word) self.voc_ctr = 1 ``` I tried indexing it as well this way just to test where the error was: ``` self.voc_ctr[word][0] = self.voc_ctr[word][0] + 1 ``` But it still gives me the same error at that line: > > TypeError: 'int' object is not subscriptable > > > Knowing that this is a function in the same class, where self.voc and self.voc\_ctr are defined: ``` class BV: def __init__(self): self.voc = [] self.voc_ctr = {} def build_voc(self, data): for document in data: for word in document.split(' '): if word in self.voc: self.voc_ctr[word] = self.voc_ctr[word] + 1 else: self.voc.append(word) self.voc_ctr = 1 ``` The error seems to say self.voc\_ctr is an int object, but I defined it as a list so I don't know where I went wrong.
2020/10/17
[ "https://Stackoverflow.com/questions/64403863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5587209/" ]
I presume you realize you're supposed to compare Strings with `equals` and not `==`. However, look at the identity hashCodes for the strings. `abcdef` and `b` have the same one. That is why they are equal using `==` They are referencing the same object from the internal cache. ``` String abcdef = "abcdef"; final String def = "def"; String a = "abc"; a += def; String b = "abc" + def; String c = "abc"; c = c + def; System.out.println("a = " + System.identityHashCode(a) + " abcdef = " + System.identityHashCode(abcdef)); System.out.println("b = " + System.identityHashCode(b) + " abcdef = " + System.identityHashCode(abcdef)); System.out.println("c = " + System.identityHashCode(c) + " abcdef = " + System.identityHashCode(abcdef)); if (abcdef == a) { System.out.println("A"); } if (abcdef == b) { System.out.println("B"); } if (abcdef == c) { System.out.println("C"); } ``` Prints ``` a = 925858445 abcdef = 798154996 b = 798154996 abcdef = 798154996 c = 681842940 abcdef = 798154996 B ```
In Java the operator "==" checks if the two operands reference to the same object. Do not use "==" with any objects including Strings. And note Java Strings are immutable. That mean all the operations with them don't modify them but create new objects.
94,499
I am an international student in a interdisciplinary PhD in the social sciences. 1. My supervisor has about 60 students and does not do any advising beyond a few personal favorites. 2. My second supervisor considers me a student of the first, resents the fact that he is the expert on the subject, and as a result won't read my thesis either. This has gone on for seven years and now I must submit. I speak four European languages and my thesis is in an area which is very relevant. Right now I can t see any future for myself as there are no jobs back home. 1.What do I do about my supervisors as the PhD is graded here? 2.Can I apply for post docs/tenure track (community college is more than fine) in North America with a PhD from Germany, or do they prefer N.American PhDs? How do I go about it? I have publications. I'd be grateful for any advice/career suggestions etc. I don't mind leaving academia but I cannot return home as there are no jobs there.
2017/08/13
[ "https://academia.stackexchange.com/questions/94499", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/78397/" ]
It is not uncommon that a German professor does not give advise to their PhD students. Neither is it uncommon that the 2nd referee does not want to read your thesis. In Germany, whether your dissertation is good enough or not is mainly decided by the first advisor. If they say it's ok, then it's ok. Your advisor theirself is the chairman of the exam committee, the other members would not say "no" to him. That is, there is no need to worry about your situation. If I were you, I would just write up my dissertation, give it to my advisor, and ask them for advice. Then, from what I know, the advisor would find some time to read it, and tell you something to improve (they have to pretend as if they understood your thesis). Then you could do the improvements, mail the thesis to the 2nd referee. Again this guy would also tell you something to improve, you do it, and that's it.
Did your first supervisor ever say to you that he/she won't read your thesis? Why don't you try to finish writing the first draft of your thesis first and let your first supervisor to read and comment? My supervisor also is a type that doesn't do much supervising and only let me do whatever I want. But she took time to read my thesis and I finally managed to submit mine. I am not sure whether it is possible for you to apply for postdoc without PhD degree. Correct me if I am wrong. The fact that you already have publications means you will have a good time writing your thesis.
94,499
I am an international student in a interdisciplinary PhD in the social sciences. 1. My supervisor has about 60 students and does not do any advising beyond a few personal favorites. 2. My second supervisor considers me a student of the first, resents the fact that he is the expert on the subject, and as a result won't read my thesis either. This has gone on for seven years and now I must submit. I speak four European languages and my thesis is in an area which is very relevant. Right now I can t see any future for myself as there are no jobs back home. 1.What do I do about my supervisors as the PhD is graded here? 2.Can I apply for post docs/tenure track (community college is more than fine) in North America with a PhD from Germany, or do they prefer N.American PhDs? How do I go about it? I have publications. I'd be grateful for any advice/career suggestions etc. I don't mind leaving academia but I cannot return home as there are no jobs there.
2017/08/13
[ "https://academia.stackexchange.com/questions/94499", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/78397/" ]
It is not uncommon that a German professor does not give advise to their PhD students. Neither is it uncommon that the 2nd referee does not want to read your thesis. In Germany, whether your dissertation is good enough or not is mainly decided by the first advisor. If they say it's ok, then it's ok. Your advisor theirself is the chairman of the exam committee, the other members would not say "no" to him. That is, there is no need to worry about your situation. If I were you, I would just write up my dissertation, give it to my advisor, and ask them for advice. Then, from what I know, the advisor would find some time to read it, and tell you something to improve (they have to pretend as if they understood your thesis). Then you could do the improvements, mail the thesis to the 2nd referee. Again this guy would also tell you something to improve, you do it, and that's it.
I have had problems that are similar to yours. I would say that you need to finish your PhD. The strongest thing you can have in your CV besides your publications is your degree. Apply for Postdoc in other countries within the EU. There are many opportunities and you may get lucky. America is having difficulties with funding for Science and Humanities, but of course, you can still try there. The situation with your advisors is terrible, but you can always ask for other people to read your dissertation, like your senior colleagues and professors. Ask for their opinion and suggestion. Make your dissertation as well written and coherent as you possibly can in this situation. It can indeed bring you some job opportunity.
2,573,982
Given $f(x, y) = x$ and $X$ is defined as $2rx \leq x^2 + y^2 \leq R^2$ and $0 < 2r < R$. Calculate $\int \int\_X f(x, y)dxdy$. So $x^2 + y^2 \leq R^2$ is an area inside a circle with radius $R$. $2rx \leq x^2 + y^2$ and $0 < 2r < R$ give us a second circle, which area depends on value of $x$ with center on somewhere on $(0, R)$, the leftest coordinate on $(0, 0)$ and the rightest on $(x\_1, 0)$, where $x\_1 < R$. So the area of the integral is area of a big circle minus the area of a small circle. Now let's denote the area of a big circle as $X\_1: (x, y)| - R \leq x \leq R; -\sqrt{x} \leq y \leq \sqrt{x}$. Small circle $X\_2: (x, y) | 0 \leq x \leq 2r; -\sqrt{x(x - r)} \leq y \leq \sqrt{x(x - 2r)}$ I'm not quite sure about the bounds, especially of the small circle, so it may be some mistake here. Unfortunately I'm unable to find it. Then $\int \int\_{X\_1} x = \int \limits\_{-R}^{R} dx \int \limits\_{-\sqrt{x}}^{\sqrt{x}} x dy = \int \limits^R\_{-R}xdx\int \limits\_{-\sqrt{x}}^{\sqrt{x}}dy = 2 \int \limits\_{-R}^{R} x^{\frac{3}{2}} dx = \frac{4}{5}\left(R^{\frac{5}{2}} - \left(-R \right)^{\frac{5}{2}}\right)$. And now I'm stuck on calculate the area of a small circle. Also can somebody check the bounds which I found for $X\_1$ and $X\_2$, since it might be the reason I'm unable evaluate second integral.
2017/12/20
[ "https://math.stackexchange.com/questions/2573982", "https://math.stackexchange.com", "https://math.stackexchange.com/users/376675/" ]
For the big circle: $x^2 + y^2 \leq R^2$. Let $x=\rho\cos\phi$ and $y=\rho\sin\phi$ $$I\_1=\int \int\_{X\_1} x dx dy =\int \limits\_{0}^{2\pi}\int \limits\_{0}^{R} \rho^2\cos\phi d\rho d\phi = \int \limits\_{0}^{R} \rho^2 d\rho\int \limits\_{0}^{2\pi}\cos\phi d\phi =0$$ For the small circle: $2rx \geq x^2 + y^2 \rightarrow r^2 \geq (x-r)^2 + y^2$. Let $x=\rho\cos\phi+r$ and $y=\rho\sin\phi$ $$I\_2=\int \int\_{X\_2} x dx dy =\int \limits\_{0}^{2\pi}\int \limits\_{0}^{r} \rho(\rho\cos\phi+r) d\rho d\phi =\int \limits\_{0}^{r} \rho^2 d\rho\int \limits\_{0}^{2\pi}\cos\phi d\phi+ r\int \limits\_{0}^{r} \rho d\rho\int \limits\_{0}^{2\pi}1 d\phi =$$ $$=0+\frac{r^3}{2}2\pi=r^3\pi$$ Finally: $$I=I\_1-I\_2=-r^3\pi$$
Well, firstly, I'd like you to realize that it would be best to deal with this in terms of polar coordinates, as we are dealing with circles. Now let's analyse this. $2rx\leq x^2+y^2\leq R^2$, $0\leq 2r\leq R$, where $R$ is the radius of the circle. Now remember that in polar coordinates, $x=R\cos\theta,y=R\sin\theta$, therefore we have that $x^2+y^2=R^2$ $2rx\leq R^2\leq R^2$, which simplifies to $2rx\leq R^2$, or $2r(R\cos\theta)\leq R^2$, which means that $2r\cos\theta\leq R$. Now we also have that $0\lt 2r\lt R$. Since these circles are not shifted vertically, the range for $\theta$ is $0\leq\theta\leq 2\pi$ What about the radius $R$? Well the radius is clearly between $0\leq R\leq 2r\cos\theta$ Now our original function $f(x,y)=x$ can be written as $R\cos\theta$. So the integral is of the form: $$\int\int\text{ f(x,y) R dr d$\theta$}=\int^{2\pi}\_{0}\int^{2r\cos\theta}\_{0}(R\cos\theta)\text{ dR d$\theta$}$$ Your integral will depend on $r$
58,659,448
I am working on many large gz file like the below examples (only the first 5 rows are showed here). ``` gene_id variant_id tss_distance ma_samples ma_count maf pval_nominal slope slope_se ENSG00000223972.4 1_13417_C_CGAGA_b37 1548 50 50 0.0766871 0.735446 -0.0468165 0.138428 ENSG00000223972.4 1_17559_G_C_b37 5690 7 7 0.00964187 0.39765 -0.287573 0.339508 ENSG00000223972.4 1_54421_A_G_b37 42552 28 28 0.039548 0.680357 0.0741142 0.179725 ENSG00000223972.4 1_54490_G_A_b37 42621 112 120 0.176471 0.00824733 0.247533 0.093081 ``` Below is the output that I want. Here, I split the second column by "\_", and selected the rows based on the second and third columns (after splitting) ($2==1 and $3>20000). And I save it as a txt. The command below works perfectly. ``` zcat InputData.txt.gz | awk -F "_" '$1=$1' | awk '{if ($2==1 && $3>20000) {print}}' > OutputData.txt ENSG00000223972.4 1 54421 A G b37 42552 28 28 0.039548 0.680357 0.0741142 0.179725 ENSG00000223972.4 1 54490 G A b37 42621 112 120 0.176471 0.00824733 0.247533 0.093081 ``` But I want to use GNU parallel to speed up the process since I have many large gz files to work with. However, there seems to be some conflict between GNU parallel and awk, probably in terms of the quotation? I tried defining the awk option separately as below, but it did not give me anything in the output file. In the below command, I am only running the parallel on one input file. But I want to run in on multiple input files, and save multiple output files each corresponding to one input file. For example, InputData\_1.txt.gz to OutputData\_1.txt InputData\_2.txt.gz to OutputData\_2.txt ``` awk1='{ -F "_" "$1=$1" }' awk2='{if ($2==1 && $3>20000) {print}}' parallel "zcat {} | awk '$awk1' |awk '$awk2' > OutputData.txt" ::: InputData.txt.gz ``` Does anyone have any suggestion on this task? Thank you very much. --- According to the suggestion from @karakfa, this is one solution ``` chr=1 RegionStart=10000 RegionEnd=50000 zcat InputData.txt.gz | awk -v chr=$chr -v start=$RegionStart -v end=$RegionEnd '{split($2,NewDF,"_")} NewDF[1]==chr && NewDF[2]>start && NewDF[2]<end {gsub("_"," ",$2) ; print > ("OutputData.txt")}' #This also works using parallel awkbody='{split($2,NewDF,"_")} NewDF[1]==chr && NewDF[2]>start && NewDF[2]<end {gsub("_"," ",$2) ; print > ("{}_OutputData.txt")}' parallel "zcat {} | awk -v chr=$chr -v start=$RegionStart -v end=$RegionEnd '$awkbody' " ::: InputData_*.txt.gz ``` The output file name for the input file `InputData_1.txt.gz` will be `InputData_1.txt.gz_OutputData.txt`
2019/11/01
[ "https://Stackoverflow.com/questions/58659448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4196742/" ]
one way of doing this is with `split` ``` $ awk '{split($2,f2,"_")} f2[1]==1 && f2[2]>20000 {gsub("_"," ",$2); print > (FILENAME".output")}' file ``` however, if you provide data though stdin, `awk` won't capture a filename to write to. You need to pass it to the script as a variable perhaps...
The simple solution is to combine the filter into single `awk` script, than and only than parallel can work. Here is a sample solution that scan the whole `input.txt` only once (twice the performance): ``` awk 'BEGIN{FS="[ ]*[_]?"}$2==1 && $7 > 20000 {print}' input.txt ``` ### Explanation: `BEGIN{FS="[ ]*[_]?"}` Make the field separator multiple " " **or** "\_" `$2==1 && $7 > 20000 {print}` Print only lines with 2nd field == 1 and 7nt field > 2000 Sample debug script: ``` BEGIN{FS="[ ]*[_]?"} { for(i = 1; i <= NF; i++) printf("$%d=%s%s",i, $i, OFS); print ""; } $2==1 && $7 > 20000 {print} ``` Produce: ``` $1=gene $2=id $3=variant $4=id $5=tss $6=distance $7=ma $8=samples $9=ma $10=count $11=maf $12=pval $13=nominal $14=slope $15=slope $16=se $1=ENSG00000223972.4 $2=1 $3=13417 $4=C $5=CGAGA $6=b37 $7=1548 $8=50 $9=50 $10=0.0766871 $11=0.735446 $12=-0.0468165 $13=0.138428 $1=ENSG00000223972.4 $2=1 $3=17559 $4=G $5=C $6=b37 $7=5690 $8=7 $9=7 $10=0.00964187 $11=0.39765 $12=-0.287573 $13=0.339508 $1=ENSG00000223972.4 $2=1 $3=54421 $4=A $5=G $6=b37 $7=42552 $8=28 $9=28 $10=0.039548 $11=0.680357 $12=0.0741142 $13=0.179725 ENSG00000223972.4 1_54421_A_G_b37 42552 28 28 0.039548 0.680357 0.0741142 0.179725 $1=ENSG00000223972.4 $2=1 $3=54490 $4=G $5=A $6=b37 $7=42621 $8=112 $9=120 $10=0.176471 $11=0.00824733 $12=0.247533 $13=0.093081 ENSG00000223972.4 1_54490_G_A_b37 42621 112 120 0.176471 0.00824733 0.247533 0.093081 ```
58,659,448
I am working on many large gz file like the below examples (only the first 5 rows are showed here). ``` gene_id variant_id tss_distance ma_samples ma_count maf pval_nominal slope slope_se ENSG00000223972.4 1_13417_C_CGAGA_b37 1548 50 50 0.0766871 0.735446 -0.0468165 0.138428 ENSG00000223972.4 1_17559_G_C_b37 5690 7 7 0.00964187 0.39765 -0.287573 0.339508 ENSG00000223972.4 1_54421_A_G_b37 42552 28 28 0.039548 0.680357 0.0741142 0.179725 ENSG00000223972.4 1_54490_G_A_b37 42621 112 120 0.176471 0.00824733 0.247533 0.093081 ``` Below is the output that I want. Here, I split the second column by "\_", and selected the rows based on the second and third columns (after splitting) ($2==1 and $3>20000). And I save it as a txt. The command below works perfectly. ``` zcat InputData.txt.gz | awk -F "_" '$1=$1' | awk '{if ($2==1 && $3>20000) {print}}' > OutputData.txt ENSG00000223972.4 1 54421 A G b37 42552 28 28 0.039548 0.680357 0.0741142 0.179725 ENSG00000223972.4 1 54490 G A b37 42621 112 120 0.176471 0.00824733 0.247533 0.093081 ``` But I want to use GNU parallel to speed up the process since I have many large gz files to work with. However, there seems to be some conflict between GNU parallel and awk, probably in terms of the quotation? I tried defining the awk option separately as below, but it did not give me anything in the output file. In the below command, I am only running the parallel on one input file. But I want to run in on multiple input files, and save multiple output files each corresponding to one input file. For example, InputData\_1.txt.gz to OutputData\_1.txt InputData\_2.txt.gz to OutputData\_2.txt ``` awk1='{ -F "_" "$1=$1" }' awk2='{if ($2==1 && $3>20000) {print}}' parallel "zcat {} | awk '$awk1' |awk '$awk2' > OutputData.txt" ::: InputData.txt.gz ``` Does anyone have any suggestion on this task? Thank you very much. --- According to the suggestion from @karakfa, this is one solution ``` chr=1 RegionStart=10000 RegionEnd=50000 zcat InputData.txt.gz | awk -v chr=$chr -v start=$RegionStart -v end=$RegionEnd '{split($2,NewDF,"_")} NewDF[1]==chr && NewDF[2]>start && NewDF[2]<end {gsub("_"," ",$2) ; print > ("OutputData.txt")}' #This also works using parallel awkbody='{split($2,NewDF,"_")} NewDF[1]==chr && NewDF[2]>start && NewDF[2]<end {gsub("_"," ",$2) ; print > ("{}_OutputData.txt")}' parallel "zcat {} | awk -v chr=$chr -v start=$RegionStart -v end=$RegionEnd '$awkbody' " ::: InputData_*.txt.gz ``` The output file name for the input file `InputData_1.txt.gz` will be `InputData_1.txt.gz_OutputData.txt`
2019/11/01
[ "https://Stackoverflow.com/questions/58659448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4196742/" ]
<https://www.gnu.org/software/parallel/man.html#QUOTING> concludes: > > **Conclusion:** To avoid dealing with the quoting problems it may be easier just to write a small script or a function (remember to export -f the function) and have GNU parallel call that. > > > So: ``` doit() { zcat "$1" | awk -F "_" '$1=$1' | awk '{if ($2==1 && $3>20000) {print}}' } export -f doit parallel 'doit {} > {=s/In/Out/; s/.gz//=}' ::: InputData*.txt.gz ```
one way of doing this is with `split` ``` $ awk '{split($2,f2,"_")} f2[1]==1 && f2[2]>20000 {gsub("_"," ",$2); print > (FILENAME".output")}' file ``` however, if you provide data though stdin, `awk` won't capture a filename to write to. You need to pass it to the script as a variable perhaps...
58,659,448
I am working on many large gz file like the below examples (only the first 5 rows are showed here). ``` gene_id variant_id tss_distance ma_samples ma_count maf pval_nominal slope slope_se ENSG00000223972.4 1_13417_C_CGAGA_b37 1548 50 50 0.0766871 0.735446 -0.0468165 0.138428 ENSG00000223972.4 1_17559_G_C_b37 5690 7 7 0.00964187 0.39765 -0.287573 0.339508 ENSG00000223972.4 1_54421_A_G_b37 42552 28 28 0.039548 0.680357 0.0741142 0.179725 ENSG00000223972.4 1_54490_G_A_b37 42621 112 120 0.176471 0.00824733 0.247533 0.093081 ``` Below is the output that I want. Here, I split the second column by "\_", and selected the rows based on the second and third columns (after splitting) ($2==1 and $3>20000). And I save it as a txt. The command below works perfectly. ``` zcat InputData.txt.gz | awk -F "_" '$1=$1' | awk '{if ($2==1 && $3>20000) {print}}' > OutputData.txt ENSG00000223972.4 1 54421 A G b37 42552 28 28 0.039548 0.680357 0.0741142 0.179725 ENSG00000223972.4 1 54490 G A b37 42621 112 120 0.176471 0.00824733 0.247533 0.093081 ``` But I want to use GNU parallel to speed up the process since I have many large gz files to work with. However, there seems to be some conflict between GNU parallel and awk, probably in terms of the quotation? I tried defining the awk option separately as below, but it did not give me anything in the output file. In the below command, I am only running the parallel on one input file. But I want to run in on multiple input files, and save multiple output files each corresponding to one input file. For example, InputData\_1.txt.gz to OutputData\_1.txt InputData\_2.txt.gz to OutputData\_2.txt ``` awk1='{ -F "_" "$1=$1" }' awk2='{if ($2==1 && $3>20000) {print}}' parallel "zcat {} | awk '$awk1' |awk '$awk2' > OutputData.txt" ::: InputData.txt.gz ``` Does anyone have any suggestion on this task? Thank you very much. --- According to the suggestion from @karakfa, this is one solution ``` chr=1 RegionStart=10000 RegionEnd=50000 zcat InputData.txt.gz | awk -v chr=$chr -v start=$RegionStart -v end=$RegionEnd '{split($2,NewDF,"_")} NewDF[1]==chr && NewDF[2]>start && NewDF[2]<end {gsub("_"," ",$2) ; print > ("OutputData.txt")}' #This also works using parallel awkbody='{split($2,NewDF,"_")} NewDF[1]==chr && NewDF[2]>start && NewDF[2]<end {gsub("_"," ",$2) ; print > ("{}_OutputData.txt")}' parallel "zcat {} | awk -v chr=$chr -v start=$RegionStart -v end=$RegionEnd '$awkbody' " ::: InputData_*.txt.gz ``` The output file name for the input file `InputData_1.txt.gz` will be `InputData_1.txt.gz_OutputData.txt`
2019/11/01
[ "https://Stackoverflow.com/questions/58659448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4196742/" ]
<https://www.gnu.org/software/parallel/man.html#QUOTING> concludes: > > **Conclusion:** To avoid dealing with the quoting problems it may be easier just to write a small script or a function (remember to export -f the function) and have GNU parallel call that. > > > So: ``` doit() { zcat "$1" | awk -F "_" '$1=$1' | awk '{if ($2==1 && $3>20000) {print}}' } export -f doit parallel 'doit {} > {=s/In/Out/; s/.gz//=}' ::: InputData*.txt.gz ```
The simple solution is to combine the filter into single `awk` script, than and only than parallel can work. Here is a sample solution that scan the whole `input.txt` only once (twice the performance): ``` awk 'BEGIN{FS="[ ]*[_]?"}$2==1 && $7 > 20000 {print}' input.txt ``` ### Explanation: `BEGIN{FS="[ ]*[_]?"}` Make the field separator multiple " " **or** "\_" `$2==1 && $7 > 20000 {print}` Print only lines with 2nd field == 1 and 7nt field > 2000 Sample debug script: ``` BEGIN{FS="[ ]*[_]?"} { for(i = 1; i <= NF; i++) printf("$%d=%s%s",i, $i, OFS); print ""; } $2==1 && $7 > 20000 {print} ``` Produce: ``` $1=gene $2=id $3=variant $4=id $5=tss $6=distance $7=ma $8=samples $9=ma $10=count $11=maf $12=pval $13=nominal $14=slope $15=slope $16=se $1=ENSG00000223972.4 $2=1 $3=13417 $4=C $5=CGAGA $6=b37 $7=1548 $8=50 $9=50 $10=0.0766871 $11=0.735446 $12=-0.0468165 $13=0.138428 $1=ENSG00000223972.4 $2=1 $3=17559 $4=G $5=C $6=b37 $7=5690 $8=7 $9=7 $10=0.00964187 $11=0.39765 $12=-0.287573 $13=0.339508 $1=ENSG00000223972.4 $2=1 $3=54421 $4=A $5=G $6=b37 $7=42552 $8=28 $9=28 $10=0.039548 $11=0.680357 $12=0.0741142 $13=0.179725 ENSG00000223972.4 1_54421_A_G_b37 42552 28 28 0.039548 0.680357 0.0741142 0.179725 $1=ENSG00000223972.4 $2=1 $3=54490 $4=G $5=A $6=b37 $7=42621 $8=112 $9=120 $10=0.176471 $11=0.00824733 $12=0.247533 $13=0.093081 ENSG00000223972.4 1_54490_G_A_b37 42621 112 120 0.176471 0.00824733 0.247533 0.093081 ```
38,067,742
I get this message: The Google Maps API server rejected your request. You have exceeded your daily request quota for this API. Despite the site not yet being indexable and only having had 265 visitors - it's hosted at wordpress.com so I can't access the site code at all. Site theme is Selma (is it because the theme developers have exceeded their total requests?).
2016/06/28
[ "https://Stackoverflow.com/questions/38067742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6521475/" ]
It is defined: ``` private static Timer aTimer; ``` and assigned: ``` aTimer = new Timer(5); ```
The `static void Main` is the acces point of program. It will be executed at the very beginning. And it will assign a value to `aTimer`. ``` public class Example { private static Timer aTimer; ... public static void Main() { ... aTimer = new Timer(5); ... } ... } ```
38,067,742
I get this message: The Google Maps API server rejected your request. You have exceeded your daily request quota for this API. Despite the site not yet being indexable and only having had 265 visitors - it's hosted at wordpress.com so I can't access the site code at all. Site theme is Selma (is it because the theme developers have exceeded their total requests?).
2016/06/28
[ "https://Stackoverflow.com/questions/38067742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6521475/" ]
``` using System; using System.IO; using System.Collections.Generic; using System.Timers; public class Example { private static Timer aTimer; ``` Last line of this code. Press Ctrl+F and Highlight All (Mozilla Firefox), search for aTimer
The `static void Main` is the acces point of program. It will be executed at the very beginning. And it will assign a value to `aTimer`. ``` public class Example { private static Timer aTimer; ... public static void Main() { ... aTimer = new Timer(5); ... } ... } ```
23,598,213
I'm trying my first adventure using viewmodels, but I got a problem, this is my view model and the models: **ViewModel:** ``` public class ProfessionalDashboard { public List<JobOffertModel> AcceptedJobOfferts { get; set; } public List<JobOffertModel> NotAcceptedJobOfferts { get; set; } public ProfessionalModel Professional { get; set; } } ``` **Models:** ``` public class JobOffertModel { [Key] public int Id { get; set; } public ProfessionalModel Professional { get; set; } [Required] public string Description { get; set; } [Required] [DefaultValue(false)] public bool Accepted { get; set; } [Required] [DefaultValue(true)] public bool Active { get; set; } public ICollection<SkillModel> Skills { get; set; } [Required] [Column(TypeName = "DateTime2")] public DateTime JobDate { get; set; } public virtual CustomerModel Customer { get; set; } } ``` And ... ``` public class ProfessionalModel { [Key] public int Id { get; set; } [Required] public string Name { get; set; } [Required] [Column(TypeName = "DateTime2")] public DateTime BirthDate { get; set; } public int PhoneNumber { get; set; } public string Profession { get; set; } public UserAddressModel UserAddress { get; set; } [Required] public UserAccountModel UserAccount { get; set; } public ICollection<SkillModel> Skills { get; set; } public ProfessionalModel() {} } ``` Here is my View: ``` @model TCCApplication.ViewModels.ProfessionalDashboard @{ ViewBag.Title = "Dashboard"; } <div class="row"> <div class="col-md-5"> <h2>Minhas tarefas</h2> @for (int i = 0; i < Model.AcceptedJobOfferts.Count; i++) { @Html.HiddenFor(itemModel => Model.AcceptedJobOfferts[i].Id) <div class="row"> <div class="col-md-3"> <label>Oferta: </label> @Html.DisplayFor(itemModel => Model.AcceptedJobOfferts[i].Description) </div> @*<div class="col-md-2"> <label>Aceito</label> @Html.DisplayFor(itemModel => Model.AcceptedJobOfferts[i].Accepted) </div>*@ <div class="col-md-5"> <label>Data do trabalho</label> @Html.DisplayFor(itemModel => Model.AcceptedJobOfferts[i].JobDate) </div> @Html.HiddenFor(itemModel => Model.AcceptedJobOfferts[i].Professional.Id) @Html.HiddenFor(itemModel => Model.AcceptedJobOfferts[i].Professional.Name) @Html.HiddenFor(itemModel => Model.AcceptedJobOfferts[i].Professional.Skills) @Html.HiddenFor(itemModel => Model.AcceptedJobOfferts[i].Professional.BirthDate) @Html.HiddenFor(itemModel => Model.AcceptedJobOfferts[i].JobDate) @Html.HiddenFor(itemModel => Model.AcceptedJobOfferts[i].Active) @Html.HiddenFor(itemModel => Model.AcceptedJobOfferts[i].Description) @Html.HiddenFor(itemModel => Model.AcceptedJobOfferts[i].Accepted) </div> } </div> <div class="col-md-7"> @using (Html.BeginForm("AcceptJobOfferts","Professional")){ for (int i = 0; i < Model.NotAcceptedJobOfferts.Count; i++) { @Html.HiddenFor(itemModel => Model.NotAcceptedJobOfferts[i].Professional) @Html.HiddenFor(itemModel => Model.NotAcceptedJobOfferts[i].Professional.Id) @Html.HiddenFor(itemModel => Model.NotAcceptedJobOfferts[i].Professional.Name) @Html.HiddenFor(itemModel => Model.NotAcceptedJobOfferts[i].Professional.Skills) @Html.HiddenFor(itemModel => Model.NotAcceptedJobOfferts[i].Professional.BirthDate) @Html.HiddenFor(itemModel => Model.NotAcceptedJobOfferts[i].JobDate) @Html.HiddenFor(itemModel => Model.NotAcceptedJobOfferts[i].Active) @Html.HiddenFor(itemModel => Model.NotAcceptedJobOfferts[i].Description) @Html.HiddenFor(itemModel => Model.NotAcceptedJobOfferts[i].Accepted) @Html.HiddenFor(itemModel => Model.NotAcceptedJobOfferts) <h2>Ofertas de trabalho indicadas</h2> @Html.HiddenFor(itemModel => Model.NotAcceptedJobOfferts[i].Id) <div class="row"> <div class="col-md-3"> <label>Oferta: </label> @Html.DisplayFor(itemModel => Model.NotAcceptedJobOfferts[i].Description) </div> <div class="col-md-2"> <label>Aceito</label> @Html.EditorFor(itemModel => Model.NotAcceptedJobOfferts[i].Accepted) </div> <div class="col-md-5"> <label>Data do trabalho</label> @Html.DisplayFor(itemModel => Model.NotAcceptedJobOfferts[i].JobDate) </div> </div> } <div> <input type="submit" value="Aceitar Ofertas" /> <!-- This is the post button --> </div> } </div> </div> <div class="row" style="height:50px"> </div> <div class="row"> <div class="col-md-12 text-center"> <div> <label>Cliente: </label> @Model.Professional.Name </div> <div> <label>Data de nascimento: </label> @Model.Professional.BirthDate </div> <div> <label>Telefone: </label> @Model.Professional.PhoneNumber </div> <div> <label>Usuário: </label> @Model.Professional.UserAccount.Username </div> <div> <label>Profissão: </label> @Model.Professional.Profession </div> <div> <label>Bairro: </label> @Model.Professional.UserAddress.Neighborhood </div> <p class="div-to-btn"> @Html.ActionLink("Alterar informações", "Edit", new { id = @Model.Professional.Id }) </p> </div> </div> ``` And this is the method who must to receive the post method: ``` [HttpPost] public ActionResult AcceptJobOfferts(ProfessionalDashboard profDash) { initBusinessObjects(); //foreach (var jo in jobOffertModel) //{ // jobOffertBusiness.Update(jo); //} return RedirectToAction("ViewMyTasks", new { professionalId = profDash.Professional.Id}); } ``` My parameter profDash receives a null Professional Object, a null List and another with zero itens. How can I make it work?
2014/05/11
[ "https://Stackoverflow.com/questions/23598213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1121139/" ]
All I see in your form are `Model.NotAcceptedJobOfferts`. If you want to maintain your data you need to add it as a hidden input in your form. Once the view is rendered to the user, your model is lost, the only data available is what has been rendered on the page.
You have a plenty of complex types in play. The default model binder is having difficulties in binding the values that are getting posted in the form. Here's something you can do: * Check the names of the values in the HTML by doing view source. Make sure they are following [PropertyNameInParentModelClass].[PropertyNameInChildModelClass] convention.For ex: Professional.Name * Add a break point in the action method, and inspect the form values.Try looking at HttpContext.Current.Request. Check if all the expected form values are there as expected. * Consider simplifying the view models and models a bit by cutting out the things you are not going to need. As you have a complete view of your system(hopefully), you should be able to determine that. * Consider using custom model binders. There's plenty of literature on internet on how to have custom model binders. Here's a couple to start with: [MSDN article](http://msdn.microsoft.com/en-us/magazine/hh781022.aspx) and [Code Project Example](http://www.codeproject.com/Articles/605595/ASP-NET-MVC-Custom-Model-Binder)
56,141,507
I have `TextInputLayout` and `TextInputEditText` like this ``` <com.google.android.material.textfield.TextInputLayout android:id="@+id/loginUsernameText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/text_input_margin_left_right" android:layout_marginRight="@dimen/text_input_margin_left_right" android:layout_marginTop="@dimen/text_input_margin_top_bottom" android:hint="@string/username" android:layout_below="@id/loginButtonLogin"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/loginUsername" android:layout_width="match_parent" android:padding="5dp" android:layout_height="wrap_content" android:inputType="textEmailAddress"/> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.textfield.TextInputLayout android:id="@+id/loginPasswordText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/text_input_margin_left_right" android:layout_marginRight="@dimen/text_input_margin_left_right" android:layout_marginTop="@dimen/text_input_margin_top_bottom" android:hint="@string/password" android:layout_below="@id/loginUsernameText"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/loginPassword" android:layout_width="match_parent" android:padding="5dp" android:layout_height="wrap_content" android:inputType="textPassword"/> </com.google.android.material.textfield.TextInputLayout> ``` This is my styles.xml file ``` <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /> <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /> <style name="TextAppearance.App.TextInputLayout" parent="@android:style/TextAppearance"> <item name="android:textColor">@color/white</item> <item name="android:textSize">14sp</item> </style> </resources> ``` So I am not using anything extra on TextInputLayout and they are appearing like this [![enter image description here](https://i.stack.imgur.com/QHRDx.png)](https://i.stack.imgur.com/QHRDx.png) This grey background is always there. How do I remove this background and just get the default TextInputLayout. Thanks.
2019/05/15
[ "https://Stackoverflow.com/questions/56141507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2325929/" ]
The default background color is based on the **`colorOnSurface`** attribute. You can override this value using: ``` <com.google.android.material.textfield.TextInputLayout android:theme="@style/MyTextInputLayout_overlay" ..> ``` with: ``` <style name="MyTextInputLayout_overlay"> <item name="colorOnSurface">@color/....</item> </style> ``` or you can use the **`boxBackgroundColor`** attribute (in the layout or in a custom style): ``` <com.google.android.material.textfield.TextInputLayout app:boxBackgroundColor="@color/....." ..> ```
At beginning everything was working fine. Later layout was broken. The reason was I changed property background TextInputEditText. Transaparency must be set on TextInputEditText, not in TextInputLayout **`android:background="#80FFFFFF"`**
56,141,507
I have `TextInputLayout` and `TextInputEditText` like this ``` <com.google.android.material.textfield.TextInputLayout android:id="@+id/loginUsernameText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/text_input_margin_left_right" android:layout_marginRight="@dimen/text_input_margin_left_right" android:layout_marginTop="@dimen/text_input_margin_top_bottom" android:hint="@string/username" android:layout_below="@id/loginButtonLogin"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/loginUsername" android:layout_width="match_parent" android:padding="5dp" android:layout_height="wrap_content" android:inputType="textEmailAddress"/> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.textfield.TextInputLayout android:id="@+id/loginPasswordText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/text_input_margin_left_right" android:layout_marginRight="@dimen/text_input_margin_left_right" android:layout_marginTop="@dimen/text_input_margin_top_bottom" android:hint="@string/password" android:layout_below="@id/loginUsernameText"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/loginPassword" android:layout_width="match_parent" android:padding="5dp" android:layout_height="wrap_content" android:inputType="textPassword"/> </com.google.android.material.textfield.TextInputLayout> ``` This is my styles.xml file ``` <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /> <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /> <style name="TextAppearance.App.TextInputLayout" parent="@android:style/TextAppearance"> <item name="android:textColor">@color/white</item> <item name="android:textSize">14sp</item> </style> </resources> ``` So I am not using anything extra on TextInputLayout and they are appearing like this [![enter image description here](https://i.stack.imgur.com/QHRDx.png)](https://i.stack.imgur.com/QHRDx.png) This grey background is always there. How do I remove this background and just get the default TextInputLayout. Thanks.
2019/05/15
[ "https://Stackoverflow.com/questions/56141507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2325929/" ]
**Method A** *(completely transparent background)* ``` <com.google.android.material.textfield.TextInputLayout app:boxBackgroundMode="filled" app:boxBackgroundColor="@null" ..> <com.google.android.material.textfield.TextInputEditText android:backgroundTint="@android:color/transparent" ..> ``` **Method B** *(solid background colour)* ``` <com.google.android.material.textfield.TextInputLayout app:boxBackgroundMode="filled" app:boxBackgroundColor="?android:attr/colorBackground" ..> ``` \*For my case, I needed it to be fully transparent as the screen background is not a solid colour. If that's the case for you, go with **Method A**
You can use these options to customise the TextInputLayout. ``` <com.google.android.material.textfield.TextInputLayout android:id="@+id/menuMakeList" style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox.ExposedDropdownMenu" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:background="@drawable/background_round_menu_selector" app:boxBackgroundColor="@android:color/transparent" app:boxBackgroundMode="outline" app:boxStrokeColor="@android:color/transparent" app:boxStrokeWidth="0dp" app:endIconDrawable="@drawable/ic_arrow_down" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textViewHeader"> <AutoCompleteTextView android:layout_width="match_parent" android:layout_height="wrap_content" android:background="null" android:hint="Make" android:inputType="none" android:padding="16dp" app:hintTextColor="#C8CCC9" /> </com.google.android.material.textfield.TextInputLayout> ``` This is how it will be coming up. I have used my custom rounded corners xml as background and override the colors from material **background\_round\_menu\_selector.xml**. ``` <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="@color/white" /> <corners android:radius="15dp" /> <stroke android:width="2dp" android:color="#EAEAEA" /> </shape> ``` [![enter image description here](https://i.stack.imgur.com/CEDwZ.png)](https://i.stack.imgur.com/CEDwZ.png)
56,141,507
I have `TextInputLayout` and `TextInputEditText` like this ``` <com.google.android.material.textfield.TextInputLayout android:id="@+id/loginUsernameText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/text_input_margin_left_right" android:layout_marginRight="@dimen/text_input_margin_left_right" android:layout_marginTop="@dimen/text_input_margin_top_bottom" android:hint="@string/username" android:layout_below="@id/loginButtonLogin"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/loginUsername" android:layout_width="match_parent" android:padding="5dp" android:layout_height="wrap_content" android:inputType="textEmailAddress"/> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.textfield.TextInputLayout android:id="@+id/loginPasswordText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/text_input_margin_left_right" android:layout_marginRight="@dimen/text_input_margin_left_right" android:layout_marginTop="@dimen/text_input_margin_top_bottom" android:hint="@string/password" android:layout_below="@id/loginUsernameText"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/loginPassword" android:layout_width="match_parent" android:padding="5dp" android:layout_height="wrap_content" android:inputType="textPassword"/> </com.google.android.material.textfield.TextInputLayout> ``` This is my styles.xml file ``` <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /> <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /> <style name="TextAppearance.App.TextInputLayout" parent="@android:style/TextAppearance"> <item name="android:textColor">@color/white</item> <item name="android:textSize">14sp</item> </style> </resources> ``` So I am not using anything extra on TextInputLayout and they are appearing like this [![enter image description here](https://i.stack.imgur.com/QHRDx.png)](https://i.stack.imgur.com/QHRDx.png) This grey background is always there. How do I remove this background and just get the default TextInputLayout. Thanks.
2019/05/15
[ "https://Stackoverflow.com/questions/56141507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2325929/" ]
For me it worked with `app:boxBackgroundColor="@null"`, like this: ``` <com.google.android.material.textfield.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" app:boxBackgroundColor="@null" android:hint="@string/description"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/description" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textMultiLine|textCapSentences" /> </com.google.android.material.textfield.TextInputLayout> ```
I recently faced with this issue. None of the above solutions worked for the latest material theme release. Took me a while to figure it out. Here's my solution: **Style:** ``` <style name="Widget.App.TextInputLayout" parent="Widget.Design.TextInputLayout"> <item name="materialThemeOverlay">@style/ThemeOverlay.App.TextInputLayout</item> <item name="hintTextColor">@color/pink</item> <item name="android:textColorHint">@color/grey</item> </style> <style name="ThemeOverlay.App.TextInputLayout" parent=""> <item name="colorControlNormal">@color/grey</item> </style> ``` **Usage:** ``` <com.google.android.material.textfield.TextInputLayout android:id="@+id/password" style="@style/Widget.App.TextInputLayout" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="@string/password" app:layout_constraintBottom_toTopOf="@+id/agreement" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/email"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword"/> </com.google.android.material.textfield.TextInputLayout> ``` > > Also I strongly recommend you to check this article out. [Migrating to > Material Components for Android](http://Migrating%20to%20Material%20Components%20for%20Android) > > >
56,141,507
I have `TextInputLayout` and `TextInputEditText` like this ``` <com.google.android.material.textfield.TextInputLayout android:id="@+id/loginUsernameText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/text_input_margin_left_right" android:layout_marginRight="@dimen/text_input_margin_left_right" android:layout_marginTop="@dimen/text_input_margin_top_bottom" android:hint="@string/username" android:layout_below="@id/loginButtonLogin"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/loginUsername" android:layout_width="match_parent" android:padding="5dp" android:layout_height="wrap_content" android:inputType="textEmailAddress"/> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.textfield.TextInputLayout android:id="@+id/loginPasswordText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/text_input_margin_left_right" android:layout_marginRight="@dimen/text_input_margin_left_right" android:layout_marginTop="@dimen/text_input_margin_top_bottom" android:hint="@string/password" android:layout_below="@id/loginUsernameText"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/loginPassword" android:layout_width="match_parent" android:padding="5dp" android:layout_height="wrap_content" android:inputType="textPassword"/> </com.google.android.material.textfield.TextInputLayout> ``` This is my styles.xml file ``` <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /> <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /> <style name="TextAppearance.App.TextInputLayout" parent="@android:style/TextAppearance"> <item name="android:textColor">@color/white</item> <item name="android:textSize">14sp</item> </style> </resources> ``` So I am not using anything extra on TextInputLayout and they are appearing like this [![enter image description here](https://i.stack.imgur.com/QHRDx.png)](https://i.stack.imgur.com/QHRDx.png) This grey background is always there. How do I remove this background and just get the default TextInputLayout. Thanks.
2019/05/15
[ "https://Stackoverflow.com/questions/56141507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2325929/" ]
<https://github.com/material-components/material-components-android/issues/102> It seems a material textfield bug. You can use this code to change background white temporarily. ``` <com.google.android.material.textfield.TextInputLayout app:boxBackgroundColor="@android:color/transparent" android:background="@android:color/transparent"> <com.google.android.material.textfield.TextInputEditText/> </com.google.android.material.textfield.TextInputLayout> ```
**Method A** *(completely transparent background)* ``` <com.google.android.material.textfield.TextInputLayout app:boxBackgroundMode="filled" app:boxBackgroundColor="@null" ..> <com.google.android.material.textfield.TextInputEditText android:backgroundTint="@android:color/transparent" ..> ``` **Method B** *(solid background colour)* ``` <com.google.android.material.textfield.TextInputLayout app:boxBackgroundMode="filled" app:boxBackgroundColor="?android:attr/colorBackground" ..> ``` \*For my case, I needed it to be fully transparent as the screen background is not a solid colour. If that's the case for you, go with **Method A**
56,141,507
I have `TextInputLayout` and `TextInputEditText` like this ``` <com.google.android.material.textfield.TextInputLayout android:id="@+id/loginUsernameText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/text_input_margin_left_right" android:layout_marginRight="@dimen/text_input_margin_left_right" android:layout_marginTop="@dimen/text_input_margin_top_bottom" android:hint="@string/username" android:layout_below="@id/loginButtonLogin"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/loginUsername" android:layout_width="match_parent" android:padding="5dp" android:layout_height="wrap_content" android:inputType="textEmailAddress"/> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.textfield.TextInputLayout android:id="@+id/loginPasswordText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/text_input_margin_left_right" android:layout_marginRight="@dimen/text_input_margin_left_right" android:layout_marginTop="@dimen/text_input_margin_top_bottom" android:hint="@string/password" android:layout_below="@id/loginUsernameText"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/loginPassword" android:layout_width="match_parent" android:padding="5dp" android:layout_height="wrap_content" android:inputType="textPassword"/> </com.google.android.material.textfield.TextInputLayout> ``` This is my styles.xml file ``` <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /> <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /> <style name="TextAppearance.App.TextInputLayout" parent="@android:style/TextAppearance"> <item name="android:textColor">@color/white</item> <item name="android:textSize">14sp</item> </style> </resources> ``` So I am not using anything extra on TextInputLayout and they are appearing like this [![enter image description here](https://i.stack.imgur.com/QHRDx.png)](https://i.stack.imgur.com/QHRDx.png) This grey background is always there. How do I remove this background and just get the default TextInputLayout. Thanks.
2019/05/15
[ "https://Stackoverflow.com/questions/56141507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2325929/" ]
For me it worked with `app:boxBackgroundColor="@null"`, like this: ``` <com.google.android.material.textfield.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" app:boxBackgroundColor="@null" android:hint="@string/description"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/description" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textMultiLine|textCapSentences" /> </com.google.android.material.textfield.TextInputLayout> ```
Simple way worked for me! ``` app:boxBackgroundMode="filled" app:boxBackgroundColor="@color/white" ```
56,141,507
I have `TextInputLayout` and `TextInputEditText` like this ``` <com.google.android.material.textfield.TextInputLayout android:id="@+id/loginUsernameText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/text_input_margin_left_right" android:layout_marginRight="@dimen/text_input_margin_left_right" android:layout_marginTop="@dimen/text_input_margin_top_bottom" android:hint="@string/username" android:layout_below="@id/loginButtonLogin"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/loginUsername" android:layout_width="match_parent" android:padding="5dp" android:layout_height="wrap_content" android:inputType="textEmailAddress"/> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.textfield.TextInputLayout android:id="@+id/loginPasswordText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/text_input_margin_left_right" android:layout_marginRight="@dimen/text_input_margin_left_right" android:layout_marginTop="@dimen/text_input_margin_top_bottom" android:hint="@string/password" android:layout_below="@id/loginUsernameText"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/loginPassword" android:layout_width="match_parent" android:padding="5dp" android:layout_height="wrap_content" android:inputType="textPassword"/> </com.google.android.material.textfield.TextInputLayout> ``` This is my styles.xml file ``` <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /> <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /> <style name="TextAppearance.App.TextInputLayout" parent="@android:style/TextAppearance"> <item name="android:textColor">@color/white</item> <item name="android:textSize">14sp</item> </style> </resources> ``` So I am not using anything extra on TextInputLayout and they are appearing like this [![enter image description here](https://i.stack.imgur.com/QHRDx.png)](https://i.stack.imgur.com/QHRDx.png) This grey background is always there. How do I remove this background and just get the default TextInputLayout. Thanks.
2019/05/15
[ "https://Stackoverflow.com/questions/56141507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2325929/" ]
For me it worked with `app:boxBackgroundColor="@null"`, like this: ``` <com.google.android.material.textfield.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" app:boxBackgroundColor="@null" android:hint="@string/description"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/description" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textMultiLine|textCapSentences" /> </com.google.android.material.textfield.TextInputLayout> ```
The default background color is based on the **`colorOnSurface`** attribute. You can override this value using: ``` <com.google.android.material.textfield.TextInputLayout android:theme="@style/MyTextInputLayout_overlay" ..> ``` with: ``` <style name="MyTextInputLayout_overlay"> <item name="colorOnSurface">@color/....</item> </style> ``` or you can use the **`boxBackgroundColor`** attribute (in the layout or in a custom style): ``` <com.google.android.material.textfield.TextInputLayout app:boxBackgroundColor="@color/....." ..> ```
56,141,507
I have `TextInputLayout` and `TextInputEditText` like this ``` <com.google.android.material.textfield.TextInputLayout android:id="@+id/loginUsernameText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/text_input_margin_left_right" android:layout_marginRight="@dimen/text_input_margin_left_right" android:layout_marginTop="@dimen/text_input_margin_top_bottom" android:hint="@string/username" android:layout_below="@id/loginButtonLogin"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/loginUsername" android:layout_width="match_parent" android:padding="5dp" android:layout_height="wrap_content" android:inputType="textEmailAddress"/> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.textfield.TextInputLayout android:id="@+id/loginPasswordText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/text_input_margin_left_right" android:layout_marginRight="@dimen/text_input_margin_left_right" android:layout_marginTop="@dimen/text_input_margin_top_bottom" android:hint="@string/password" android:layout_below="@id/loginUsernameText"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/loginPassword" android:layout_width="match_parent" android:padding="5dp" android:layout_height="wrap_content" android:inputType="textPassword"/> </com.google.android.material.textfield.TextInputLayout> ``` This is my styles.xml file ``` <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /> <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /> <style name="TextAppearance.App.TextInputLayout" parent="@android:style/TextAppearance"> <item name="android:textColor">@color/white</item> <item name="android:textSize">14sp</item> </style> </resources> ``` So I am not using anything extra on TextInputLayout and they are appearing like this [![enter image description here](https://i.stack.imgur.com/QHRDx.png)](https://i.stack.imgur.com/QHRDx.png) This grey background is always there. How do I remove this background and just get the default TextInputLayout. Thanks.
2019/05/15
[ "https://Stackoverflow.com/questions/56141507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2325929/" ]
One way to remove the background color is to adjust the background mode of TextInputLayout. app:boxBackgroundMode="none" Worked for me. Example XML Code: ``` <com.google.android.material.textfield.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" app:boxBackgroundMode="none" app:errorEnabled="true" app:hintEnabled="false" app:layout_constraintTop_toTopOf="parent"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="top" android:hint="@string/comment_placeholder" android:inputType="textCapSentences|textMultiLine" android:maxLength="500" /> </com.google.android.material.textfield.TextInputLayout> ```
For me it worked with `app:boxBackgroundColor="@null"`, like this: ``` <com.google.android.material.textfield.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" app:boxBackgroundColor="@null" android:hint="@string/description"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/description" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textMultiLine|textCapSentences" /> </com.google.android.material.textfield.TextInputLayout> ```
56,141,507
I have `TextInputLayout` and `TextInputEditText` like this ``` <com.google.android.material.textfield.TextInputLayout android:id="@+id/loginUsernameText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/text_input_margin_left_right" android:layout_marginRight="@dimen/text_input_margin_left_right" android:layout_marginTop="@dimen/text_input_margin_top_bottom" android:hint="@string/username" android:layout_below="@id/loginButtonLogin"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/loginUsername" android:layout_width="match_parent" android:padding="5dp" android:layout_height="wrap_content" android:inputType="textEmailAddress"/> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.textfield.TextInputLayout android:id="@+id/loginPasswordText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/text_input_margin_left_right" android:layout_marginRight="@dimen/text_input_margin_left_right" android:layout_marginTop="@dimen/text_input_margin_top_bottom" android:hint="@string/password" android:layout_below="@id/loginUsernameText"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/loginPassword" android:layout_width="match_parent" android:padding="5dp" android:layout_height="wrap_content" android:inputType="textPassword"/> </com.google.android.material.textfield.TextInputLayout> ``` This is my styles.xml file ``` <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /> <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /> <style name="TextAppearance.App.TextInputLayout" parent="@android:style/TextAppearance"> <item name="android:textColor">@color/white</item> <item name="android:textSize">14sp</item> </style> </resources> ``` So I am not using anything extra on TextInputLayout and they are appearing like this [![enter image description here](https://i.stack.imgur.com/QHRDx.png)](https://i.stack.imgur.com/QHRDx.png) This grey background is always there. How do I remove this background and just get the default TextInputLayout. Thanks.
2019/05/15
[ "https://Stackoverflow.com/questions/56141507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2325929/" ]
Simple way worked for me! ``` app:boxBackgroundMode="filled" app:boxBackgroundColor="@color/white" ```
At beginning everything was working fine. Later layout was broken. The reason was I changed property background TextInputEditText. Transaparency must be set on TextInputEditText, not in TextInputLayout **`android:background="#80FFFFFF"`**
56,141,507
I have `TextInputLayout` and `TextInputEditText` like this ``` <com.google.android.material.textfield.TextInputLayout android:id="@+id/loginUsernameText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/text_input_margin_left_right" android:layout_marginRight="@dimen/text_input_margin_left_right" android:layout_marginTop="@dimen/text_input_margin_top_bottom" android:hint="@string/username" android:layout_below="@id/loginButtonLogin"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/loginUsername" android:layout_width="match_parent" android:padding="5dp" android:layout_height="wrap_content" android:inputType="textEmailAddress"/> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.textfield.TextInputLayout android:id="@+id/loginPasswordText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/text_input_margin_left_right" android:layout_marginRight="@dimen/text_input_margin_left_right" android:layout_marginTop="@dimen/text_input_margin_top_bottom" android:hint="@string/password" android:layout_below="@id/loginUsernameText"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/loginPassword" android:layout_width="match_parent" android:padding="5dp" android:layout_height="wrap_content" android:inputType="textPassword"/> </com.google.android.material.textfield.TextInputLayout> ``` This is my styles.xml file ``` <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /> <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /> <style name="TextAppearance.App.TextInputLayout" parent="@android:style/TextAppearance"> <item name="android:textColor">@color/white</item> <item name="android:textSize">14sp</item> </style> </resources> ``` So I am not using anything extra on TextInputLayout and they are appearing like this [![enter image description here](https://i.stack.imgur.com/QHRDx.png)](https://i.stack.imgur.com/QHRDx.png) This grey background is always there. How do I remove this background and just get the default TextInputLayout. Thanks.
2019/05/15
[ "https://Stackoverflow.com/questions/56141507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2325929/" ]
I recently faced with this issue. None of the above solutions worked for the latest material theme release. Took me a while to figure it out. Here's my solution: **Style:** ``` <style name="Widget.App.TextInputLayout" parent="Widget.Design.TextInputLayout"> <item name="materialThemeOverlay">@style/ThemeOverlay.App.TextInputLayout</item> <item name="hintTextColor">@color/pink</item> <item name="android:textColorHint">@color/grey</item> </style> <style name="ThemeOverlay.App.TextInputLayout" parent=""> <item name="colorControlNormal">@color/grey</item> </style> ``` **Usage:** ``` <com.google.android.material.textfield.TextInputLayout android:id="@+id/password" style="@style/Widget.App.TextInputLayout" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="@string/password" app:layout_constraintBottom_toTopOf="@+id/agreement" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/email"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword"/> </com.google.android.material.textfield.TextInputLayout> ``` > > Also I strongly recommend you to check this article out. [Migrating to > Material Components for Android](http://Migrating%20to%20Material%20Components%20for%20Android) > > >
You can use these options to customise the TextInputLayout. ``` <com.google.android.material.textfield.TextInputLayout android:id="@+id/menuMakeList" style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox.ExposedDropdownMenu" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:background="@drawable/background_round_menu_selector" app:boxBackgroundColor="@android:color/transparent" app:boxBackgroundMode="outline" app:boxStrokeColor="@android:color/transparent" app:boxStrokeWidth="0dp" app:endIconDrawable="@drawable/ic_arrow_down" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textViewHeader"> <AutoCompleteTextView android:layout_width="match_parent" android:layout_height="wrap_content" android:background="null" android:hint="Make" android:inputType="none" android:padding="16dp" app:hintTextColor="#C8CCC9" /> </com.google.android.material.textfield.TextInputLayout> ``` This is how it will be coming up. I have used my custom rounded corners xml as background and override the colors from material **background\_round\_menu\_selector.xml**. ``` <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="@color/white" /> <corners android:radius="15dp" /> <stroke android:width="2dp" android:color="#EAEAEA" /> </shape> ``` [![enter image description here](https://i.stack.imgur.com/CEDwZ.png)](https://i.stack.imgur.com/CEDwZ.png)
56,141,507
I have `TextInputLayout` and `TextInputEditText` like this ``` <com.google.android.material.textfield.TextInputLayout android:id="@+id/loginUsernameText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/text_input_margin_left_right" android:layout_marginRight="@dimen/text_input_margin_left_right" android:layout_marginTop="@dimen/text_input_margin_top_bottom" android:hint="@string/username" android:layout_below="@id/loginButtonLogin"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/loginUsername" android:layout_width="match_parent" android:padding="5dp" android:layout_height="wrap_content" android:inputType="textEmailAddress"/> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.textfield.TextInputLayout android:id="@+id/loginPasswordText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/text_input_margin_left_right" android:layout_marginRight="@dimen/text_input_margin_left_right" android:layout_marginTop="@dimen/text_input_margin_top_bottom" android:hint="@string/password" android:layout_below="@id/loginUsernameText"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/loginPassword" android:layout_width="match_parent" android:padding="5dp" android:layout_height="wrap_content" android:inputType="textPassword"/> </com.google.android.material.textfield.TextInputLayout> ``` This is my styles.xml file ``` <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /> <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /> <style name="TextAppearance.App.TextInputLayout" parent="@android:style/TextAppearance"> <item name="android:textColor">@color/white</item> <item name="android:textSize">14sp</item> </style> </resources> ``` So I am not using anything extra on TextInputLayout and they are appearing like this [![enter image description here](https://i.stack.imgur.com/QHRDx.png)](https://i.stack.imgur.com/QHRDx.png) This grey background is always there. How do I remove this background and just get the default TextInputLayout. Thanks.
2019/05/15
[ "https://Stackoverflow.com/questions/56141507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2325929/" ]
I recently faced with this issue. None of the above solutions worked for the latest material theme release. Took me a while to figure it out. Here's my solution: **Style:** ``` <style name="Widget.App.TextInputLayout" parent="Widget.Design.TextInputLayout"> <item name="materialThemeOverlay">@style/ThemeOverlay.App.TextInputLayout</item> <item name="hintTextColor">@color/pink</item> <item name="android:textColorHint">@color/grey</item> </style> <style name="ThemeOverlay.App.TextInputLayout" parent=""> <item name="colorControlNormal">@color/grey</item> </style> ``` **Usage:** ``` <com.google.android.material.textfield.TextInputLayout android:id="@+id/password" style="@style/Widget.App.TextInputLayout" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="@string/password" app:layout_constraintBottom_toTopOf="@+id/agreement" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/email"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword"/> </com.google.android.material.textfield.TextInputLayout> ``` > > Also I strongly recommend you to check this article out. [Migrating to > Material Components for Android](http://Migrating%20to%20Material%20Components%20for%20Android) > > >
At beginning everything was working fine. Later layout was broken. The reason was I changed property background TextInputEditText. Transaparency must be set on TextInputEditText, not in TextInputLayout **`android:background="#80FFFFFF"`**
59,737,839
I'm using `vuex-presistedstate` in my project. In the source code on github the plugin calls `store.replaceState` to hydrate store from storage. Is there a way to know when the store hydrates?
2020/01/14
[ "https://Stackoverflow.com/questions/59737839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9388051/" ]
The `vuex-presistedstate` plugin has a configuration option called `rehydrated` that allows you to pass a function that will be called immediately after `replaceState`. If you only care about calls to `replaceState` from that plugin then that should fit your needs nicely. I don't believe the store itself provides a 'hook' for when `replaceState` is called. The method `replaceState` is implemented here: <https://github.com/vuejs/vuex/blob/e0126533301febf66072f1865cf9a77778cf2176/src/store.js#L183> As you can see from the code it doesn't do much. Even subscribers registered using `subscribe` aren't called. However, you could potentially use `watch` to register a watcher on a specific property within the state and use that to detect when the state is replaced: <https://vuex.vuejs.org/api/#watch> Of course you'd need to be careful to structure things so that only the calls to `replaceState` trigger the watcher, which may get fiddly. A further alternative would be to patch/override the `replaceState` method. Replace it with your own method that calls out to the original, giving you a hook point for any extra functionality you might need. I've attempted to demonstrate all of the above in the example below: ```js // Can't use localStorage in an SO snippet... const fakeStorage = { vuex: `{"flag": {}, "number": ${Math.random()}}` } const storage = { getItem (key) { return fakeStorage[key] }, setItem (key, value) { fakeStorage[key] = value }, removeItem (key) { delete fakeStorage[key] } } // Override replaceState with our own version class StoreOverride extends Vuex.Store { replaceState (...args) { super.replaceState(...args) console.log('replaceState called') } } const store = new StoreOverride({ state: { flag: {}, number: 0 }, plugins: [ createPersistedState({ rehydrated () { console.log('rehydrated called') }, storage }) ] }) store.subscribe(() => { console.log('store.subscribe called (will not happen for replaceState)') }) store.watch(state => state.flag, () => { console.log('store.watch called') }) console.log('creating Vue instance') new Vue({ el: '#app', store, methods: { onReplace () { // The property 'number' is changed so we can see something happen this.$store.replaceState({ flag: {}, number: this.$store.state.number + 1 }) } } }) ``` ```html <script src="https://unpkg.com/[email protected]/dist/vue.js"></script> <script> Vue.config.devtools = false Vue.config.productionTip = false </script> <script src="https://unpkg.com/[email protected]/dist/vuex.js"></script> <script src="https://unpkg.com/[email protected]/dist/vuex-persistedstate.umd.js"></script> <div id="app"> <button @click="onReplace">Replace</button> <p>{{ $store.state.number }}</p> </div> ```
You can try rewrite `store.replaceState`: ```js import store from './your/path/to/store' // ... store.replaceState = (fn => (...params) => { console.log('do something before replaceState called') fn.apply(store, params) console.log('do something after replaceState called') })(store.replaceState) ``` In this way, you can watch not only `replaceState` but any methods on `store` instance if you want.
52,186,029
I have a `DBContext` that is initializing through `DropCreateDatabaseAlways` class. In the `Seed` method I have this code: ``` base.Seed(context); var c1 = new Company { Name = "Samsung"}; var c2 = new Company { Name = "Microsoft"}; context.Companies.AddRange(new List<Company>{c1,c2 }); var phones = new List<Phone> { new Phone("Samsung Galaxy S5", 20000, c1), new Phone("Nokia S1243", 200000, c1), new Phone("Nokia 930", 10000, c2), new Phone("Nokia 890", 8900, c2) }; context.Phones.AddRange(phones); context.SaveChanges(); ``` And if iterate through `phones` now, I see that `phone.Company` is not `null`. But when I do this in any other piece of code, `phone.Company` IS `null`. What do I do wrong? A simple piece of code with null `phone.Company`: ``` using (var db = new MyDataModel()) { var phonesList = db.Phones.ToList(); foreach (var p in phones) { System.Console.WriteLine($"Name: {p.Name} Company: {p.Company}"); // Company is null. } } ``` I can access `Company` using `Join` with Companies on `phone.companyId`, so `Companies` table exists in DB. My `DataModel` class: ``` public class MyDataModel : DbContext { public MyDataModel() : base("name=MyDataModel") { } static MyDataModel() { Database.SetInitializer(new MyContextInializer()); } public DbSet<Company> Companies { get; set; } public DbSet<Phone> Phones { get; set; } } ``` My `Phone` class: ``` namespace DataContext { public class Phone { public Phone() { } public Phone(string name, int price, Company company) { Name = name; Price = price; Company = company; } public int Id { get; set; } public string Name { get; set; } public int Price { get; set; } public int CompanyId { get; set; } public Company Company { get; set; } } } ```
2018/09/05
[ "https://Stackoverflow.com/questions/52186029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9047572/" ]
If you want to automagically load the companies when you load a phone, you need to add the `virtual` keyword before the Company property. ``` public class Phone { public Phone() { } public Phone(string name, int price, Company company) { Name = name; Price = price; Company = company; } public int Id { get; set; } public string Name { get; set; } public int Price { get; set; } public int CompanyId { get; set; } public virtual Company Company { get; set; } } ``` This tells entity framework to automatically load the linked company whenever you retrieve a phone from the database. Alternatively you can use eager loading when performing a query on phones. ``` var phones = MyDataModel.Phones.Include(x => x.Company).ToList(); ```
In addition to the cool answer from Immorality, I'll place here these links: 1. [Virtual properties](https://stackoverflow.com/questions/8542864/why-use-virtual-for-class-properties-in-entity-framework-model-definitions) 2. [MSDN - Loading related data strategies](https://msdn.microsoft.com/en-us/magazine/hh205756.aspx)
70,274,059
I want to write unique initials before listing an array of names, so given const names = ["Bill", "Jack", "john"], I would like to print something like: ``` <ul> <li>B <ul> <li>Bill</li> </ul> </li> <li>J <ul> <li>John</li> <li>jack</li> </ul> </li> </ul> ``` The way I found to do this is to push the JSX into an array before rendering it like: ``` const RenderNames = () => { let initials = []; let renderData = []; names.forEach(name => { let initial = name.charAt(0).toUpperCase(); if(initials.indexOf(initial) === -1){ initials.push(initial) renderData.push(<li>{initial}</li>) } renderData.push(<li>{name}</li>) }); return <ul>{renderData}</ul>; } ``` But I feel the code is a bit clunky, and I can only push in tags that are immediately closing. Is this the best way to do things or could it be done better?
2021/12/08
[ "https://Stackoverflow.com/questions/70274059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6130262/" ]
Here we go: ``` const names = ['Bill', 'Jack', 'john', 'Alex']; const groupedNames = names.reduce((accumulator, name) => { // first char of name, uppercased const firstLetter = name[0].toUpperCase(); // check if data for key exist const namesList = accumulator[firstLetter] || []; // check if name in array exist to prevent duplicates // keep in mind for example John and john are not the same if (!namesList.includes(name)) { namesList.push(name); } // collect data and return return {...accumulator, [firstLetter]: namesList} }, {}); ``` and result is ``` { B: [ 'Bill' ], J: [ 'Jack', 'john' ], A: [ 'Alex' ] } ``` Then you can sort keys and `map()` over it.
You can use this:: ``` const names = ['Bill', 'John', 'bob', 'Jack']; const category = names.reduce((unique, name) => { const char = name.charAt(0).toUpperCase(); return (unique[char] ? { ...unique, [char]: [...unique[char], name] } : { ...unique, [char]: [name] }); }, {}); return ( <div className="App"> <ul> { Object.entries(category).map(([key, value]) => <ul> <li>{key}</li> { value.length && <ul> { value.map(name => <li>{name}</li> ) } </ul> } </ul> )} </ul> </div> ); ``` Check this link: <https://codesandbox.io/s/vigilant-sound-ukv0q?file=/src/App.js>
39,492,631
I am doing a little code for my programming class and we need to make a program that calculates the cost of building a desk. I need help changing my DrawerAmount to an integer, not a string! ``` def Drawers(): print("How many drawers are there?") DrawerAmount = input(int) print("Okay, I accept that the total amount of drawers is " + DrawerAmount + ".") return DrawerAmount def Desk(): print("What type of wood is your desk?") DeskType = input() print("Alright, your desk is made of " + DeskType + ".") return DeskType def Calculation(DrawerAmount, DeskType): if "m" in DeskType: FinalPrice = DrawerAmount * 30 + 180 elif "o" in DeskType: FinalPrice = DrawerAmount * 30 + 140 elif "p" in DeskType: FinalPrice = DrawerAmount * 30 + 100 def Total(): print("The final price is " + FinalPrice ) DrawerAmount = Drawers() DeskType = Desk() Calculation(DrawerAmount, DeskType) FinalPrice = Total() ```
2016/09/14
[ "https://Stackoverflow.com/questions/39492631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6831132/" ]
> > I need help changing my DrawerAmount to an integer, not a string! > > > Try this: ``` v = int(DrawerAmount) ```
``` def Drawers(): draweramount = input("How many drawers are there?") print("Okay, I accept that the total amount of drawers is " + draweramount + ".") return int(draweramount) def Desk(): desktype = input("What type of wood is your desk?") print("Alright, your desk is made of " + desktype + ".") return desktype def Calculation(draweramount, desktype): if "m" in desktype: finalprice = draweramount * 30 + 180 elif "o" in desktype: finalprice = draweramount * 30 + 140 elif "p" in desktype: finalprice = draweramount * 30 + 100 return finalprice draweramount = Drawers() desktype = Desk() finalprice=Calculation(draweramount, desktype) print("The final price is ",Calculation(draweramount,desktype) ) ``` > > You haven't specified the output in case the input is not "P" or "M" or "O". > Have your functions in small letters and include **\_** whenever its a combination of two or more words > eg. function\_name() > > >
9,060,217
I have a iPhone app and want to develop iPad app with the same name. I want to design different UI for ipad app including new features. So my question is, Will i have to make changes in iPhone app for iPad or need to create another new app for iPad ? Note: Name of both app will be same. Please explain how should i perform it.
2012/01/30
[ "https://Stackoverflow.com/questions/9060217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1177466/" ]
What you describe is perfectly possible with [universal apps](http://developer.apple.com/library/ios/ipad/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/AdvancedAppTricks/AdvancedAppTricks.html). You will have to maintain to completely different hierachies of NIBs/Storyboards for your UI though. Controllers can be reused if you stick to the MVC pattern.
Here is a [tutorial](http://www.slideshare.net/cliffmcc/creating-a-universal-ios-application) for creating universal app(both for iPad and iPhone). Go through it
9,060,217
I have a iPhone app and want to develop iPad app with the same name. I want to design different UI for ipad app including new features. So my question is, Will i have to make changes in iPhone app for iPad or need to create another new app for iPad ? Note: Name of both app will be same. Please explain how should i perform it.
2012/01/30
[ "https://Stackoverflow.com/questions/9060217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1177466/" ]
What you describe is perfectly possible with [universal apps](http://developer.apple.com/library/ios/ipad/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/AdvancedAppTricks/AdvancedAppTricks.html). You will have to maintain to completely different hierachies of NIBs/Storyboards for your UI though. Controllers can be reused if you stick to the MVC pattern.
You can use same app for iPad but you have make different UI for iPad as size of iPhone and iPad screen is different but controllers and modal classes will remain same.
34,214,860
I have an unordered\_map with key as ULONG. I know that there can be a huge number of entries but not sure how many. So can't specify the bucket count before hand. I was expecting the time complexity for inserts to be O(1) since the keys are unique. But it seems like the inserts are taking very long time. I've read that this might be possible if there have been lots of re-hashing since the bucket count is unspecified which takes indeterministic time. Is there anything I can do to improve the time complexity of insert here. Or am I missing something?
2015/12/11
[ "https://Stackoverflow.com/questions/34214860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5666874/" ]
Couple of things that might help: 1. You can actually compute when a rehash will take place and work out if that is the issue. From [cplusplus.com](http://www.cplusplus.com/reference/unordered_map/unordered_map/insert/): "A rehash is forced if the new container size after the insertion operation would increase above its capacity threshold (calculated as the container's bucket\_count multiplied by its max\_load\_factor)." 2. Try to isolate the insert operation and see if it does indeed take as long as it seems, otherwise write a simple timer and place it at useful places in the code to see where the time is being eaten
Between [`max_load_factor`](http://www.cplusplus.com/reference/unordered_map/unordered_map/max_load_factor/) and preemptively calling [`reserve`](http://www.cplusplus.com/reference/unordered_map/unordered_map/reserve/), you should be able to both minimize rehashing, and minimize bucket collisions. Getting the balance right is mostly a matter of performance testing.
34,214,860
I have an unordered\_map with key as ULONG. I know that there can be a huge number of entries but not sure how many. So can't specify the bucket count before hand. I was expecting the time complexity for inserts to be O(1) since the keys are unique. But it seems like the inserts are taking very long time. I've read that this might be possible if there have been lots of re-hashing since the bucket count is unspecified which takes indeterministic time. Is there anything I can do to improve the time complexity of insert here. Or am I missing something?
2015/12/11
[ "https://Stackoverflow.com/questions/34214860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5666874/" ]
Couple of things that might help: 1. You can actually compute when a rehash will take place and work out if that is the issue. From [cplusplus.com](http://www.cplusplus.com/reference/unordered_map/unordered_map/insert/): "A rehash is forced if the new container size after the insertion operation would increase above its capacity threshold (calculated as the container's bucket\_count multiplied by its max\_load\_factor)." 2. Try to isolate the insert operation and see if it does indeed take as long as it seems, otherwise write a simple timer and place it at useful places in the code to see where the time is being eaten
For a start, many Standard Library implementations hash integers with an identity function, i.e. `hash(x) == x`. This is usually ok, especially if the implementation ensures the bucket count is prime (e.g. GCC), but some implementations use power-of-two bucket counts (e.g. Visual C++). You could run some numbers through your hash function and see if it's an identity function: if so, consider whether your inputs are sufficiently random for that not to matter. For example, if your numbers are all multiples of 4, then a power-of-two bucket count means you're only using a quarter of your buckets. If they tend to vary most in the high-order bits that's also a problem because bitwise-AND with a power-of-two bucket count effectively throws some number of high order bits away (for example, with 1024 buckets only the 10 least significant bits of the hash value will affect the bucket selection). A good way to check for this type of problem is to iterate over your buckets and create a histogram of the number of colliding elements, for example - given `unordered_map` `m`: ``` std::map<int, int> histogram; for (size_t i = 0; i < m.bucket_count(); ++i) ++histogram[m.bucket_size(i)]; for (auto& kv : histogram) std::cout << ".bucket_size() " << kv.first << " seen " << kv.second << " times\n"; ``` (You can see such code run [here](http://coliru.stacked-crooked.com/a/83b4cfdcfbf4b11c)). You'd expect the frequency of larger `bucket_size()` values to trail away quickly: if not, work on your hash function. On the other hand, if you've gone over-the-top and instantiated your `unordered_map` with a 512-bit cryptographic hash or something, that will unnecessarily slow down your table operations too. The strongest hash you need consider for day-to-day use with tables having less than 4 billion elements is a 32 bit murmur hash. Still, use the Standard Library provided one unless the collisions reported above are problematic. Switching to a closed addressing / open hashing hash table implementation (you could Google for one) is very likely to be dramatically faster *if* you don't have a lot of "churn": deleting hash table elements nearly as much as you insert new ones, with lookups interspersed. Closed addressing means the hash table keys are stored directly in buckets, and you get far better cache hits and much faster rehashing as the table size increases. If the values your integral keys map to are large (memory wise, as in `sizeof(My_Map::value_type)`), then do make sure the implementation's only storing pointers to them in the table itself, so the entire objects do not need to be copied during resizing. Note: the above assumes the hash table really is causing your performance problems. If there's any doubt, do use a profiler to confirm that if you haven't already.
42,478,576
I'm programming a game in C# and I'm using a SoA pattern for performance-critical components. Here's an example: ``` public class ComponentData { public int[] Ints; public float[] Floats; } ``` Ideally, I'd want other programmers to only specify this data (as above) and be done with it. However, some operations have to be done for each array, like allocating, copying, growing, etc. Right now I'm using an abstract class with abstract methods to implement those, like so: ``` public class ComponentData : BaseData { public int[] Ints; public float[] Floats; protected override void Allocate(int size) { Ints = new int[size]; Floats = new float[size]; } protected override void Copy(int source, int destination) { Ints[destination] = Ints[source]; Floats[destination] = Floats[source]; } // And so on... } ``` This requires the programmer to add all of this boilerplate code everytime she writes a new component, and every time she adds a new array. I tried figuring it out by using templates, and while this works for the AoS pattern, it doesn't do much good for SoA (having `Data : BaseData<int, float>` would be extremely vague). So I'd like to hear ideas for automatically "injecting" these arrays somewhere to reduce the extreme amount of boilerplate code.
2017/02/27
[ "https://Stackoverflow.com/questions/42478576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1757253/" ]
The idea was the following: ``` public abstract class ComponentData : BaseData { public Collection<Array> ArraysRegister { get; private set; } public int[] Ints; public float[] Floats; public ComponentData() { ArraysRegister = new Collection<Array>(); ArraysRegister.Add(this.Ints); ArraysRegister.Add(this.Floats); /* whatever you need in base class*/ } protected void Copy(int source, int destination) { for (int i = 0; i < ArraysRegister.Count; i++) { ArraysRegister[i][destination] = ArraysRegister[i][source]; } } /* All the other methods */ } public class SomeComponentData : ComponentData { // In child class you only have to define property... public decimal[] Decimals; public SomeComponentData() { // ... and add it to Register ArraysRegister.Add(this.Decimals); } // And no need to modify all the base methods } ``` It is not perfect however (something has to be done with allocation), but at least implementing child class you don't have to override all the methods of base class that deal with arrays. Is it worth doing or not depends on how much similar methods you have.
I would suggest defining a collection of all arrays used by class and then making all the necessary operations upon all of them in cycle.
56,785,717
[![enter image description here](https://i.stack.imgur.com/d34st.png)](https://i.stack.imgur.com/d34st.png) I want the icon `details` to point upward like as shown in the image. but the list of material icon has icon `details` points to downward, so how can I rotate the material icon in my flutter project, without downloading the icon image. [![enter image description here](https://i.stack.imgur.com/fZ8b1.png)](https://i.stack.imgur.com/fZ8b1.png) ```dart Column( children: <Widget>[ Container( height: 48, decoration: BoxDecoration( color: Color(0xFFFBBC05), borderRadius: BorderRadius.circular(48), boxShadow: [ BoxShadow( blurRadius: 16, offset: Offset(0, 8), color: Color(0XFFFBBC05), spreadRadius: -10) ]), child: IconButton( icon: Icon( Icons.details, color: Colors.white, ), onPressed: null, ), ), SizedBox( height: 8, ), Text( "Historical", style: TextStyle(fontFamily: 'AirbnbCerealMedium', fontSize: 12), ), ], ) ```
2019/06/27
[ "https://Stackoverflow.com/questions/56785717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5846565/" ]
You can wrap your `IconButton` in a `Transform` widget using the [rotate constructor](https://api.flutter.dev/flutter/widgets/Transform/Transform.rotate.html): ``` import 'dart:math' as math; Transform.rotate( angle: 180 * math.pi / 180, child: IconButton( icon: Icon( Icons.details, color: Colors.white, ), onPressed: null, ), ), ```
One solution could be to use the `Transform` widget. ```dart Column(children: <Widget>[ Container( height: 48, decoration: BoxDecoration( color: Color(0xFFFBBC05), borderRadius: BorderRadius.circular(48), boxShadow: [ BoxShadow( blurRadius: 16, offset: Offset(0, 8), color: Color(0XFFFBBC05), spreadRadius: -10) ]), child: Transform( //<--- This changed transform: Matrix4.rotationX(90), child: IconButton(icon: Icon(Icons.details), onPressed: () {})), ), SizedBox( height: 8, ), Text( "Historical", style: TextStyle(fontFamily: 'AirbnbCerealMedium', fontSize: 12), ), ]) ```
56,785,717
[![enter image description here](https://i.stack.imgur.com/d34st.png)](https://i.stack.imgur.com/d34st.png) I want the icon `details` to point upward like as shown in the image. but the list of material icon has icon `details` points to downward, so how can I rotate the material icon in my flutter project, without downloading the icon image. [![enter image description here](https://i.stack.imgur.com/fZ8b1.png)](https://i.stack.imgur.com/fZ8b1.png) ```dart Column( children: <Widget>[ Container( height: 48, decoration: BoxDecoration( color: Color(0xFFFBBC05), borderRadius: BorderRadius.circular(48), boxShadow: [ BoxShadow( blurRadius: 16, offset: Offset(0, 8), color: Color(0XFFFBBC05), spreadRadius: -10) ]), child: IconButton( icon: Icon( Icons.details, color: Colors.white, ), onPressed: null, ), ), SizedBox( height: 8, ), Text( "Historical", style: TextStyle(fontFamily: 'AirbnbCerealMedium', fontSize: 12), ), ], ) ```
2019/06/27
[ "https://Stackoverflow.com/questions/56785717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5846565/" ]
You can wrap your `IconButton` in a `Transform` widget using the [rotate constructor](https://api.flutter.dev/flutter/widgets/Transform/Transform.rotate.html): ``` import 'dart:math' as math; Transform.rotate( angle: 180 * math.pi / 180, child: IconButton( icon: Icon( Icons.details, color: Colors.white, ), onPressed: null, ), ), ```
If you want to rotate icons like arrow\_forward\_ios, could help following code. ``` icon: Transform.rotate( angle: 90 *math.pi /180, child: Icon(Icons.arrow_forward_ios, color: Colors.white,size: 18,),, ```
56,785,717
[![enter image description here](https://i.stack.imgur.com/d34st.png)](https://i.stack.imgur.com/d34st.png) I want the icon `details` to point upward like as shown in the image. but the list of material icon has icon `details` points to downward, so how can I rotate the material icon in my flutter project, without downloading the icon image. [![enter image description here](https://i.stack.imgur.com/fZ8b1.png)](https://i.stack.imgur.com/fZ8b1.png) ```dart Column( children: <Widget>[ Container( height: 48, decoration: BoxDecoration( color: Color(0xFFFBBC05), borderRadius: BorderRadius.circular(48), boxShadow: [ BoxShadow( blurRadius: 16, offset: Offset(0, 8), color: Color(0XFFFBBC05), spreadRadius: -10) ]), child: IconButton( icon: Icon( Icons.details, color: Colors.white, ), onPressed: null, ), ), SizedBox( height: 8, ), Text( "Historical", style: TextStyle(fontFamily: 'AirbnbCerealMedium', fontSize: 12), ), ], ) ```
2019/06/27
[ "https://Stackoverflow.com/questions/56785717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5846565/" ]
``` Transform.rotate( angle: 180 * pi / 180, child: IconButton( icon: Icon( Icons.details, color: Colors.white, ), onPressed: null, ), ), ```
One solution could be to use the `Transform` widget. ```dart Column(children: <Widget>[ Container( height: 48, decoration: BoxDecoration( color: Color(0xFFFBBC05), borderRadius: BorderRadius.circular(48), boxShadow: [ BoxShadow( blurRadius: 16, offset: Offset(0, 8), color: Color(0XFFFBBC05), spreadRadius: -10) ]), child: Transform( //<--- This changed transform: Matrix4.rotationX(90), child: IconButton(icon: Icon(Icons.details), onPressed: () {})), ), SizedBox( height: 8, ), Text( "Historical", style: TextStyle(fontFamily: 'AirbnbCerealMedium', fontSize: 12), ), ]) ```
56,785,717
[![enter image description here](https://i.stack.imgur.com/d34st.png)](https://i.stack.imgur.com/d34st.png) I want the icon `details` to point upward like as shown in the image. but the list of material icon has icon `details` points to downward, so how can I rotate the material icon in my flutter project, without downloading the icon image. [![enter image description here](https://i.stack.imgur.com/fZ8b1.png)](https://i.stack.imgur.com/fZ8b1.png) ```dart Column( children: <Widget>[ Container( height: 48, decoration: BoxDecoration( color: Color(0xFFFBBC05), borderRadius: BorderRadius.circular(48), boxShadow: [ BoxShadow( blurRadius: 16, offset: Offset(0, 8), color: Color(0XFFFBBC05), spreadRadius: -10) ]), child: IconButton( icon: Icon( Icons.details, color: Colors.white, ), onPressed: null, ), ), SizedBox( height: 8, ), Text( "Historical", style: TextStyle(fontFamily: 'AirbnbCerealMedium', fontSize: 12), ), ], ) ```
2019/06/27
[ "https://Stackoverflow.com/questions/56785717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5846565/" ]
Another solution is: ```dart RotatedBox( quarterTurns: 2, child: IconButton( icon: Icon( Icons.details, color: Colors.white, ), onPressed: null, ), ), ```
One solution could be to use the `Transform` widget. ```dart Column(children: <Widget>[ Container( height: 48, decoration: BoxDecoration( color: Color(0xFFFBBC05), borderRadius: BorderRadius.circular(48), boxShadow: [ BoxShadow( blurRadius: 16, offset: Offset(0, 8), color: Color(0XFFFBBC05), spreadRadius: -10) ]), child: Transform( //<--- This changed transform: Matrix4.rotationX(90), child: IconButton(icon: Icon(Icons.details), onPressed: () {})), ), SizedBox( height: 8, ), Text( "Historical", style: TextStyle(fontFamily: 'AirbnbCerealMedium', fontSize: 12), ), ]) ```
56,785,717
[![enter image description here](https://i.stack.imgur.com/d34st.png)](https://i.stack.imgur.com/d34st.png) I want the icon `details` to point upward like as shown in the image. but the list of material icon has icon `details` points to downward, so how can I rotate the material icon in my flutter project, without downloading the icon image. [![enter image description here](https://i.stack.imgur.com/fZ8b1.png)](https://i.stack.imgur.com/fZ8b1.png) ```dart Column( children: <Widget>[ Container( height: 48, decoration: BoxDecoration( color: Color(0xFFFBBC05), borderRadius: BorderRadius.circular(48), boxShadow: [ BoxShadow( blurRadius: 16, offset: Offset(0, 8), color: Color(0XFFFBBC05), spreadRadius: -10) ]), child: IconButton( icon: Icon( Icons.details, color: Colors.white, ), onPressed: null, ), ), SizedBox( height: 8, ), Text( "Historical", style: TextStyle(fontFamily: 'AirbnbCerealMedium', fontSize: 12), ), ], ) ```
2019/06/27
[ "https://Stackoverflow.com/questions/56785717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5846565/" ]
``` Transform.rotate( angle: 180 * pi / 180, child: IconButton( icon: Icon( Icons.details, color: Colors.white, ), onPressed: null, ), ), ```
If you want to rotate icons like arrow\_forward\_ios, could help following code. ``` icon: Transform.rotate( angle: 90 *math.pi /180, child: Icon(Icons.arrow_forward_ios, color: Colors.white,size: 18,),, ```
56,785,717
[![enter image description here](https://i.stack.imgur.com/d34st.png)](https://i.stack.imgur.com/d34st.png) I want the icon `details` to point upward like as shown in the image. but the list of material icon has icon `details` points to downward, so how can I rotate the material icon in my flutter project, without downloading the icon image. [![enter image description here](https://i.stack.imgur.com/fZ8b1.png)](https://i.stack.imgur.com/fZ8b1.png) ```dart Column( children: <Widget>[ Container( height: 48, decoration: BoxDecoration( color: Color(0xFFFBBC05), borderRadius: BorderRadius.circular(48), boxShadow: [ BoxShadow( blurRadius: 16, offset: Offset(0, 8), color: Color(0XFFFBBC05), spreadRadius: -10) ]), child: IconButton( icon: Icon( Icons.details, color: Colors.white, ), onPressed: null, ), ), SizedBox( height: 8, ), Text( "Historical", style: TextStyle(fontFamily: 'AirbnbCerealMedium', fontSize: 12), ), ], ) ```
2019/06/27
[ "https://Stackoverflow.com/questions/56785717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5846565/" ]
Another solution is: ```dart RotatedBox( quarterTurns: 2, child: IconButton( icon: Icon( Icons.details, color: Colors.white, ), onPressed: null, ), ), ```
If you want to rotate icons like arrow\_forward\_ios, could help following code. ``` icon: Transform.rotate( angle: 90 *math.pi /180, child: Icon(Icons.arrow_forward_ios, color: Colors.white,size: 18,),, ```
6,878,776
What's the difference between using XS and the Inline::C module? This was mentioned by someone in [this](https://stackoverflow.com/questions/6684351/when-should-you-use-xs) question and has made me curious.
2011/07/29
[ "https://Stackoverflow.com/questions/6878776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/474819/" ]
Inline::C generates XS and builds the generated module. It does this at run-time, although it caches past builds. Inline::C is possibly easier to use, but there are a few downsides. The first time it runs, it slows down startup, it requires permissions to create files at run-time, and it requires the tools to compile the module. Furthermore, it makes it harder for a sysadmin to install. The upside is that you can grab the generated XS and eliminate Inline::C once things start shaping up. This makes it useful for prototyping.
Inline compiles the C code at the same time when your Perl is compiled, and will be recompiled every time your source code is changed. XS is compiled once and the binary is saved as a .so file like a library. Perl is written in C so XS uses the native Perl types and subroutine mechanisms. A module using XS runs almost as efficiently as a built-in language feature. It's more difficult to do some things in Inline, and there will be a conversion step when calling or returning from your code. That being said, Inline does a good job of not recompiling when not necessary, and the conversions into and out of Inline code aren't likely to be a noticeable performance hit. Finally, writing XS assumes that you are packaging a module. There is a lot of setup and knowledge of Perl guts and module packaging required. If you just need to call a C library from Perl, you are better off using Inline.
29,946,831
I guess this question is geared more towards the language-geeks. I have the following class: ``` <?php abstract class ScopeFactory { public static function doStuff() { } } ``` Now, I'm able to call this function, like so: `ScopeFactory::doStuff()` And this works happily. I've always coded under the impression that `abstract` classes could not be used directly - and they have to be implemented by a concrete class in order to be callable. My impression of `static` is that it does not require an *instance* to be callable. Could someone explain to me why this is legal, and if it should be? I'm curious about the finer details.
2015/04/29
[ "https://Stackoverflow.com/questions/29946831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/385265/" ]
Static methods in OOP do not change internal state, therefore you can call static methods from an abstract class.
I would be surprised if this wouldn't be allowed. Abstract class assumes you cannot instantiate it. As static methods don't need a class instance, you can happily use them. Looking deeper, you could create an abstract static method and call it from your non-abstract method: ``` abstract class ScopeFactory { public static function doStuff() { static::otherStuff(); } abstract public static function otherStuff(); } ``` PHP will give you a fatal error saying you cannot call an abstract method. But also it'll give you a E\_STRICT warning saying you shouldn't create abstract static methods.
22,531,961
``` public class DetailsActivity extends Activity { private ArrayAdapter<Imageclass> adapter; ArrayList<String> imageselect = new ArrayList<String>(); private ArrayList<Imageclass> array1; private ArrayList<Imageclass> list = new ArrayList<Imageclass>(); //private ArrayList<Imageclass> array; ArrayList<String> imagetest = new ArrayList<String>(); private TextView textView1; private TextView textView2; private TextView textView3; private TextView textView4; private TextView textView5; int id; int pid; int val; int val_new; double lati; double longi; String imagename; //private ImageView image; //public static final String URL = "http://theopentutorials.com/totwp331/wp-content/uploads/totlogo.png"; ImageView image; static Bitmap bm; ProgressDialog pd; BitmapFactory.Options bmOptions; public class test extends AsyncTask<Void, Void, InputStream>{ ArrayList<Imageclass> str; private DetailsActivity activity; public test(DetailsActivity activity){ this.activity = activity; } @Override protected InputStream doInBackground(Void... params) { //String stringURL = "http://192.168.2.104:8088/Image/MyImage" + String.format("?id=%d",id); Log.e("Checking id",""+id); String stringURL = "http://megavenues.org/mobile_json/get_images" + String.format("?id=%d",id); URL url; try { stringURL=stringURL.replaceAll(" ", "%20"); url = new URL(stringURL); Log.e("URL",""+ url); URLConnection conn= url.openConnection(); Log.e("URLConnection",""+conn ); InputStream stream= conn.getInputStream(); Log.e("URLStream",""+stream ); return stream; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { Log.e("Excepiton", ""+e); e.printStackTrace(); } return null; } @Override protected void onPostExecute(InputStream result) { super.onPostExecute(result); Log.e("Result", ""+result); StringBuilder builder = new StringBuilder(); Log.e("Builder", ""+ builder); BufferedReader reader = new BufferedReader(new InputStreamReader(result)); Log.e("Reader", ""+ reader); String line = null; try { while((line = reader.readLine()) != null) { Log.e("Result11", ""+ builder.append(line)); builder.append(line); } } catch (IOException e) { e.printStackTrace(); } String jsonString = builder.toString(); Log.e("image", jsonString); try { JSONObject rootObject = new JSONObject(jsonString); Log.e("JSOnObject",""+ rootObject); JSONArray jsonArray = rootObject.getJSONArray("tbl_ads_images"); //array1.clear(); ArrayList<String> imagearray = new ArrayList<String>(); for (int index = 0; index < jsonArray.length(); index++) { Imageclass imageinstance = new Imageclass(); JSONObject object = (JSONObject) jsonArray.get(index); Log.e("Image test", "" + object); imageinstance.image = object.getString("file_name"); //### this contain the image name Log.e("Imageinstance.image",""+imageinstance.image); imagename = imageinstance.image; imagearray.add(imageinstance.image); array1.add(imageinstance); //array1.add(imagearray); Log.e("array1","test"+array1); } Log.e("IMAGES",""+array1); activity.setlist(array1); } catch (JSONException e) { Log.e("this Exception",""+ e); e.printStackTrace(); } catch (Exception e) { Log.e("NULL","NULL"+e); } // adapter.notifyDataSetChanged(); } } ``` --- ``` public class ImageDownload extends AsyncTask<String, Void, String> { protected String doInBackground(String... param) { bmOptions = new BitmapFactory.Options(); bmOptions.inSampleSize = 1; String imageUrl ="http://megavenues.com/assets/uploads/users/"+val+"/ads/thumbnail/"+Finalname; Log.e("inside img",""+Finalname); Log.e("inside img_val",""+val); Log.e("Check","check"+imageUrl); loadBitmap(imageUrl, bmOptions); return imageUrl; } protected void onPostExecute(String imageUrl) { pd.dismiss(); if (!imageUrl.equals("")) { Log.e("Test","Test"+ imageUrl.equals("")); image.setImageBitmap(bm); } else { Toast.makeText(DetailsActivity.this, "test", Toast.LENGTH_LONG) .show(); } } } public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) { InputStream in = null; try { in = OpenHttpConnection(URL); bm = BitmapFactory.decodeStream(in, null, options); in.close(); } catch (IOException e1) { } return bm; } private static InputStream OpenHttpConnection(String strURL) throws IOException { InputStream inputStream = null; URL url = new URL(strURL); URLConnection conn = url.openConnection(); try { HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setRequestMethod("GET"); httpConn.connect(); if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) { inputStream = httpConn.getInputStream(); } } catch (Exception ex) { } return inputStream; } String Finalname; //String imageUrl ="http://megavenues.com/assets/uploads/users/220/ads/thumbnail/"+Finalname; public void setlist(ArrayList<Imageclass> list) { this.list= list; Log.e("LIST",""+ this.list); String imagename1 = list.toString(); Log.e("image new value",""+imagename1); this.list= list; Log.e("testing",""+ this.list); for (int i=0; i < list.size(); i++) { Log.e("new check",""+list.get(i)); //String test2= list.get(i).toString(); imagetest.add(list.get(i).toString()); Finalname = list.get(i).toString(); getimage_name(Finalname); Log.e("Come",""+list.get(i).toString()); Log.e("Finalname",""+Finalname); } } //String imageUrl ="http://megavenues.com/assets/uploads/users/"+val+"/ads/thumbnail/"+Finalname; private void getimage_name(String finalname2) { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details); image = (ImageView)findViewById(R.id.imageView2); // getMenuInflater().inflate(R.menu.details); //R.id.textDetailPlace textView1 = (TextView)findViewById(R.id.textDetailPlace); textView2 = (TextView)findViewById(R.id.textDetailAddress ); textView3 = (TextView)findViewById(R.id.textCapacity); // textView4 = (TextView)findViewById(R.id.textDetailContactNo); textView5 = (TextView) findViewById(R.id.textViewDescription); textView1.setText(getIntent().getExtras().getString("test")); textView2.setText(getIntent().getExtras().getString("test2")); textView3.setText(getIntent().getExtras().getString("test3")); //textView4.setText(getIntent().getExtras().getString("test4")); textView5.setText(getIntent().getExtras().getString("test5")); id = getIntent().getExtras().getInt("test6"); Log.e("ID value",""+id); pid = getIntent().getExtras().getInt("test7"); Log.e("PID value",""+pid); lati = getIntent().getExtras().getDouble("testlat"); Log.e("long",""+lati); longi = getIntent().getExtras().getDouble("testlong"); Log.e("long",""+longi); val=pid; Log.e("val",""+val); ActionBar actionBar = getActionBar(); actionBar.hide(); pd = ProgressDialog.show(DetailsActivity.this, null, null,true); pd.setContentView(R.layout.progress); array1 = new ArrayList<Imageclass>(); //new test(this).execute(); new test(this).execute(); ``` --- here test asynctask is called ``` Log.e("JUST","CHECK"); Log.e("JUST","CHECK"); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } ``` --- here imageDownload asynctask is getting called:: ``` new ImageDownload().execute(); Log.e("imagename",""+imagename); } } ``` here before ImageDownload is start executing before test async task is complete and i am not able to get the status of the task can u tell how it is done
2014/03/20
[ "https://Stackoverflow.com/questions/22531961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2231384/" ]
whatever i understood from this you want to execute your ImageDownload thread after the task thread,so start the ImageDownload Thread from the onPostExecute() of your task thread
When executing an async task a new thread is started, but your current thread keeps running. It immediately runs into your thread.sleep(1000) just after starting test.async. It looks like your doing some internet downloading in test.async, and as you might have guessed, it takes longer than 1000 milliseconds (1 second). This means 1 second later, your other async is starting, before the first completed. I assume you want to stagger them. In the postExecute of the first async, you can spawn the second async. A more stylistically correct method would be to implement an interface on your activity that takes a callback on Async completion, then upon receiving the call back, launch your second async. An example of how to structure this is below. ``` interface AsyncCallback{ void onAsyncComplete(); } public class ExampleActivity extends Activity implements AsyncCallback { .... public void launchFirstAsync(){ new Task(this).execute(); } @Override public void onAsyncComplete() { //todo launch second asyncTask; } } class Task extends AsyncTask<Void, Void, Void>{ AsyncCallback cb; Task(AsyncCallback cb){ this.cb = cb; } @Override protected Void doInBackground(Void... params) { // TODO Auto-generated method stub return null; } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); cb.onAsyncComplete(); } ``` }
22,531,961
``` public class DetailsActivity extends Activity { private ArrayAdapter<Imageclass> adapter; ArrayList<String> imageselect = new ArrayList<String>(); private ArrayList<Imageclass> array1; private ArrayList<Imageclass> list = new ArrayList<Imageclass>(); //private ArrayList<Imageclass> array; ArrayList<String> imagetest = new ArrayList<String>(); private TextView textView1; private TextView textView2; private TextView textView3; private TextView textView4; private TextView textView5; int id; int pid; int val; int val_new; double lati; double longi; String imagename; //private ImageView image; //public static final String URL = "http://theopentutorials.com/totwp331/wp-content/uploads/totlogo.png"; ImageView image; static Bitmap bm; ProgressDialog pd; BitmapFactory.Options bmOptions; public class test extends AsyncTask<Void, Void, InputStream>{ ArrayList<Imageclass> str; private DetailsActivity activity; public test(DetailsActivity activity){ this.activity = activity; } @Override protected InputStream doInBackground(Void... params) { //String stringURL = "http://192.168.2.104:8088/Image/MyImage" + String.format("?id=%d",id); Log.e("Checking id",""+id); String stringURL = "http://megavenues.org/mobile_json/get_images" + String.format("?id=%d",id); URL url; try { stringURL=stringURL.replaceAll(" ", "%20"); url = new URL(stringURL); Log.e("URL",""+ url); URLConnection conn= url.openConnection(); Log.e("URLConnection",""+conn ); InputStream stream= conn.getInputStream(); Log.e("URLStream",""+stream ); return stream; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { Log.e("Excepiton", ""+e); e.printStackTrace(); } return null; } @Override protected void onPostExecute(InputStream result) { super.onPostExecute(result); Log.e("Result", ""+result); StringBuilder builder = new StringBuilder(); Log.e("Builder", ""+ builder); BufferedReader reader = new BufferedReader(new InputStreamReader(result)); Log.e("Reader", ""+ reader); String line = null; try { while((line = reader.readLine()) != null) { Log.e("Result11", ""+ builder.append(line)); builder.append(line); } } catch (IOException e) { e.printStackTrace(); } String jsonString = builder.toString(); Log.e("image", jsonString); try { JSONObject rootObject = new JSONObject(jsonString); Log.e("JSOnObject",""+ rootObject); JSONArray jsonArray = rootObject.getJSONArray("tbl_ads_images"); //array1.clear(); ArrayList<String> imagearray = new ArrayList<String>(); for (int index = 0; index < jsonArray.length(); index++) { Imageclass imageinstance = new Imageclass(); JSONObject object = (JSONObject) jsonArray.get(index); Log.e("Image test", "" + object); imageinstance.image = object.getString("file_name"); //### this contain the image name Log.e("Imageinstance.image",""+imageinstance.image); imagename = imageinstance.image; imagearray.add(imageinstance.image); array1.add(imageinstance); //array1.add(imagearray); Log.e("array1","test"+array1); } Log.e("IMAGES",""+array1); activity.setlist(array1); } catch (JSONException e) { Log.e("this Exception",""+ e); e.printStackTrace(); } catch (Exception e) { Log.e("NULL","NULL"+e); } // adapter.notifyDataSetChanged(); } } ``` --- ``` public class ImageDownload extends AsyncTask<String, Void, String> { protected String doInBackground(String... param) { bmOptions = new BitmapFactory.Options(); bmOptions.inSampleSize = 1; String imageUrl ="http://megavenues.com/assets/uploads/users/"+val+"/ads/thumbnail/"+Finalname; Log.e("inside img",""+Finalname); Log.e("inside img_val",""+val); Log.e("Check","check"+imageUrl); loadBitmap(imageUrl, bmOptions); return imageUrl; } protected void onPostExecute(String imageUrl) { pd.dismiss(); if (!imageUrl.equals("")) { Log.e("Test","Test"+ imageUrl.equals("")); image.setImageBitmap(bm); } else { Toast.makeText(DetailsActivity.this, "test", Toast.LENGTH_LONG) .show(); } } } public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) { InputStream in = null; try { in = OpenHttpConnection(URL); bm = BitmapFactory.decodeStream(in, null, options); in.close(); } catch (IOException e1) { } return bm; } private static InputStream OpenHttpConnection(String strURL) throws IOException { InputStream inputStream = null; URL url = new URL(strURL); URLConnection conn = url.openConnection(); try { HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setRequestMethod("GET"); httpConn.connect(); if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) { inputStream = httpConn.getInputStream(); } } catch (Exception ex) { } return inputStream; } String Finalname; //String imageUrl ="http://megavenues.com/assets/uploads/users/220/ads/thumbnail/"+Finalname; public void setlist(ArrayList<Imageclass> list) { this.list= list; Log.e("LIST",""+ this.list); String imagename1 = list.toString(); Log.e("image new value",""+imagename1); this.list= list; Log.e("testing",""+ this.list); for (int i=0; i < list.size(); i++) { Log.e("new check",""+list.get(i)); //String test2= list.get(i).toString(); imagetest.add(list.get(i).toString()); Finalname = list.get(i).toString(); getimage_name(Finalname); Log.e("Come",""+list.get(i).toString()); Log.e("Finalname",""+Finalname); } } //String imageUrl ="http://megavenues.com/assets/uploads/users/"+val+"/ads/thumbnail/"+Finalname; private void getimage_name(String finalname2) { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details); image = (ImageView)findViewById(R.id.imageView2); // getMenuInflater().inflate(R.menu.details); //R.id.textDetailPlace textView1 = (TextView)findViewById(R.id.textDetailPlace); textView2 = (TextView)findViewById(R.id.textDetailAddress ); textView3 = (TextView)findViewById(R.id.textCapacity); // textView4 = (TextView)findViewById(R.id.textDetailContactNo); textView5 = (TextView) findViewById(R.id.textViewDescription); textView1.setText(getIntent().getExtras().getString("test")); textView2.setText(getIntent().getExtras().getString("test2")); textView3.setText(getIntent().getExtras().getString("test3")); //textView4.setText(getIntent().getExtras().getString("test4")); textView5.setText(getIntent().getExtras().getString("test5")); id = getIntent().getExtras().getInt("test6"); Log.e("ID value",""+id); pid = getIntent().getExtras().getInt("test7"); Log.e("PID value",""+pid); lati = getIntent().getExtras().getDouble("testlat"); Log.e("long",""+lati); longi = getIntent().getExtras().getDouble("testlong"); Log.e("long",""+longi); val=pid; Log.e("val",""+val); ActionBar actionBar = getActionBar(); actionBar.hide(); pd = ProgressDialog.show(DetailsActivity.this, null, null,true); pd.setContentView(R.layout.progress); array1 = new ArrayList<Imageclass>(); //new test(this).execute(); new test(this).execute(); ``` --- here test asynctask is called ``` Log.e("JUST","CHECK"); Log.e("JUST","CHECK"); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } ``` --- here imageDownload asynctask is getting called:: ``` new ImageDownload().execute(); Log.e("imagename",""+imagename); } } ``` here before ImageDownload is start executing before test async task is complete and i am not able to get the status of the task can u tell how it is done
2014/03/20
[ "https://Stackoverflow.com/questions/22531961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2231384/" ]
whatever i understood from this you want to execute your ImageDownload thread after the task thread,so start the ImageDownload Thread from the onPostExecute() of your task thread
Have a look here, This Help me for same..Pass your url to `GetTemplateImageController` and get the result in `Bitmap` array GetTemplateImageController Class: ``` public class GetTemplateImageController extends AsyncTask<String, Void, Bitmap[]> { Context mcontext; private ProgressDialog pDialog; public static String[] imageurls; public static Bitmap bm[]=new Bitmap[15]; // URL to get JSON private static final String url= "http://xxx.xxx.xxx.xxx/image_master.php?"; private static final String TEMPLATE = "Template_images"; private static final String IMAGEURLS = "tempimagename"; // JSONArray JSONArray loginjsonarray=null; //result from url public GetTemplateImageController(Context c) { this.mcontext=c; } protected void onPreExecute() { // Showing progress dialog super.onPreExecute(); pDialog=new ProgressDialog(mcontext); pDialog.setMessage("Loading"); pDialog.setCancelable(true); pDialog.setIndeterminate(true); pDialog.show(); } protected Bitmap[] doInBackground(String... arg) { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("templateMasterId",arg[0].toString())); // Creating service handler class instance ServiceHandler sh = new ServiceHandler(); // Making a request to url and getting response String jsonstr = sh.makeServiceCall(url, ServiceHandler.POST, params); Log.d("Response: ", ">"+jsonstr); if(jsonstr!=null) { try { JSONObject jsonObj =new JSONObject(jsonstr); loginjsonarray=jsonObj.getJSONArray(TEMPLATE); imageurls=new String[loginjsonarray.length()]; for(int i=0;i<loginjsonarray.length();i++) { JSONObject l=loginjsonarray.getJSONObject(i); imageurls[i]=l.getString(IMAGEURLS); } for(int i=0;i<imageurls.length;i++){ bm[i]=DownloadImage(imageurls[i]); } }catch(JSONException e){ e.printStackTrace(); } }else{ Toast.makeText(mcontext,"Check your Internet Connection",Toast.LENGTH_SHORT).show(); } return bm; } public Bitmap DownloadImage(String STRURL) { Bitmap bitmap = null; InputStream in = null; try { int response = -1; URL url = new URL(STRURL); URLConnection conn = url.openConnection(); if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection"); try{ HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect(); response = httpConn.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } }catch(Exception ex) { throw new IOException("Error connecting"); } bitmap = BitmapFactory.decodeStream(in); in.close(); }catch (IOException e1) { e1.printStackTrace(); } return bitmap; } protected void onPostExecute(Integer result) { // Dismiss the progress dialog pDialog.dismiss(); if(result != null) Toast.makeText(mcontext,"Download complete", Toast.LENGTH_SHORT).show(); //} } } ``` ServiceHandler Class: ``` public class ServiceHandler { static String response = null; public final static int GET = 1; public final static int POST = 2; public String makeServiceCall(String url, int method) { return this.makeServiceCall(url, method, null); } /** * Making service call * @url - url to make request * @method - http request method * @params - http request params * */ public String makeServiceCall(String url, int method, List<NameValuePair> params) { try { DefaultHttpClient httpClient=new DefaultHttpClient(); HttpEntity httpEntity=null; HttpResponse httpResponse=null; // Checking http request method type if(method==POST){ HttpPost httpPost=new HttpPost(url); if(params!=null) { //adding post params httpPost.setEntity(new UrlEncodedFormEntity(params)); } httpResponse=httpClient.execute(httpPost); } else if(method==GET) { // appending params to url if(params!=null) { String paramString=URLEncodedUtils.format(params, "utf-8"); url +="?"+paramString; } HttpGet httpGet=new HttpGet(url); httpResponse=httpClient.execute(httpGet); } httpEntity=httpResponse.getEntity(); response=EntityUtils.toString(httpEntity); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return response; } } ```
22,531,961
``` public class DetailsActivity extends Activity { private ArrayAdapter<Imageclass> adapter; ArrayList<String> imageselect = new ArrayList<String>(); private ArrayList<Imageclass> array1; private ArrayList<Imageclass> list = new ArrayList<Imageclass>(); //private ArrayList<Imageclass> array; ArrayList<String> imagetest = new ArrayList<String>(); private TextView textView1; private TextView textView2; private TextView textView3; private TextView textView4; private TextView textView5; int id; int pid; int val; int val_new; double lati; double longi; String imagename; //private ImageView image; //public static final String URL = "http://theopentutorials.com/totwp331/wp-content/uploads/totlogo.png"; ImageView image; static Bitmap bm; ProgressDialog pd; BitmapFactory.Options bmOptions; public class test extends AsyncTask<Void, Void, InputStream>{ ArrayList<Imageclass> str; private DetailsActivity activity; public test(DetailsActivity activity){ this.activity = activity; } @Override protected InputStream doInBackground(Void... params) { //String stringURL = "http://192.168.2.104:8088/Image/MyImage" + String.format("?id=%d",id); Log.e("Checking id",""+id); String stringURL = "http://megavenues.org/mobile_json/get_images" + String.format("?id=%d",id); URL url; try { stringURL=stringURL.replaceAll(" ", "%20"); url = new URL(stringURL); Log.e("URL",""+ url); URLConnection conn= url.openConnection(); Log.e("URLConnection",""+conn ); InputStream stream= conn.getInputStream(); Log.e("URLStream",""+stream ); return stream; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { Log.e("Excepiton", ""+e); e.printStackTrace(); } return null; } @Override protected void onPostExecute(InputStream result) { super.onPostExecute(result); Log.e("Result", ""+result); StringBuilder builder = new StringBuilder(); Log.e("Builder", ""+ builder); BufferedReader reader = new BufferedReader(new InputStreamReader(result)); Log.e("Reader", ""+ reader); String line = null; try { while((line = reader.readLine()) != null) { Log.e("Result11", ""+ builder.append(line)); builder.append(line); } } catch (IOException e) { e.printStackTrace(); } String jsonString = builder.toString(); Log.e("image", jsonString); try { JSONObject rootObject = new JSONObject(jsonString); Log.e("JSOnObject",""+ rootObject); JSONArray jsonArray = rootObject.getJSONArray("tbl_ads_images"); //array1.clear(); ArrayList<String> imagearray = new ArrayList<String>(); for (int index = 0; index < jsonArray.length(); index++) { Imageclass imageinstance = new Imageclass(); JSONObject object = (JSONObject) jsonArray.get(index); Log.e("Image test", "" + object); imageinstance.image = object.getString("file_name"); //### this contain the image name Log.e("Imageinstance.image",""+imageinstance.image); imagename = imageinstance.image; imagearray.add(imageinstance.image); array1.add(imageinstance); //array1.add(imagearray); Log.e("array1","test"+array1); } Log.e("IMAGES",""+array1); activity.setlist(array1); } catch (JSONException e) { Log.e("this Exception",""+ e); e.printStackTrace(); } catch (Exception e) { Log.e("NULL","NULL"+e); } // adapter.notifyDataSetChanged(); } } ``` --- ``` public class ImageDownload extends AsyncTask<String, Void, String> { protected String doInBackground(String... param) { bmOptions = new BitmapFactory.Options(); bmOptions.inSampleSize = 1; String imageUrl ="http://megavenues.com/assets/uploads/users/"+val+"/ads/thumbnail/"+Finalname; Log.e("inside img",""+Finalname); Log.e("inside img_val",""+val); Log.e("Check","check"+imageUrl); loadBitmap(imageUrl, bmOptions); return imageUrl; } protected void onPostExecute(String imageUrl) { pd.dismiss(); if (!imageUrl.equals("")) { Log.e("Test","Test"+ imageUrl.equals("")); image.setImageBitmap(bm); } else { Toast.makeText(DetailsActivity.this, "test", Toast.LENGTH_LONG) .show(); } } } public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) { InputStream in = null; try { in = OpenHttpConnection(URL); bm = BitmapFactory.decodeStream(in, null, options); in.close(); } catch (IOException e1) { } return bm; } private static InputStream OpenHttpConnection(String strURL) throws IOException { InputStream inputStream = null; URL url = new URL(strURL); URLConnection conn = url.openConnection(); try { HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setRequestMethod("GET"); httpConn.connect(); if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) { inputStream = httpConn.getInputStream(); } } catch (Exception ex) { } return inputStream; } String Finalname; //String imageUrl ="http://megavenues.com/assets/uploads/users/220/ads/thumbnail/"+Finalname; public void setlist(ArrayList<Imageclass> list) { this.list= list; Log.e("LIST",""+ this.list); String imagename1 = list.toString(); Log.e("image new value",""+imagename1); this.list= list; Log.e("testing",""+ this.list); for (int i=0; i < list.size(); i++) { Log.e("new check",""+list.get(i)); //String test2= list.get(i).toString(); imagetest.add(list.get(i).toString()); Finalname = list.get(i).toString(); getimage_name(Finalname); Log.e("Come",""+list.get(i).toString()); Log.e("Finalname",""+Finalname); } } //String imageUrl ="http://megavenues.com/assets/uploads/users/"+val+"/ads/thumbnail/"+Finalname; private void getimage_name(String finalname2) { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details); image = (ImageView)findViewById(R.id.imageView2); // getMenuInflater().inflate(R.menu.details); //R.id.textDetailPlace textView1 = (TextView)findViewById(R.id.textDetailPlace); textView2 = (TextView)findViewById(R.id.textDetailAddress ); textView3 = (TextView)findViewById(R.id.textCapacity); // textView4 = (TextView)findViewById(R.id.textDetailContactNo); textView5 = (TextView) findViewById(R.id.textViewDescription); textView1.setText(getIntent().getExtras().getString("test")); textView2.setText(getIntent().getExtras().getString("test2")); textView3.setText(getIntent().getExtras().getString("test3")); //textView4.setText(getIntent().getExtras().getString("test4")); textView5.setText(getIntent().getExtras().getString("test5")); id = getIntent().getExtras().getInt("test6"); Log.e("ID value",""+id); pid = getIntent().getExtras().getInt("test7"); Log.e("PID value",""+pid); lati = getIntent().getExtras().getDouble("testlat"); Log.e("long",""+lati); longi = getIntent().getExtras().getDouble("testlong"); Log.e("long",""+longi); val=pid; Log.e("val",""+val); ActionBar actionBar = getActionBar(); actionBar.hide(); pd = ProgressDialog.show(DetailsActivity.this, null, null,true); pd.setContentView(R.layout.progress); array1 = new ArrayList<Imageclass>(); //new test(this).execute(); new test(this).execute(); ``` --- here test asynctask is called ``` Log.e("JUST","CHECK"); Log.e("JUST","CHECK"); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } ``` --- here imageDownload asynctask is getting called:: ``` new ImageDownload().execute(); Log.e("imagename",""+imagename); } } ``` here before ImageDownload is start executing before test async task is complete and i am not able to get the status of the task can u tell how it is done
2014/03/20
[ "https://Stackoverflow.com/questions/22531961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2231384/" ]
Over time there have been several changes to the way Android deals with AsyncTasks that run concurrently. In very old Android versions (pre-1.6 afaik) multiple AsyncTasks were executed in sequence. That behavior has been changed to run the AsyncTasks in parallel up until Android 2.3. Beginning with Android 3.0 the the Android team decided that people were not careful enough with synchronizing the tasks that run in parallel and switched the default behavior back to sequential execution. Internally the AsyncTask uses an ExecutionService that can be configured to run in sequence (default) or in parallel as required: ``` ImageLoader imageLoader = new ImageLoader( imageView ); imageLoader.executeOnExecutor( AsyncTask.THREAD_POOL_EXECUTOR, "http://url.com/image.png" ); ```
When executing an async task a new thread is started, but your current thread keeps running. It immediately runs into your thread.sleep(1000) just after starting test.async. It looks like your doing some internet downloading in test.async, and as you might have guessed, it takes longer than 1000 milliseconds (1 second). This means 1 second later, your other async is starting, before the first completed. I assume you want to stagger them. In the postExecute of the first async, you can spawn the second async. A more stylistically correct method would be to implement an interface on your activity that takes a callback on Async completion, then upon receiving the call back, launch your second async. An example of how to structure this is below. ``` interface AsyncCallback{ void onAsyncComplete(); } public class ExampleActivity extends Activity implements AsyncCallback { .... public void launchFirstAsync(){ new Task(this).execute(); } @Override public void onAsyncComplete() { //todo launch second asyncTask; } } class Task extends AsyncTask<Void, Void, Void>{ AsyncCallback cb; Task(AsyncCallback cb){ this.cb = cb; } @Override protected Void doInBackground(Void... params) { // TODO Auto-generated method stub return null; } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); cb.onAsyncComplete(); } ``` }
22,531,961
``` public class DetailsActivity extends Activity { private ArrayAdapter<Imageclass> adapter; ArrayList<String> imageselect = new ArrayList<String>(); private ArrayList<Imageclass> array1; private ArrayList<Imageclass> list = new ArrayList<Imageclass>(); //private ArrayList<Imageclass> array; ArrayList<String> imagetest = new ArrayList<String>(); private TextView textView1; private TextView textView2; private TextView textView3; private TextView textView4; private TextView textView5; int id; int pid; int val; int val_new; double lati; double longi; String imagename; //private ImageView image; //public static final String URL = "http://theopentutorials.com/totwp331/wp-content/uploads/totlogo.png"; ImageView image; static Bitmap bm; ProgressDialog pd; BitmapFactory.Options bmOptions; public class test extends AsyncTask<Void, Void, InputStream>{ ArrayList<Imageclass> str; private DetailsActivity activity; public test(DetailsActivity activity){ this.activity = activity; } @Override protected InputStream doInBackground(Void... params) { //String stringURL = "http://192.168.2.104:8088/Image/MyImage" + String.format("?id=%d",id); Log.e("Checking id",""+id); String stringURL = "http://megavenues.org/mobile_json/get_images" + String.format("?id=%d",id); URL url; try { stringURL=stringURL.replaceAll(" ", "%20"); url = new URL(stringURL); Log.e("URL",""+ url); URLConnection conn= url.openConnection(); Log.e("URLConnection",""+conn ); InputStream stream= conn.getInputStream(); Log.e("URLStream",""+stream ); return stream; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { Log.e("Excepiton", ""+e); e.printStackTrace(); } return null; } @Override protected void onPostExecute(InputStream result) { super.onPostExecute(result); Log.e("Result", ""+result); StringBuilder builder = new StringBuilder(); Log.e("Builder", ""+ builder); BufferedReader reader = new BufferedReader(new InputStreamReader(result)); Log.e("Reader", ""+ reader); String line = null; try { while((line = reader.readLine()) != null) { Log.e("Result11", ""+ builder.append(line)); builder.append(line); } } catch (IOException e) { e.printStackTrace(); } String jsonString = builder.toString(); Log.e("image", jsonString); try { JSONObject rootObject = new JSONObject(jsonString); Log.e("JSOnObject",""+ rootObject); JSONArray jsonArray = rootObject.getJSONArray("tbl_ads_images"); //array1.clear(); ArrayList<String> imagearray = new ArrayList<String>(); for (int index = 0; index < jsonArray.length(); index++) { Imageclass imageinstance = new Imageclass(); JSONObject object = (JSONObject) jsonArray.get(index); Log.e("Image test", "" + object); imageinstance.image = object.getString("file_name"); //### this contain the image name Log.e("Imageinstance.image",""+imageinstance.image); imagename = imageinstance.image; imagearray.add(imageinstance.image); array1.add(imageinstance); //array1.add(imagearray); Log.e("array1","test"+array1); } Log.e("IMAGES",""+array1); activity.setlist(array1); } catch (JSONException e) { Log.e("this Exception",""+ e); e.printStackTrace(); } catch (Exception e) { Log.e("NULL","NULL"+e); } // adapter.notifyDataSetChanged(); } } ``` --- ``` public class ImageDownload extends AsyncTask<String, Void, String> { protected String doInBackground(String... param) { bmOptions = new BitmapFactory.Options(); bmOptions.inSampleSize = 1; String imageUrl ="http://megavenues.com/assets/uploads/users/"+val+"/ads/thumbnail/"+Finalname; Log.e("inside img",""+Finalname); Log.e("inside img_val",""+val); Log.e("Check","check"+imageUrl); loadBitmap(imageUrl, bmOptions); return imageUrl; } protected void onPostExecute(String imageUrl) { pd.dismiss(); if (!imageUrl.equals("")) { Log.e("Test","Test"+ imageUrl.equals("")); image.setImageBitmap(bm); } else { Toast.makeText(DetailsActivity.this, "test", Toast.LENGTH_LONG) .show(); } } } public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) { InputStream in = null; try { in = OpenHttpConnection(URL); bm = BitmapFactory.decodeStream(in, null, options); in.close(); } catch (IOException e1) { } return bm; } private static InputStream OpenHttpConnection(String strURL) throws IOException { InputStream inputStream = null; URL url = new URL(strURL); URLConnection conn = url.openConnection(); try { HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setRequestMethod("GET"); httpConn.connect(); if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) { inputStream = httpConn.getInputStream(); } } catch (Exception ex) { } return inputStream; } String Finalname; //String imageUrl ="http://megavenues.com/assets/uploads/users/220/ads/thumbnail/"+Finalname; public void setlist(ArrayList<Imageclass> list) { this.list= list; Log.e("LIST",""+ this.list); String imagename1 = list.toString(); Log.e("image new value",""+imagename1); this.list= list; Log.e("testing",""+ this.list); for (int i=0; i < list.size(); i++) { Log.e("new check",""+list.get(i)); //String test2= list.get(i).toString(); imagetest.add(list.get(i).toString()); Finalname = list.get(i).toString(); getimage_name(Finalname); Log.e("Come",""+list.get(i).toString()); Log.e("Finalname",""+Finalname); } } //String imageUrl ="http://megavenues.com/assets/uploads/users/"+val+"/ads/thumbnail/"+Finalname; private void getimage_name(String finalname2) { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details); image = (ImageView)findViewById(R.id.imageView2); // getMenuInflater().inflate(R.menu.details); //R.id.textDetailPlace textView1 = (TextView)findViewById(R.id.textDetailPlace); textView2 = (TextView)findViewById(R.id.textDetailAddress ); textView3 = (TextView)findViewById(R.id.textCapacity); // textView4 = (TextView)findViewById(R.id.textDetailContactNo); textView5 = (TextView) findViewById(R.id.textViewDescription); textView1.setText(getIntent().getExtras().getString("test")); textView2.setText(getIntent().getExtras().getString("test2")); textView3.setText(getIntent().getExtras().getString("test3")); //textView4.setText(getIntent().getExtras().getString("test4")); textView5.setText(getIntent().getExtras().getString("test5")); id = getIntent().getExtras().getInt("test6"); Log.e("ID value",""+id); pid = getIntent().getExtras().getInt("test7"); Log.e("PID value",""+pid); lati = getIntent().getExtras().getDouble("testlat"); Log.e("long",""+lati); longi = getIntent().getExtras().getDouble("testlong"); Log.e("long",""+longi); val=pid; Log.e("val",""+val); ActionBar actionBar = getActionBar(); actionBar.hide(); pd = ProgressDialog.show(DetailsActivity.this, null, null,true); pd.setContentView(R.layout.progress); array1 = new ArrayList<Imageclass>(); //new test(this).execute(); new test(this).execute(); ``` --- here test asynctask is called ``` Log.e("JUST","CHECK"); Log.e("JUST","CHECK"); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } ``` --- here imageDownload asynctask is getting called:: ``` new ImageDownload().execute(); Log.e("imagename",""+imagename); } } ``` here before ImageDownload is start executing before test async task is complete and i am not able to get the status of the task can u tell how it is done
2014/03/20
[ "https://Stackoverflow.com/questions/22531961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2231384/" ]
Over time there have been several changes to the way Android deals with AsyncTasks that run concurrently. In very old Android versions (pre-1.6 afaik) multiple AsyncTasks were executed in sequence. That behavior has been changed to run the AsyncTasks in parallel up until Android 2.3. Beginning with Android 3.0 the the Android team decided that people were not careful enough with synchronizing the tasks that run in parallel and switched the default behavior back to sequential execution. Internally the AsyncTask uses an ExecutionService that can be configured to run in sequence (default) or in parallel as required: ``` ImageLoader imageLoader = new ImageLoader( imageView ); imageLoader.executeOnExecutor( AsyncTask.THREAD_POOL_EXECUTOR, "http://url.com/image.png" ); ```
Have a look here, This Help me for same..Pass your url to `GetTemplateImageController` and get the result in `Bitmap` array GetTemplateImageController Class: ``` public class GetTemplateImageController extends AsyncTask<String, Void, Bitmap[]> { Context mcontext; private ProgressDialog pDialog; public static String[] imageurls; public static Bitmap bm[]=new Bitmap[15]; // URL to get JSON private static final String url= "http://xxx.xxx.xxx.xxx/image_master.php?"; private static final String TEMPLATE = "Template_images"; private static final String IMAGEURLS = "tempimagename"; // JSONArray JSONArray loginjsonarray=null; //result from url public GetTemplateImageController(Context c) { this.mcontext=c; } protected void onPreExecute() { // Showing progress dialog super.onPreExecute(); pDialog=new ProgressDialog(mcontext); pDialog.setMessage("Loading"); pDialog.setCancelable(true); pDialog.setIndeterminate(true); pDialog.show(); } protected Bitmap[] doInBackground(String... arg) { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("templateMasterId",arg[0].toString())); // Creating service handler class instance ServiceHandler sh = new ServiceHandler(); // Making a request to url and getting response String jsonstr = sh.makeServiceCall(url, ServiceHandler.POST, params); Log.d("Response: ", ">"+jsonstr); if(jsonstr!=null) { try { JSONObject jsonObj =new JSONObject(jsonstr); loginjsonarray=jsonObj.getJSONArray(TEMPLATE); imageurls=new String[loginjsonarray.length()]; for(int i=0;i<loginjsonarray.length();i++) { JSONObject l=loginjsonarray.getJSONObject(i); imageurls[i]=l.getString(IMAGEURLS); } for(int i=0;i<imageurls.length;i++){ bm[i]=DownloadImage(imageurls[i]); } }catch(JSONException e){ e.printStackTrace(); } }else{ Toast.makeText(mcontext,"Check your Internet Connection",Toast.LENGTH_SHORT).show(); } return bm; } public Bitmap DownloadImage(String STRURL) { Bitmap bitmap = null; InputStream in = null; try { int response = -1; URL url = new URL(STRURL); URLConnection conn = url.openConnection(); if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection"); try{ HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect(); response = httpConn.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } }catch(Exception ex) { throw new IOException("Error connecting"); } bitmap = BitmapFactory.decodeStream(in); in.close(); }catch (IOException e1) { e1.printStackTrace(); } return bitmap; } protected void onPostExecute(Integer result) { // Dismiss the progress dialog pDialog.dismiss(); if(result != null) Toast.makeText(mcontext,"Download complete", Toast.LENGTH_SHORT).show(); //} } } ``` ServiceHandler Class: ``` public class ServiceHandler { static String response = null; public final static int GET = 1; public final static int POST = 2; public String makeServiceCall(String url, int method) { return this.makeServiceCall(url, method, null); } /** * Making service call * @url - url to make request * @method - http request method * @params - http request params * */ public String makeServiceCall(String url, int method, List<NameValuePair> params) { try { DefaultHttpClient httpClient=new DefaultHttpClient(); HttpEntity httpEntity=null; HttpResponse httpResponse=null; // Checking http request method type if(method==POST){ HttpPost httpPost=new HttpPost(url); if(params!=null) { //adding post params httpPost.setEntity(new UrlEncodedFormEntity(params)); } httpResponse=httpClient.execute(httpPost); } else if(method==GET) { // appending params to url if(params!=null) { String paramString=URLEncodedUtils.format(params, "utf-8"); url +="?"+paramString; } HttpGet httpGet=new HttpGet(url); httpResponse=httpClient.execute(httpGet); } httpEntity=httpResponse.getEntity(); response=EntityUtils.toString(httpEntity); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return response; } } ```
15,644,353
I have a database access, and one of this field is double-precision. Normally if i set in the textbox 1.71 or 1,71 the field in database should contain 1.71. But if i execute query the value of acces'field is 171 !!. ``` public const string QUERY = @"UPDATE TBLART SET TBLART.COST = @cost WHERE TBLART.CODE= '1'"; var param = new DynamicParameters(); var cost = totalCost.Replace(',', '.'); //totalCost is a textbox param.Add("cost", Double.Parse(cost), DbType.Double); gsmconn.Execute(QUERY, param); ``` What i wrong ? Thanks.
2013/03/26
[ "https://Stackoverflow.com/questions/15644353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2204958/" ]
`double.Parse` will use the current thread's culture by default. I *suspect* your current culture uses "." as a grouping separator. Two options: * Continue to use `Replace` as you are already doing, but then specify `CultureInfo.InvariantCulture` when parsing * Remove the replacement, and just use the current thread's culture when parsing the original value. This relies on the culture being appropriate for the user, but is probably a better solution when that's the case. (Otherwise someone entering "1,234.56" will get a parse error when they expected a value of "just a bit more than 1234".)
If I remember correctly in windows forms you can bind an double property to a textbox and it will automatically take care of parsing and converting. You should not manually do parsing from string to double. That problem is already solved fro you by the .NET framework. Another suggestion, your data access code should not do any parsing. That should be done in some higher layer. But better leave it to the framework.
1,590,898
For Christmas my family have been playing a card game called [Wordaround](http://thinkfun.com/products/wordaround/). The rules are irrelevant here, other than the fact that each card has $3$ words printed on it and there are $100$ cards. In each "game" of Wordaround, we use exactly one word from each of the $100$ cards. The method by which words are chosen is not important here, so assume each word is chosen with uniform probability of $\frac13$. Now, after a few games of this, we realised that we were encountering the same words again and again. This is not hard to believe, since it's possible to exhaust all words in exactly $3$ games, though it's quite unlikely. Being obsessed with maths, I was naturally inclined to try and work out the expected value of the number of "unused" words after $n$ games. I began with a simple argument, but was unconvinced, so tried a more complex argument. The two answers agreed, but I'm not sure I'm entirely correct in my first derivation. ### My First Attempt: Words are Events The simple (perhaps naive) approach I took first was to consider the $300$ words as true/false events for each game. In each game, a word has $\frac23$ probability of **not** being picked. Since choices of a word in successive games are independent events, we can then say that after $n$ games, a word has a $(\frac23)^n$ chance of **not** being chosen. So the expected value of unused words is just the sum of all the individual expected values i.e. $300(\frac23)^n$. This agrees with a simple observation: after one round, there will be exactly $200$ unused words. But I think I made a subtle mistake here, because choosing one word on a card mutually excludes the choice of the other two. ### My Second Attempt: Words left per Card To ease my worries I calculated the probability a different way. Consider a card and ask: how many unused words are left on it after $n$ games? Clearly after $1$ game, there are exactly $2$ unused words. Let's assume $n \geq 1$. Then there are either $0, 1$ or $2$ unused words. The expected number of unused words is the probability that there is $1$ unused word plus twice the probability that there are $2$ unused words. The probability of two unused words is the chance that the same word was chosen for all games i.e. for the remaining $n-1$ games the first word repeats, yielding: $$\left(\frac13\right)^{n-1} = \frac{3}{3^n}$$ The probability of $1$ unused card can be calculated by considering first the number of $n$ digit ternary numbers that use only two digits- excluding numbers that use only one digit. This number is $3 \cdot (2^n - 2)$. That is: $3$ ways to exclude a number, and $(2^n - 2)$ subsets of $n$ corresponding to the choices for the indices of the smaller number remaining, excluding the $2$ corner cases where all indices are the same digit. Dividing this by the total number of ternary $n$ digit numbers gives us the probability. $$\dfrac{3 \cdot (2^n - 2)}{3^n}$$ So the expected value per card is: $$2 \cdot \frac{3}{3^n} + \dfrac{3 \cdot (2^n - 2)}{3^n} = \dfrac{3 \cdot (2^n)}{3^n}$$ Multiplying by $100$ cards and we get: $$300(\frac23)^n$$ Which agrees with the answer derived by the first method. ### Question Are both methods valid paths to the correct answer or is the first answer just a fluke?
2015/12/27
[ "https://math.stackexchange.com/questions/1590898", "https://math.stackexchange.com", "https://math.stackexchange.com/users/252983/" ]
The first answer has correct reasoning, as well. Your doubt stems from the (true) fact that the survival of one word is not independent from survival of another on the same card. But expectation values are additive, even when the underlying variables are not independent.
Both are valid ways to get the answer. A valid justification for the first method goes as follows: For each of the 300 words ($1 \leq i \leq 300$), let $X\_{i,n}$ be the random variable which is $1$ if the $i$-th word has never been chosen after $n$ games, and $0$ otherwise. As you stated, $E(X\_{i,n}) =\text{Pr}(X\_{i,n} = 1) = \left(\frac{2}{3}\right)^n.$ Now, the number of unused words after $n$ games is clearly $\sum\_{i=1}^{300} X\_{i,n}$, hence the expected number of unused words is $$E\left(\sum\_{i=1}^{300}X\_{i,n}\right) = \sum\_{i=1}^{300}E(X\_{i,n}) = 300 \left(\frac{2}{3}\right)^n$$
24,297,726
im trying to write a program which create a new text file with asp. it is giving Microsoft VBScript runtime error '800a0035'. However when I change the file for the line ``` Set f=fs.GetFile("c:\vie4.txt") ``` to an existing file it does not give this error. > > Hello ! > > > Welcome to my Web site! > > > Microsoft VBScript runtime error '800a0035' > > > File not found > > > /simple2.asp, line 33 > > > ``` <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" method ="post" action = "simple2.asp" runat="server" > <div> <input id="Text1" type="text" value = "fname" /> <input id="Text2" type="text" value ="lname" /> </div> </form> <% response.write(request.querystring("fname")) response.write(" " & request.querystring("lname")) fname = request.querystring("fname") lname = request.querystring("lname") response.write("<p>Hello " & fname & " " & lname & "!</p>") response.write("<p>Welcome to my Web site!</p>") Dim fs,f Set fs=Server.CreateObject("Scripting.FileSystemObject") Set f=fs.GetFile("c:\vie4.txt") Response.Write("File created: " & f.DateCreated) set f=nothing set fs=nothing %> </body> </html> ```
2014/06/19
[ "https://Stackoverflow.com/questions/24297726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2439070/" ]
When in doubt, read the [documentation](http://msdn.microsoft.com/en-us/library/sheydkke%28v=vs.84%29.aspx). `GetFile` doesn't create files. Use [`CreateTextFile`](http://msdn.microsoft.com/en-us/library/5t9b5c0c%28v=vs.84%29.aspx) for that: ``` ... filename = "c:\vie4.txt" If Not fs.FileExists(filename) Then fs.CreateTextFile filename Set f = fs.GetFile(filename) ... ```
```html Table1.Rows.Clear(); List<Knjiga> knjige = new List<Knjiga>(); XmlDocument doc = new XmlDocument(); doc.Load(Server.MapPath("biblioteka.xml")); foreach (XmlElement el in doc.GetElementsByTagName("knjiga")) { knjige.Add(new Knjiga() { ISBN = el.GetAttribute("ISBN"), Naslov = el.GetAttribute("naslov"), Stanje = Int32.Parse(el.GetAttribute("stanje")), Citano = Int32.Parse(el.GetAttribute("citano")) }); } knjige = knjige.OrderByDescending(d => d.Citano).ToList(); foreach (var knjiga in knjige) { TableRow tr = new TableRow(); // Cells TableCell isbn = new TableCell(); TableCell naslov = new TableCell(); TableCell stanje = new TableCell(); TableCell citano = new TableCell(); isbn.Text = knjiga.ISBN; naslov.Text = knjiga.Naslov; stanje.Text = knjiga.Stanje.ToString(); citano.Text = knjiga.Citano.ToString(); tr.Cells.AddRange(new TableCell[]{ isbn, naslov, stanje, citano}); Table1.Rows.Add(tr); } ```
3,858,377
Here is the question: A rectangular prism has a volume of $720$ cm$^3$ and a surface area of $666$ cm$^2$. If the lengths of all its edges are integers, what is the length of the longest edge? This is from a previously timed competition. Quick answers will be the most helpful. You can set up equations and use Vieta's formulas to get $x^3+bx^2+333x-720$. How do I solve the problem after this?
2020/10/09
[ "https://math.stackexchange.com/questions/3858377", "https://math.stackexchange.com", "https://math.stackexchange.com/users/807252/" ]
We have $$xyz=720$$ and $$xy+xz+yz=333,$$ where $x$, $y$ and $z$ are naturals. Now, let $x\geq y\geq z$. Thus, $$720\geq z^3,$$ which gives $$1\leq z\leq8$$ and $z=3$ is valid, which gives $x=16$ and $y=15.$
Factorize $720$ as a product of three factors, then pairwise, their products sum to $333$. Once you see this, you know that two of the factors must be odd. From trial and error, I get the longest side to be $16$, with the other two sides being $3$ and $15$. Verifying: $$3\times15\times16=720,\qquad 2\times(3\times15+15\times16+16\times3)=666.$$
5,713,276
I have a function in PHP that retrieves all the directories and files from a given path. This returns me an array like: ``` array( "dirname1" => array( "dirname2" => array( "dirname3" => array( "0" => "file1", "1" => "file2", "2" => "file3" ), "0" => "file4", "1" => "file5", "2" => "file6", "dirname4" => array( "0" => "file7", "1" => "file8" ) ), "0" => "file9", "1" => "file10" ), "0" => "file11", "1" => "file12", "2" => "file13" ); ``` What I finally need is a multidimensional (don't know if is the exactly word) list with `<ul />` and `<li />` generated with XSLT 1.0 from a XML file, like: ``` <ul> <li class="dirname"> dirname1 <ul> <li class="dirname"> Dirname2 <ul> <li class="dirname"> Dirname3 <ul> <li>file1</li> <li>file2</li> <li>file3</li> </ul> </li> <li>file4</li> <li>file5</li> <li>file6</li> <li class="dirname"> dirname4 <ul> <li>file7</li> <li>file8</li> </ul> </li> </ul> </li> <li>file9</li> <li>file10</li> </ul> </li> <li>file11</li> <li>file12</li> <li>file13</li> </ul> ``` And finally, inside every `<li />` I need the path in a `<a />`, like: ``` <li class="dirname"><a href="/dirname1">dirname1</a></li> <li><a href="/dirname1/dirname2/dirname3/file1">file1</a></li> <li><a href="/dirname1/file9">file9</a></li> ``` Actually I don't have the XML that I need to convert because I don't know what can be a nice structure for then convert it to XSLT 1.0. I have the paths inside the `<a />`. I can do it with PHP if necessary and I can detect in PHP when it is a directory or when not and we can also add something on the XML to detect the `class="dirname"`. I hope I've given sufficient information to understand me. Thank you in advance!
2011/04/19
[ "https://Stackoverflow.com/questions/5713276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/569908/" ]
While I like the DBC idea, AOP is the wrong weapon for this task in my opinion. Aspects need special infrastructure complicating your build process Aspects enforcing contracts need to run in production code, with the risk of actually introducing bugs instead of preventing them. Aspects do not provide any compile time security, which is really the main aim of DBC. Don't know about C# but ther doesn't seem to be a mature DBC option available in java land. Therefore I tend to implement contracts as tests. Although not as often as I should
Look at [Contract4j](http://www.polyglotprogramming.com/contract4j) which uses AspectJ to inforce DBC.
5,713,276
I have a function in PHP that retrieves all the directories and files from a given path. This returns me an array like: ``` array( "dirname1" => array( "dirname2" => array( "dirname3" => array( "0" => "file1", "1" => "file2", "2" => "file3" ), "0" => "file4", "1" => "file5", "2" => "file6", "dirname4" => array( "0" => "file7", "1" => "file8" ) ), "0" => "file9", "1" => "file10" ), "0" => "file11", "1" => "file12", "2" => "file13" ); ``` What I finally need is a multidimensional (don't know if is the exactly word) list with `<ul />` and `<li />` generated with XSLT 1.0 from a XML file, like: ``` <ul> <li class="dirname"> dirname1 <ul> <li class="dirname"> Dirname2 <ul> <li class="dirname"> Dirname3 <ul> <li>file1</li> <li>file2</li> <li>file3</li> </ul> </li> <li>file4</li> <li>file5</li> <li>file6</li> <li class="dirname"> dirname4 <ul> <li>file7</li> <li>file8</li> </ul> </li> </ul> </li> <li>file9</li> <li>file10</li> </ul> </li> <li>file11</li> <li>file12</li> <li>file13</li> </ul> ``` And finally, inside every `<li />` I need the path in a `<a />`, like: ``` <li class="dirname"><a href="/dirname1">dirname1</a></li> <li><a href="/dirname1/dirname2/dirname3/file1">file1</a></li> <li><a href="/dirname1/file9">file9</a></li> ``` Actually I don't have the XML that I need to convert because I don't know what can be a nice structure for then convert it to XSLT 1.0. I have the paths inside the `<a />`. I can do it with PHP if necessary and I can detect in PHP when it is a directory or when not and we can also add something on the XML to detect the `class="dirname"`. I hope I've given sufficient information to understand me. Thank you in advance!
2011/04/19
[ "https://Stackoverflow.com/questions/5713276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/569908/" ]
C# (actually .NET) supports DBC using the [Code Contracts](http://msdn.microsoft.com/en-us/devlabs/dd491992) framework and tooling. It provides an API for declaring your pre-, post- and invariant conditions, plus the ability to perform runtime checks, static checks and generate documentation. The framework is built-in into .NET framework 4.
Look at [Contract4j](http://www.polyglotprogramming.com/contract4j) which uses AspectJ to inforce DBC.
4,446,331
In Shiryaev's book *problems in probability*, an upper bound for binomial coefficients is shown in section 1.2.1: $$\binom{m+n}{n}\le(1+m/n)^n(1+n/m)^m.$$ It seems that this bound is sharper than the well known result that $\binom{n}{k}\le (ne/k)^k$ because $(1+n/m)^m = (1+m/n)^{(m/n)n} < e^n$. Could anyone tell me how to derive this tighter bound?
2022/05/09
[ "https://math.stackexchange.com/questions/4446331", "https://math.stackexchange.com", "https://math.stackexchange.com/users/1055875/" ]
If you multiply the inequality by $n^nm^m$, the RHS can be expanded with the binomial theorem, and the LHS will be but one of the terms of the resulting sum.
*If you want a tighter bound.* Using my answer [here](https://math.stackexchange.com/questions/4434203/the-lower-bound-about-the-binomial-coefficient/4434415#4434415) $$\binom{m+n}{n}\le \frac{1}{\sqrt{2 \pi }}\sqrt{\frac{1}{m}+\frac{1}{n}}\,\frac{(m+n)^{m+n} }{m^m\, n^n }$$ Comparing $$\frac{\frac{1}{\sqrt{2 \pi }}\sqrt{\frac{1}{m}+\frac{1}{n}}\,\frac{(m+n)^{m+n} }{m^m\, n^n } } {\left(1+\frac{m}{n}\right)^n \left(1+\frac{n}{m}\right)^m }=\sqrt{\frac{\frac{1}{m}+\frac{1}{n}}{2 \pi }} \ll1$$
381,242
I'd like to know how to configure Apache 2 to specify the same error documents for both 403 (Forbidden) and 404 (Page Not Found) responses. I assume there is a directive to add to httpd.conf, but not sure what it is. Most of the tutorials I see for doing this are based around .htaccess files, but I want to set this directive globally.
2012/04/19
[ "https://serverfault.com/questions/381242", "https://serverfault.com", "https://serverfault.com/users/93209/" ]
Add in a block like: ``` ErrorDocument 403 /40x.html ErrorDocument 404 /40x.html ``` into the server or virtualhost configuration. Here's the relevant section of the documentation: <http://httpd.apache.org/docs/2.2/mod/core.html#errordocument>
You can set this globally in httpd.conf with the [ErrorDocument](http://httpd.apache.org/docs/2.0/mod/core.html#errordocument) directive ``` ErrorDocument 404 /error.html ErrorDocument 403 /error.html ```
62,282,625
I have a Vue application which communicates with API (using axios requests) and return error(s). It works fine if I get only one error, for example when response is like this: `{"error":"passwords.token"}` When i'm getting cumulated errors like this: ``` {"message":"The given data was invalid.", "errors":{ "password":["The password confirmation does not match."]} } ``` Here is my code of my Vue component and method resetPassword() ``` methods: { resetPassword () { this.$vs.loading() const payload = { userDetails: { email: this.email, password: this.password, password_confirmation: this.password_confirmation, token: this.token } } this.$store.dispatch('auth/resetPassword', payload) .then((response) => { this.$vs.loading.close() this.$vs.notify({ time: 10000, title: 'Authentication Success', text: response.message.data.message, iconPack: 'feather', icon: 'icon-success-circle', color: 'success' }) }) .catch(error => { this.$vs.loading.close() this.$vs.notify({ time: 6000, title: 'Authentication Error', text: error.message, iconPack: 'feather', icon: 'icon-alert-circle', color: 'danger' }) }) }, }, ```
2020/06/09
[ "https://Stackoverflow.com/questions/62282625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4276819/" ]
What your are literally trying to do, introducing arbitrary scopes for types, can be accomplished via a *TypeScript* namespace. ``` declare namespace myNamespace { type IntermediaryType = { decisiveKey: true, mutatedKey: (params: any) => void, } | { decisiveKey: false, mutatedKey?: false, } interface IntermediaryType2 { foo?: string, bar?: boolean, } export type FinalType = IntermediaryType & IntermediaryType2; } const Foo = (param: myNamespace.FinalType) => {} Foo({ decisiveKey: true, mutatedKey: () => {}, }); ``` However, if you are writing modern code, and therefore using modules, namespaces should almost always be avoided. Fortunately, if you're are using modules the solution is even simpler; don't export the intermediate types. ``` type IntermediaryType = { decisiveKey: true, mutatedKey: (params: any) => void, } | { decisiveKey: false, mutatedKey?: false, } interface IntermediaryType2 { foo?: string, bar?: boolean, } export type FinalType = IntermediaryType & IntermediaryType2; export const Foo = (param: FinalType) => {} Foo({ decisiveKey: true, mutatedKey: () => {}, }); ```
I'm not sure about your preface > > due to it's complexity, this type required the declaration of intermediary types > > > this compiles ``` type FinalType = ( | { decisiveKey: true; mutatedKey: (params: any) => void; } | { decisiveKey: false; mutatedKey?: false; } ) & { foo?: string; bar?: boolean; }; const Foo = (param: FinalType) => {}; Foo({ decisiveKey: true, mutatedKey: () => {} }); ``` Hope this helps.
25,339,838
I would like to automatically `include/require` all `.php` files under all directories. For example: (Directory structure) ``` -[ classes --[ loader (directory) ---[ plugin.class.php --[ main.class.php --[ database.class.php ``` I need a function that automatically loads all files that end in `.php` I have tried all-sorts: ``` $scan = scandir('classes/'); foreach ($scan as $class) { if (strpos($class, '.class.php') !== false) { include($scan . $class); } } ```
2014/08/16
[ "https://Stackoverflow.com/questions/25339838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3947035/" ]
If the php files you want to include are PHP classes, then you should use [PHP Autoloader](http://php.net/manual/en/language.oop5.autoload.php) It's not a safe practice to include all php files in all directories automatically. Performance might be degraded if you're including unnecessary files. Here's the code that should work (I have not tested it): ``` $scan = scandir('classes/'); foreach ($scan as $class) { if (strpos($class, '.class.php') !== false) { include('classes/' . $class); } } ``` If you want recursive include [RecursiveIteratorIterator will help you](https://stackoverflow.com/a/5893774/1294631).
One that I use is ``` function fileLoader($dir) { $files = scandir($dir); foreach ($files as $file) { if ($file == '.' || $file == '..') { continue; } $path = $dir . '/' . $file; if (is_dir($path)) { __DIR__.$path; } else { require_once $path; } } } # calling the function fileLoader('mydirectory') ```
25,339,838
I would like to automatically `include/require` all `.php` files under all directories. For example: (Directory structure) ``` -[ classes --[ loader (directory) ---[ plugin.class.php --[ main.class.php --[ database.class.php ``` I need a function that automatically loads all files that end in `.php` I have tried all-sorts: ``` $scan = scandir('classes/'); foreach ($scan as $class) { if (strpos($class, '.class.php') !== false) { include($scan . $class); } } ```
2014/08/16
[ "https://Stackoverflow.com/questions/25339838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3947035/" ]
Well, if you want to include all php files with a certain ending even in subdirectories, you have to make a recursive function. Something like this: ``` function load_classphp($directory) { if(is_dir($directory)) { $scan = scandir($directory); unset($scan[0], $scan[1]); //unset . and .. foreach($scan as $file) { if(is_dir($directory."/".$file)) { load_classphp($directory."/".$file); } else { if(strpos($file, '.class.php') !== false) { include_once($directory."/".$file); } } } } } load_classphp('./classes'); ```
If the php files you want to include are PHP classes, then you should use [PHP Autoloader](http://php.net/manual/en/language.oop5.autoload.php) It's not a safe practice to include all php files in all directories automatically. Performance might be degraded if you're including unnecessary files. Here's the code that should work (I have not tested it): ``` $scan = scandir('classes/'); foreach ($scan as $class) { if (strpos($class, '.class.php') !== false) { include('classes/' . $class); } } ``` If you want recursive include [RecursiveIteratorIterator will help you](https://stackoverflow.com/a/5893774/1294631).
25,339,838
I would like to automatically `include/require` all `.php` files under all directories. For example: (Directory structure) ``` -[ classes --[ loader (directory) ---[ plugin.class.php --[ main.class.php --[ database.class.php ``` I need a function that automatically loads all files that end in `.php` I have tried all-sorts: ``` $scan = scandir('classes/'); foreach ($scan as $class) { if (strpos($class, '.class.php') !== false) { include($scan . $class); } } ```
2014/08/16
[ "https://Stackoverflow.com/questions/25339838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3947035/" ]
This is probably the simplest way to recursively find patterned files: ``` $dir = new RecursiveDirectoryIterator('classes/'); $iter = new RecursiveIteratorIterator($dir); $files = new RegexIterator($iter, '/^.+\.class\.php$/', RecursiveRegexIterator::GET_MATCH); // an Iterator, not an array foreach ( $files as $file ) { include $file; // $file includes `classes/` } ``` `RecursiveDirectoryIterator` is a tricky beast, so learning all about it is probably not doable. The interwebs has many specific examples though. The trick is to search for it.
``` function autoload( $path ) { $items = glob( $path . DIRECTORY_SEPARATOR . "*" ); foreach( $items as $item ) { $isPhp = pathinfo( $item )["extension"] === "php"; if ( is_file( $item ) && $isPhp ) { require_once $item; } elseif ( is_dir( $item ) ) { autoload( $item ); } } } autoload( dirname( __FILE__ ) . DIRECTORY_SEPARATOR . "classes" ); ```
25,339,838
I would like to automatically `include/require` all `.php` files under all directories. For example: (Directory structure) ``` -[ classes --[ loader (directory) ---[ plugin.class.php --[ main.class.php --[ database.class.php ``` I need a function that automatically loads all files that end in `.php` I have tried all-sorts: ``` $scan = scandir('classes/'); foreach ($scan as $class) { if (strpos($class, '.class.php') !== false) { include($scan . $class); } } ```
2014/08/16
[ "https://Stackoverflow.com/questions/25339838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3947035/" ]
Well, if you want to include all php files with a certain ending even in subdirectories, you have to make a recursive function. Something like this: ``` function load_classphp($directory) { if(is_dir($directory)) { $scan = scandir($directory); unset($scan[0], $scan[1]); //unset . and .. foreach($scan as $file) { if(is_dir($directory."/".$file)) { load_classphp($directory."/".$file); } else { if(strpos($file, '.class.php') !== false) { include_once($directory."/".$file); } } } } } load_classphp('./classes'); ```
An easy way : a simple function using `RecursiveDirectoryIterator` instead of `glob()`. ``` function include_dir_r( $dir_path ) { $path = realpath( $dir_path ); $objects = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator( $path ), \RecursiveIteratorIterator::SELF_FIRST ); foreach( $objects as $name => $object ) { if( $object->getFilename() !== "." && $object->getFilename() !== ".." ) { if( !is_dir( $name ) ){ include_once $name; } } } } ```
25,339,838
I would like to automatically `include/require` all `.php` files under all directories. For example: (Directory structure) ``` -[ classes --[ loader (directory) ---[ plugin.class.php --[ main.class.php --[ database.class.php ``` I need a function that automatically loads all files that end in `.php` I have tried all-sorts: ``` $scan = scandir('classes/'); foreach ($scan as $class) { if (strpos($class, '.class.php') !== false) { include($scan . $class); } } ```
2014/08/16
[ "https://Stackoverflow.com/questions/25339838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3947035/" ]
This is probably the simplest way to recursively find patterned files: ``` $dir = new RecursiveDirectoryIterator('classes/'); $iter = new RecursiveIteratorIterator($dir); $files = new RegexIterator($iter, '/^.+\.class\.php$/', RecursiveRegexIterator::GET_MATCH); // an Iterator, not an array foreach ( $files as $file ) { include $file; // $file includes `classes/` } ``` `RecursiveDirectoryIterator` is a tricky beast, so learning all about it is probably not doable. The interwebs has many specific examples though. The trick is to search for it.
One that I use is ``` function fileLoader($dir) { $files = scandir($dir); foreach ($files as $file) { if ($file == '.' || $file == '..') { continue; } $path = $dir . '/' . $file; if (is_dir($path)) { __DIR__.$path; } else { require_once $path; } } } # calling the function fileLoader('mydirectory') ```
25,339,838
I would like to automatically `include/require` all `.php` files under all directories. For example: (Directory structure) ``` -[ classes --[ loader (directory) ---[ plugin.class.php --[ main.class.php --[ database.class.php ``` I need a function that automatically loads all files that end in `.php` I have tried all-sorts: ``` $scan = scandir('classes/'); foreach ($scan as $class) { if (strpos($class, '.class.php') !== false) { include($scan . $class); } } ```
2014/08/16
[ "https://Stackoverflow.com/questions/25339838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3947035/" ]
Well, if you want to include all php files with a certain ending even in subdirectories, you have to make a recursive function. Something like this: ``` function load_classphp($directory) { if(is_dir($directory)) { $scan = scandir($directory); unset($scan[0], $scan[1]); //unset . and .. foreach($scan as $file) { if(is_dir($directory."/".$file)) { load_classphp($directory."/".$file); } else { if(strpos($file, '.class.php') !== false) { include_once($directory."/".$file); } } } } } load_classphp('./classes'); ```
``` $dir = new RecursiveDirectoryIterator('change this to your custom root directory'); foreach (new RecursiveIteratorIterator($dir) as $file) { if (!is_dir($file)) { if( fnmatch('*.php', $file) ) // you can change the file extension to any that you require. /* do anything here */ } } ```
25,339,838
I would like to automatically `include/require` all `.php` files under all directories. For example: (Directory structure) ``` -[ classes --[ loader (directory) ---[ plugin.class.php --[ main.class.php --[ database.class.php ``` I need a function that automatically loads all files that end in `.php` I have tried all-sorts: ``` $scan = scandir('classes/'); foreach ($scan as $class) { if (strpos($class, '.class.php') !== false) { include($scan . $class); } } ```
2014/08/16
[ "https://Stackoverflow.com/questions/25339838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3947035/" ]
Well, if you want to include all php files with a certain ending even in subdirectories, you have to make a recursive function. Something like this: ``` function load_classphp($directory) { if(is_dir($directory)) { $scan = scandir($directory); unset($scan[0], $scan[1]); //unset . and .. foreach($scan as $file) { if(is_dir($directory."/".$file)) { load_classphp($directory."/".$file); } else { if(strpos($file, '.class.php') !== false) { include_once($directory."/".$file); } } } } } load_classphp('./classes'); ```
This is probably the simplest way to recursively find patterned files: ``` $dir = new RecursiveDirectoryIterator('classes/'); $iter = new RecursiveIteratorIterator($dir); $files = new RegexIterator($iter, '/^.+\.class\.php$/', RecursiveRegexIterator::GET_MATCH); // an Iterator, not an array foreach ( $files as $file ) { include $file; // $file includes `classes/` } ``` `RecursiveDirectoryIterator` is a tricky beast, so learning all about it is probably not doable. The interwebs has many specific examples though. The trick is to search for it.
25,339,838
I would like to automatically `include/require` all `.php` files under all directories. For example: (Directory structure) ``` -[ classes --[ loader (directory) ---[ plugin.class.php --[ main.class.php --[ database.class.php ``` I need a function that automatically loads all files that end in `.php` I have tried all-sorts: ``` $scan = scandir('classes/'); foreach ($scan as $class) { if (strpos($class, '.class.php') !== false) { include($scan . $class); } } ```
2014/08/16
[ "https://Stackoverflow.com/questions/25339838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3947035/" ]
This is probably the simplest way to recursively find patterned files: ``` $dir = new RecursiveDirectoryIterator('classes/'); $iter = new RecursiveIteratorIterator($dir); $files = new RegexIterator($iter, '/^.+\.class\.php$/', RecursiveRegexIterator::GET_MATCH); // an Iterator, not an array foreach ( $files as $file ) { include $file; // $file includes `classes/` } ``` `RecursiveDirectoryIterator` is a tricky beast, so learning all about it is probably not doable. The interwebs has many specific examples though. The trick is to search for it.
An easy way : a simple function using `RecursiveDirectoryIterator` instead of `glob()`. ``` function include_dir_r( $dir_path ) { $path = realpath( $dir_path ); $objects = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator( $path ), \RecursiveIteratorIterator::SELF_FIRST ); foreach( $objects as $name => $object ) { if( $object->getFilename() !== "." && $object->getFilename() !== ".." ) { if( !is_dir( $name ) ){ include_once $name; } } } } ```
25,339,838
I would like to automatically `include/require` all `.php` files under all directories. For example: (Directory structure) ``` -[ classes --[ loader (directory) ---[ plugin.class.php --[ main.class.php --[ database.class.php ``` I need a function that automatically loads all files that end in `.php` I have tried all-sorts: ``` $scan = scandir('classes/'); foreach ($scan as $class) { if (strpos($class, '.class.php') !== false) { include($scan . $class); } } ```
2014/08/16
[ "https://Stackoverflow.com/questions/25339838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3947035/" ]
``` $dir = new RecursiveDirectoryIterator('change this to your custom root directory'); foreach (new RecursiveIteratorIterator($dir) as $file) { if (!is_dir($file)) { if( fnmatch('*.php', $file) ) // you can change the file extension to any that you require. /* do anything here */ } } ```
An easy way : a simple function using `RecursiveDirectoryIterator` instead of `glob()`. ``` function include_dir_r( $dir_path ) { $path = realpath( $dir_path ); $objects = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator( $path ), \RecursiveIteratorIterator::SELF_FIRST ); foreach( $objects as $name => $object ) { if( $object->getFilename() !== "." && $object->getFilename() !== ".." ) { if( !is_dir( $name ) ){ include_once $name; } } } } ```
25,339,838
I would like to automatically `include/require` all `.php` files under all directories. For example: (Directory structure) ``` -[ classes --[ loader (directory) ---[ plugin.class.php --[ main.class.php --[ database.class.php ``` I need a function that automatically loads all files that end in `.php` I have tried all-sorts: ``` $scan = scandir('classes/'); foreach ($scan as $class) { if (strpos($class, '.class.php') !== false) { include($scan . $class); } } ```
2014/08/16
[ "https://Stackoverflow.com/questions/25339838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3947035/" ]
This is probably the simplest way to recursively find patterned files: ``` $dir = new RecursiveDirectoryIterator('classes/'); $iter = new RecursiveIteratorIterator($dir); $files = new RegexIterator($iter, '/^.+\.class\.php$/', RecursiveRegexIterator::GET_MATCH); // an Iterator, not an array foreach ( $files as $file ) { include $file; // $file includes `classes/` } ``` `RecursiveDirectoryIterator` is a tricky beast, so learning all about it is probably not doable. The interwebs has many specific examples though. The trick is to search for it.
``` $dir = new RecursiveDirectoryIterator('change this to your custom root directory'); foreach (new RecursiveIteratorIterator($dir) as $file) { if (!is_dir($file)) { if( fnmatch('*.php', $file) ) // you can change the file extension to any that you require. /* do anything here */ } } ```
37,219,313
Given the following object: ``` scala> object P2pClient { | type Num = Double | type Weights = Array[Array[Num]] | } defined object P2pClient ``` and the following import: ``` import P2pClient._ ``` The `Weights` type *seems* to be properly understood: ``` val w: Weights = new Weights(3) w: P2pClient.Weights = Array(null, null, null) ``` But then why is it *not* working in the following construct: ``` case class SendWeightsReq(W: Weights) extends P2pReq[Weights] { | override def value() = W | } <console>:12: error: not found: type Weights case class SendWeightsReq(W: Weights) extends P2pReq[Weights] { ^ <console>:12: error: not found: type Weights case class SendWeightsReq(W: Weights) extends P2pReq[Weights] { ^ ``` Any ideas on what were happening here (/workaround) ? **Update** There appear to be significant limitations on wildcard imports int he REPL. Here is another simpler illustration: ``` scala> import reflect.runtime.universe._ import reflect.runtime.universe._ scala> trait TT { def x[T <: java.io.Serializable : TypeTag]: T } <console>:10: error: not found: type TypeTag trait TT { def x[T <: java.io.Serializable : TypeTag]: T } ^ ``` So we see that the wildcard import did *not* work. Here is the same code with the explicit package: ``` scala> trait TT { def x[T <: java.io.Serializable : reflect.runtime.universe.TypeTag]: T } defined trait TT ```
2016/05/13
[ "https://Stackoverflow.com/questions/37219313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1056563/" ]
I see the issue is due to my using the **Spark** REPL `spark-shell`. The issue is not happening in the normal Scala REPL.
Good news: your code works! Bad news: I have no idea why it doesn't work for you. Here is my REPL session; I was going to build up to your example and see what broke, but nothing did. ``` scala> object P2pClient { type Num = Int; type Weights = Array[Array[Num]] } defined object P2pClient scala> import P2pClient._ import P2pClient._ scala> val x = new Weights(3) x: Array[Array[P2pClient.Num]] = Array(null, null, null) scala> case class SendWeights(W: Weights) defined class SendWeights scala> val s = new SendWeights(new Weights(3)) s: SendWeights = SendWeights([[I@1cab0bfb) ``` Hmmm. Trivial example works. ``` scala> case class SendWeights2(w: Weights) { def dubs = w } defined class SendWeights2 ``` Works when it has a body. ``` scala> trait P2pReq[+T] { def value(): Unit } defined trait P2pReq scala> case class SendWeights3(W: Weights) extends P2pReq[Weights] { override def value() = W } defined class SendWeights3 scala> val foo = new SendWeights3(new Weights(3)) foo: SendWeights3 = SendWeights3([[I@51dcb805) res2: P2pClient.Weights = Array(null, null, null) ``` Aaaaand works when it extends a polymorphic trait and overrides one of its members. The only thing that may be different is your definition of `P2pReq`, but I don't see how that could cause one of your types to go unrecognized by the interpreter.
15,293,529
call a function continuously in c# console application. without using infinite loop and recursion because if use those then cpu usage is more.please can any one help me to solve this problem.some one suggest me to use background thread, but it doesn't call the function continuously. ``` Thread th = new Thread(//fun); th.IsBackground = true; th.start(); ```
2013/03/08
[ "https://Stackoverflow.com/questions/15293529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138896/" ]
You can not use join on update and delete queries. You have to use subqueries. > > Joins are not supported on update and delete queries because it is not > supported on all dbms. It won't be implemented in Doctrine 1 or > Doctrine 2. You can however get the same affect by using subqueries. > > > <http://www.doctrine-project.org/jira/browse/DC-646> If you are using MySQL, using subqueries will not work. You will have then to use 2 queries. > > In MySQL, you cannot modify a table and select from the same table in > a subquery > > > <http://dev.mysql.com/doc/refman/5.0/en/subqueries.html>
Doctrine DQL does not support join in update. Try doing the following : ``` $qb = $this->getEntityManager()->createQueryBuilder(); $qb ->update('MyBundle:Entity1', 'e1') ->set('e1.visibile', '1') ->where('e1.Entity2 = :id') ->setParameter("id", 123) ; ``` You can set the id, as long as it is the primary key, of the linked entity directly as if it was the entity, Doctrine will map it. I'm doing the exact same thing in my queries and it works.
15,293,529
call a function continuously in c# console application. without using infinite loop and recursion because if use those then cpu usage is more.please can any one help me to solve this problem.some one suggest me to use background thread, but it doesn't call the function continuously. ``` Thread th = new Thread(//fun); th.IsBackground = true; th.start(); ```
2013/03/08
[ "https://Stackoverflow.com/questions/15293529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138896/" ]
You can not use join on update and delete queries. You have to use subqueries. > > Joins are not supported on update and delete queries because it is not > supported on all dbms. It won't be implemented in Doctrine 1 or > Doctrine 2. You can however get the same affect by using subqueries. > > > <http://www.doctrine-project.org/jira/browse/DC-646> If you are using MySQL, using subqueries will not work. You will have then to use 2 queries. > > In MySQL, you cannot modify a table and select from the same table in > a subquery > > > <http://dev.mysql.com/doc/refman/5.0/en/subqueries.html>
try using a subquery instead [Join will not work in DQL while you re doing an update](https://stackoverflow.com/a/5598894/1427338): > > LEFT JOIN, or JOINs in particular are only supported in UPDATE > statements of MySQL. DQL abstracts a subset of common ansi sql, so > this is not possible. Try with a subselect: > > > ``` $qb = $this->getEntityManager()->createQueryBuilder(); $qb ->update('MyBundle:Entity1', 'e') ->set('e.visibile', '1') ->where('e.id IN (SELECT e1.id FROM Entity1 e1 INNER JOIN e2.Entity2 e2 WHERE e2 = :id') ->setParameter("id", 123); ```
15,293,529
call a function continuously in c# console application. without using infinite loop and recursion because if use those then cpu usage is more.please can any one help me to solve this problem.some one suggest me to use background thread, but it doesn't call the function continuously. ``` Thread th = new Thread(//fun); th.IsBackground = true; th.start(); ```
2013/03/08
[ "https://Stackoverflow.com/questions/15293529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138896/" ]
You can not use join on update and delete queries. You have to use subqueries. > > Joins are not supported on update and delete queries because it is not > supported on all dbms. It won't be implemented in Doctrine 1 or > Doctrine 2. You can however get the same affect by using subqueries. > > > <http://www.doctrine-project.org/jira/browse/DC-646> If you are using MySQL, using subqueries will not work. You will have then to use 2 queries. > > In MySQL, you cannot modify a table and select from the same table in > a subquery > > > <http://dev.mysql.com/doc/refman/5.0/en/subqueries.html>
Very old question, but do not contain an answer in full query builder. So yes, the following query is not possible to sync fields of two tables: ``` $this->createQueryBuilder('v') ->update() ->join(Pegass::class, 'p', Join::WITH, 'v.identifier = p.identifier') ->set('v.enabled', 'p.enabled') ->where('p.type = :type') ->setParameter('type', Pegass::TYPE_VOLUNTEER) ->andWhere('v.enabled <> p.enabled'); ``` The generated query do not contain the relation because of its lack of support in all dbms as explained above. They also tell you to use subqueries instead. So that's how I did the equivalent (even if using 2 queries and is less performant...): ``` foreach ([false, true] as $enabled) { $qb = $this->createQueryBuilder('v'); $sub = $this->_em->createQueryBuilder() ->select('p.identifier') ->from(Pegass::class, 'p') ->where('p.type = :type') ->andWhere('p.enabled = :enabled'); $qb ->setParameter('type', Pegass::TYPE_VOLUNTEER) ->setParameter('enabled', $enabled); $qb ->update() ->set('v.enabled', $enabled) ->where($qb->expr()->in('v.identifier', $sub->getDQL())) ->getQuery() ->execute(); } ```
35,754,539
How can we know that which type of linker(static/dynamic) our system is using? Is it decided on type of library(static/dynamic) we have used or is there any other thing?
2016/03/02
[ "https://Stackoverflow.com/questions/35754539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3765130/" ]
You have to write a nested loop to find that, ``` var keys = Object.keys(answers); var dupe = false; for(var i=0;i<keys.length;i++){ for(var j=i+1;j<keys.length;j++){ if(answers[keys[i]] === answers[keys[j]]){ dupe = true; break; } } if(dupe){ console.log("dupe value is there.."); break; } } ``` [DEMO](https://jsfiddle.net/u47px6e0/1/) ----------------------------------------
I guess you mean duplicate values and not duplicate key/value pairs. This is how I'd do it: ``` function findDuplicateValues(input) { var values = {}, key; for (key in input) { if (input.hasOwnProperty(key)) { values[input[key]] = values.hasOwnProperty(input[key]) ? values[input[key]] + 1 : 1; } } for (key in values) { if (values.hasOwnProperty(key) && values[key] > 1) { console.log('duplicate values found'); break; } } } ``` For large objects it will be quicker than the previous answer, because there are no nested loops (this will execute in linear O(n) time rather than quadratic O(n2) time).
24,497,337
I've a javascript function `setErrorImages()`, which searches all `img` tags and and gives them an `onerror` function. This works great. I also have a division `content` with dynamic content by calling de `jquery .load` function like this, which also works: ``` $("#content").load("http://example.com/otherpage.php"); ``` But when the new content (otherpage.php) was loaded into the division, the `setErrorImages()` function doesn't work on the `img`'es within the new content. I can call the `setErrorImages()` function on the otherpage.php, and everything works perfectly, but this way I have to do this on every otherpage, which are a lot. Is there a way to send a javascript file or function with the `jquery .load`, or maybe there is a way to re-execute the javascript function right after the `jquery .load`. Kind regards, Liontack --- ``` function setErrorImages(){ var images = document.getElementsByTagName("img"); for (var i = 0; i < images.length; i++) { images[i].onerror = function(){ setErrorImage(this); }; } } function setErrorImage(image){ image.onerror = null; image.src = 'http://tanuri.eu/images/error.png'; } ```
2014/06/30
[ "https://Stackoverflow.com/questions/24497337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2970516/" ]
``` $("#content").load("http://example.com/otherpage.php", setErrorImages); ``` **.load()** accepts a "complete" parameter: > > A callback function that is executed when the request completes. > > >
Firstly, I suggest using the `this` context instead of a parameter for your error handler: ``` function setErrorImage() { this.onerror = null; this.src = 'http://tanuri.eu/images/error.png'; } ``` Secondly, change `setErrorImages` to use `this` too: ``` function setErrorImages() { var images = this.getElementsByTagName('img'); for (var i = 0, n = images.length; i < n; ++i) { images[i].onerror = setErrorImage; // parameter is now implict } } ``` Note how there's now no need for a function wrapper for the `onerror` call - the browser automatically sets `this` to be the element of interest. For simpler code you could also just use jQuery to do this job for you since you already have it loaded: ``` function setErrorImages() { $('img', this).error(setErrorImage); } ``` Thirdly, use the `complete` handler of `.load`, taking advantage of the fact that it sets `this` to be the parent of the part of the DOM that just got replaced. This avoids setting the `onerror` handler on elements in the page that you already looked at. ``` $('#content').load(url, setErrorImages); ``` The only other change is that on your initial invocation you'll need to pass `document` to `setErrorImages` using `.call`: ``` setErrorImages.call(document); ```
38,976
I just started working as a QA Automation Engineer to a certain company which provides ERP and CRM services. However, I recently discovered that they have no test case documentation for the testing they do, and just report bugs. I am now having a hard time to automate their tests because I have no reference, what do you think I should do?
2019/04/30
[ "https://sqa.stackexchange.com/questions/38976", "https://sqa.stackexchange.com", "https://sqa.stackexchange.com/users/37425/" ]
Mindmap all the high-level features of the application together with business owners. Go over the map with stakeholders (e.g users, developers, managers, and sponsors). Do a risk assessment with some key people, maybe also analyze brittle areas based on defect reports. * Write automated happy-path tests for the highest risk features first. * Create a test-automation debt backlog, prioritize with stakeholders * In the meantime write automated tests for past critical defects as well. * Train developers to write automated tests for new features to stop fill the gap of missing tests.
You could tackle that from two directions. You could take the bugs and ask the people who opened the bugs how to reproduce them. There is your testcase. You can probably start automating regression tests for these bugs immediately. Or you could just write the test cases yourself based on the documents and SUT you have. Maybe there is a business capability map for which you can write happy path tests or maybe you have user stories with acceptance criteria for which test cases can be written. Or you go through the SUT and look what it should do. I usually take the approach that the test code is the test case and with a BDD framework you can more easily create test cases that are pretty readable and can be understood by the developers and management. In conclusion: Write the test cases yourself, focus on bug regression and happy path. Use a BDD framework to write test cases. Get help from people who know the features and created the bugs. See also: [xunitpatterns article.](http://xunitpatterns.com/TestAutomationRoadmap.html)
38,976
I just started working as a QA Automation Engineer to a certain company which provides ERP and CRM services. However, I recently discovered that they have no test case documentation for the testing they do, and just report bugs. I am now having a hard time to automate their tests because I have no reference, what do you think I should do?
2019/04/30
[ "https://sqa.stackexchange.com/questions/38976", "https://sqa.stackexchange.com", "https://sqa.stackexchange.com/users/37425/" ]
You could tackle that from two directions. You could take the bugs and ask the people who opened the bugs how to reproduce them. There is your testcase. You can probably start automating regression tests for these bugs immediately. Or you could just write the test cases yourself based on the documents and SUT you have. Maybe there is a business capability map for which you can write happy path tests or maybe you have user stories with acceptance criteria for which test cases can be written. Or you go through the SUT and look what it should do. I usually take the approach that the test code is the test case and with a BDD framework you can more easily create test cases that are pretty readable and can be understood by the developers and management. In conclusion: Write the test cases yourself, focus on bug regression and happy path. Use a BDD framework to write test cases. Get help from people who know the features and created the bugs. See also: [xunitpatterns article.](http://xunitpatterns.com/TestAutomationRoadmap.html)
Test Automation is not about having or not having test cases, which you can automate. This is about you deciding on **test automation strategy**. I wrote a [blog post](http://testretreat.com/2019/04/15/approach-to-test-automation/), which has several links and ideas where to start. Main idea is that you start with strategy: what do you want to automate, what kind of information you want to collect, how will you know that you automated the right thing. If you automate without strategy, you are building technical debt. I hope it helps.
38,976
I just started working as a QA Automation Engineer to a certain company which provides ERP and CRM services. However, I recently discovered that they have no test case documentation for the testing they do, and just report bugs. I am now having a hard time to automate their tests because I have no reference, what do you think I should do?
2019/04/30
[ "https://sqa.stackexchange.com/questions/38976", "https://sqa.stackexchange.com", "https://sqa.stackexchange.com/users/37425/" ]
You could tackle that from two directions. You could take the bugs and ask the people who opened the bugs how to reproduce them. There is your testcase. You can probably start automating regression tests for these bugs immediately. Or you could just write the test cases yourself based on the documents and SUT you have. Maybe there is a business capability map for which you can write happy path tests or maybe you have user stories with acceptance criteria for which test cases can be written. Or you go through the SUT and look what it should do. I usually take the approach that the test code is the test case and with a BDD framework you can more easily create test cases that are pretty readable and can be understood by the developers and management. In conclusion: Write the test cases yourself, focus on bug regression and happy path. Use a BDD framework to write test cases. Get help from people who know the features and created the bugs. See also: [xunitpatterns article.](http://xunitpatterns.com/TestAutomationRoadmap.html)
As detailed in <https://sqa.stackexchange.com/a/38917/8992> * Learn about the domain * Capture the existing functionality using a tool such as Cucumber or RSpec to document it * Make real tests described in English * Create Smoke, Happy and Sad cases
38,976
I just started working as a QA Automation Engineer to a certain company which provides ERP and CRM services. However, I recently discovered that they have no test case documentation for the testing they do, and just report bugs. I am now having a hard time to automate their tests because I have no reference, what do you think I should do?
2019/04/30
[ "https://sqa.stackexchange.com/questions/38976", "https://sqa.stackexchange.com", "https://sqa.stackexchange.com/users/37425/" ]
Mindmap all the high-level features of the application together with business owners. Go over the map with stakeholders (e.g users, developers, managers, and sponsors). Do a risk assessment with some key people, maybe also analyze brittle areas based on defect reports. * Write automated happy-path tests for the highest risk features first. * Create a test-automation debt backlog, prioritize with stakeholders * In the meantime write automated tests for past critical defects as well. * Train developers to write automated tests for new features to stop fill the gap of missing tests.
Test Automation is not about having or not having test cases, which you can automate. This is about you deciding on **test automation strategy**. I wrote a [blog post](http://testretreat.com/2019/04/15/approach-to-test-automation/), which has several links and ideas where to start. Main idea is that you start with strategy: what do you want to automate, what kind of information you want to collect, how will you know that you automated the right thing. If you automate without strategy, you are building technical debt. I hope it helps.
38,976
I just started working as a QA Automation Engineer to a certain company which provides ERP and CRM services. However, I recently discovered that they have no test case documentation for the testing they do, and just report bugs. I am now having a hard time to automate their tests because I have no reference, what do you think I should do?
2019/04/30
[ "https://sqa.stackexchange.com/questions/38976", "https://sqa.stackexchange.com", "https://sqa.stackexchange.com/users/37425/" ]
Mindmap all the high-level features of the application together with business owners. Go over the map with stakeholders (e.g users, developers, managers, and sponsors). Do a risk assessment with some key people, maybe also analyze brittle areas based on defect reports. * Write automated happy-path tests for the highest risk features first. * Create a test-automation debt backlog, prioritize with stakeholders * In the meantime write automated tests for past critical defects as well. * Train developers to write automated tests for new features to stop fill the gap of missing tests.
As detailed in <https://sqa.stackexchange.com/a/38917/8992> * Learn about the domain * Capture the existing functionality using a tool such as Cucumber or RSpec to document it * Make real tests described in English * Create Smoke, Happy and Sad cases
61,703,706
Hello I'm working with an AR Camera and once the camera identifies the anchored image it plays the video. Once the video finishes playing and return back to the camera I view the same anchored image again the video does not play. I want to be able to view the image and play the video as many times as possible. ***Here is my function to play the video.*** ``` func playVideo() { guard let videoLink = URL(string: "string") else { return } DispatchQueue.main.async { let player = AVPlayer(url: videoLink) let controller = AVPlayerViewController() controller.player = player self.present(controller, animated: true){ player.play() } } } ``` ***Here is my function to recognize the image.*** ``` func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? { if let imageAnchor = anchor as? ARImageAnchor{ switch imageAnchor.name{ case "image": playVideo() default: break } } return nil } ``` Can someone help me out or point me in the right direction to figure this out?
2020/05/09
[ "https://Stackoverflow.com/questions/61703706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11235245/" ]
For starters the logic of the function is wrong. Usually such a function should return `1` (or a positive value) that corresponds to the logical `true` or `0` that corresponds to the logical `false` when it answers to a question like "yes or no". This call ``` strcmp(string, "OH") ``` returns 0 if two strings are equal. Otherwise the function can return any positive or negative value depending on whether the first string is greater or less than the second string. Apart from this the function parameter should have the qualifier `const` because the passed string is not changed within the function. You did not reserve a memory where you are going to read a string. The declared pointer ``` char *string; ``` is uninitialized and has an indeterminate value. Thus this call ``` gets(string); ``` invokes undefined behavior. Take into account that the function `gets` is an unsafe function and is not supported by the C Standard. Instead you should use the standard C function `fgets`. And it will be much better if the function will be more generic. That is when it can check any supplied suffix of a string. Always try to write more generic functions. In this case they can be reusable. Below there is a demonstrative program that shows how the function can be defined. ``` #include <stdio.h> #include <string.h> int hydroxide( const char *s, const char *suffix ) { size_t n1 = strlen( s ); size_t n2 = strlen( suffix ); return !( n1 < n2 ) && strcmp( s + n1 - n2, suffix ) == 0; } int main(void) { enum { N = 100 }; char s[N]; while ( 1 ) { printf( "Enter a String (empty string - exit): " ); if ( fgets( s, N, stdin ) == NULL || s[0] == '\n' ) break; s[ strcspn( s, "\n" ) ] = '\0'; printf( "%s\n", hydroxide( s, "OH" ) ? "true" : "false" ); } return 0; } ``` The program output might look like ``` Enter a String (empty string - exit): brogrammerOH true Enter a String (empty string - exit): ```
Get the length of the string and check the last two characters. ``` int len = strlen(string); if(string[len-1] == 'H' && string[len-2] =='O') return -1; ```
61,703,706
Hello I'm working with an AR Camera and once the camera identifies the anchored image it plays the video. Once the video finishes playing and return back to the camera I view the same anchored image again the video does not play. I want to be able to view the image and play the video as many times as possible. ***Here is my function to play the video.*** ``` func playVideo() { guard let videoLink = URL(string: "string") else { return } DispatchQueue.main.async { let player = AVPlayer(url: videoLink) let controller = AVPlayerViewController() controller.player = player self.present(controller, animated: true){ player.play() } } } ``` ***Here is my function to recognize the image.*** ``` func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? { if let imageAnchor = anchor as? ARImageAnchor{ switch imageAnchor.name{ case "image": playVideo() default: break } } return nil } ``` Can someone help me out or point me in the right direction to figure this out?
2020/05/09
[ "https://Stackoverflow.com/questions/61703706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11235245/" ]
Your function is too complicated and it returns `0` if the suffix is `OH`. A simpler way is to compute the length of the string and if this length is at least 2, compare the last 2 characters with `'O'` and `'H'`: ```c int hydroxide(const char *string) { size_t len = strlen(string); if (len >= 2 && string[len - 2] == 'O' && string[len - 1] == 'H') return -1; else return 0; } ``` Furthermore, the `main` function has undefined behavior: `string` is an uninitialized `char` pointer: passing it to `gets()` will cause undefined behavior when `gets()` tries to write bytes to it. Note also that `gets()` is obsolete and has been removed from the latest version of the C Standard because there is no way to prevent a buffer overflow for sufficiently long input strings. Use `fgets()` instead and remove the trailing newline, if any: Here is a modified version: ```c #include <stdio.h> #include <string.h> int hydroxide(const char *string) { size_t len = strlen(string); if (len >= 2 && string[len - 2] == 'O' && string[len - 1] == 'H') return -1; else return 0; } int main() { char buf[80]; printf("Enter String: "); if (fgets(buf, sizeof buf, stdin)) { buf[strcspn(buf, "\n")] = '\0'; // strip the newline if any printf("%d\n", hydroxide(string)); } return 0; } ```
Get the length of the string and check the last two characters. ``` int len = strlen(string); if(string[len-1] == 'H' && string[len-2] =='O') return -1; ```
61,703,706
Hello I'm working with an AR Camera and once the camera identifies the anchored image it plays the video. Once the video finishes playing and return back to the camera I view the same anchored image again the video does not play. I want to be able to view the image and play the video as many times as possible. ***Here is my function to play the video.*** ``` func playVideo() { guard let videoLink = URL(string: "string") else { return } DispatchQueue.main.async { let player = AVPlayer(url: videoLink) let controller = AVPlayerViewController() controller.player = player self.present(controller, animated: true){ player.play() } } } ``` ***Here is my function to recognize the image.*** ``` func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? { if let imageAnchor = anchor as? ARImageAnchor{ switch imageAnchor.name{ case "image": playVideo() default: break } } return nil } ``` Can someone help me out or point me in the right direction to figure this out?
2020/05/09
[ "https://Stackoverflow.com/questions/61703706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11235245/" ]
For starters the logic of the function is wrong. Usually such a function should return `1` (or a positive value) that corresponds to the logical `true` or `0` that corresponds to the logical `false` when it answers to a question like "yes or no". This call ``` strcmp(string, "OH") ``` returns 0 if two strings are equal. Otherwise the function can return any positive or negative value depending on whether the first string is greater or less than the second string. Apart from this the function parameter should have the qualifier `const` because the passed string is not changed within the function. You did not reserve a memory where you are going to read a string. The declared pointer ``` char *string; ``` is uninitialized and has an indeterminate value. Thus this call ``` gets(string); ``` invokes undefined behavior. Take into account that the function `gets` is an unsafe function and is not supported by the C Standard. Instead you should use the standard C function `fgets`. And it will be much better if the function will be more generic. That is when it can check any supplied suffix of a string. Always try to write more generic functions. In this case they can be reusable. Below there is a demonstrative program that shows how the function can be defined. ``` #include <stdio.h> #include <string.h> int hydroxide( const char *s, const char *suffix ) { size_t n1 = strlen( s ); size_t n2 = strlen( suffix ); return !( n1 < n2 ) && strcmp( s + n1 - n2, suffix ) == 0; } int main(void) { enum { N = 100 }; char s[N]; while ( 1 ) { printf( "Enter a String (empty string - exit): " ); if ( fgets( s, N, stdin ) == NULL || s[0] == '\n' ) break; s[ strcspn( s, "\n" ) ] = '\0'; printf( "%s\n", hydroxide( s, "OH" ) ? "true" : "false" ); } return 0; } ``` The program output might look like ``` Enter a String (empty string - exit): brogrammerOH true Enter a String (empty string - exit): ```
Your function is too complicated and it returns `0` if the suffix is `OH`. A simpler way is to compute the length of the string and if this length is at least 2, compare the last 2 characters with `'O'` and `'H'`: ```c int hydroxide(const char *string) { size_t len = strlen(string); if (len >= 2 && string[len - 2] == 'O' && string[len - 1] == 'H') return -1; else return 0; } ``` Furthermore, the `main` function has undefined behavior: `string` is an uninitialized `char` pointer: passing it to `gets()` will cause undefined behavior when `gets()` tries to write bytes to it. Note also that `gets()` is obsolete and has been removed from the latest version of the C Standard because there is no way to prevent a buffer overflow for sufficiently long input strings. Use `fgets()` instead and remove the trailing newline, if any: Here is a modified version: ```c #include <stdio.h> #include <string.h> int hydroxide(const char *string) { size_t len = strlen(string); if (len >= 2 && string[len - 2] == 'O' && string[len - 1] == 'H') return -1; else return 0; } int main() { char buf[80]; printf("Enter String: "); if (fgets(buf, sizeof buf, stdin)) { buf[strcspn(buf, "\n")] = '\0'; // strip the newline if any printf("%d\n", hydroxide(string)); } return 0; } ```
63,170,801
So I have this issue ``` //This holds 5 messages submitted prev by the user, temporarily stored string arrayOfMessages[5]; ``` lets say ``` arrayOfMessages[0]="This is my message"//The message in the first position. ``` I need to copy `arrayOfMessages[0]` to an array of `char` like this one; ``` char message [20]; ``` I tried using `strcpy(message,arrayOfMessages[0])` but I get this error : ``` error: cannot convert 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} to 'const char*'| ``` Anyone know how I can accomplish this or if I'm doing something wrong, I cant set the string to be a const char bc the message was imputed prev by the user so it changes every time you run the program thus cannot be a constant variable.
2020/07/30
[ "https://Stackoverflow.com/questions/63170801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14020395/" ]
There are many ways of doing it By using the c\_str() function of the string class ``` string message = "This is my message"; const char *arr; arr = message.c_str(); ``` By copying all the characters from the string to the char array ``` string message = "This is my message"; char arr[200]; for(int i = 0; i < 200 && message[i] != '\0'; i++){ arr[i] = message[i]; } ``` Be careful with the array sizes if you use the second approach. You can also make it a function in order to make it easier to use ``` void copyFromStringToArr(char* arr, string str, int arrSize){ for(int i = 0; i<arrSize && str[i] != '\0'; i++){ arr[i] = str[i]; } } ``` So in your case you can just call the function like this: ``` copyFromStringToArr(message,arrayOfMessages[0],20); ``` Also I am sure there are many more ways to do it but these are the ones I would use.
To copy the contents of `std::string` into a `char[]`, use `c_str()`: ``` std::string str = "hello"; char copy[20]; strcpy(copy, str.c_str()); ``` But the datatype of `copy` must be only `char*` and not `const char*`. If you want to assign it to a `const char*`, then you can use direct assignment: ``` std::string str = "hello"; const char *copy = str.c_str(); ```