text:
Q: Error preparing transaction in JBOss PostgreSQL? When am delete the object through JPARepository  am facing the exception like max transactions hint : Make max transactions as non zero value.To fix this problem I have set the max transaction as 100 in postgre.conf and it works good . But I am not convinced with this fix and I want to know the source of this problem .
Please see the log and help me out with your suggestions.
    at com.sun.proxy.$Proxy103.deleteJurisdiction(Unknown Source)
    at com.essvote.webresults.web.controller.jurisdiction.JurisdictionControllerImpl.deleteJurisdiction(JurisdictionControllerImpl.java:217) [classes:]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_21]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_21]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_21]
    at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_21]
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) [spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745) [spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686) [spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) [spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925) [spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) [spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936) [spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doDelete(FrameworkServlet.java:860) [spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:713) [jboss-servlet-api_3.1_spec-1.0.0.Final.jar:1.0.0.Final]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812) [spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) [jboss-servlet-api_3.1_spec-1.0.0.Final.jar:1.0.0.Final]
    at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:130) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:74) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:60) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:132) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:60) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:132) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at com.essvote.webresults.web.filter.AjaxTimeoutRedirectFilter.doFilter(AjaxTimeoutRedirectFilter.java:82) [classes:]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:125) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:60) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:132) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at com.essvote.webresults.web.filter.ClientInfoFilter.doFilterInternal(ClientInfoFilter.java:63) [classes:]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:60) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:132) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at com.essvote.webresults.web.filter.ActiveJurisdictionFilter.doFilterInternal(ActiveJurisdictionFilter.java:175) [classes:]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:60) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:132) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:85) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:61) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:113) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:56) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:45) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:61) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:58) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:70) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.security.handlers.SecurityInitialHandler.handleRequest(SecurityInitialHandler.java:76) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
    at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:240) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:227) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:73) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:146) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:177) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:727) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_21]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_21]
    at java.lang.Thread.run(Thread.java:722) [rt.jar:1.7.0_21]
Caused by: org.postgresql.util.PSQLException: ERROR: maximum number of prepared transactions reached
  Hint: Increase max_prepared_transactions (currently 1).
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2161)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1890)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:560)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:403)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:331)
    at org.postgresql.xa.PGXAConnection.prepare(PGXAConnection.java:301)
    ... 122 more


text:
Q: "grep -R" replacement? I have a machine with grep installed but option -R is not compiled-in and there is also no replacement switch.
How can I replace it in bash?
I tried:
for i in `find *`; do
    grep 'pattern' $i;
done

but that is not right re-interpretation, isn't it?

A: Try piping the output of find to xargs so that grep only gets invoked a few times (xargs keeps reading input until it gets so much that more would not fit in an argument list):
find -type f | xargs grep foo

A: We usually use
find . -exec grep 'pattern' {} \;

That usually works similarly to grep -R.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Non-Persistence Field I have Items table :
Id Code   Quantity
1  Cake01 10
2  Cake02 15
3  Cake03 20

public class Items
{
    public int Id { get; set; }
    public string Code { get; set; }
    public int Quantity { get; set; }
}

Orders table :
Id ItemsId Quantity
1  1       5
2  1       3
3  2       10
4  3       2
5  3       5
6  1       2

public class Orders
{
    public int Id { get; set; }
    public int ItemsId { get; set; }
    public virtual Items Items { get; set; }
    public int Quantity { get; set; }
}

How I get remaining quantity in MVC 5? Normally, I just create view like this :
select a.Id, a.Quantity-(isnull(b.Quantity,0)) as Remaining
from Items a left join
(select ItemsId as Id, sum(Quantity) as Quantity group by ItemsId) as b
on a.Id = b.Id

Result :
Id Remaining
1  1
2  5
3  10

Is it possible to create non-persistance field in MVC 5? I have searching about this and found nothing.

A: Since each Order will have an Item associated with it via the ItemsId forigen key and Items navigational property, you should add Orders collection property to your Items entity.
public class Items
{
    public int Id { get; set; }
    public string Code { get; set; }
    public int Quantity { get; set; }

    public ICollection<Orders> Orders { set; get; }
}

Now can use a LINQ query to get the remaining quantity for each Item. I would create a view model/DTO to represent this data.
public class ProductVm
{
    public int Id { set; get; }
    public string Code { set; get; }
    public int RemainingQuantity { set; get; }
}

Now in your LINQ query, get the Items, get the sum of Quantity from each Item's Orders collection and subtract that from the Quantity property value.
var products = db.Items
                 .Select(p => new ProductVm
                               {
                                  Id = p.Id,
                                  Code = p.Code,
                                  RemainingQuantity = p.Quantity - p.Orders
                                                                    .Sum(n => n.Quantity)
                               }).ToList();

Here the type of products will be List<ProductVm>.


text:
Q: R, to get to know missing values in a column I am new to R and learning from the titanic data.
I want to know how many values are missing in a column. this is what I tried:
data = read.csv(file.path(DIR, file))

table(is.na(data$name))
table(is.na(data$cabin))

there's no missing values in the column Name.
there are 1,014 missing values in the column Cabin.
however above lines returned me:
FALSE
1309

what's the right way? thank you.

A: The file is .xls file.  We can read it with one of the packages that reads excel files
library(readxl)
data <- read_excel(file.choose())
dim(data)
#[1] 1309   14

table(is.na(data$cabin))

#  FALSE  TRUE
#  295  1014

To get the missing values in all the columns, summarise_all would be useful
library(dplyr)
data %>%
     summarise_all(funs(sum(is.na(.))))
# A tibble: 1 x 14
#    pclass survived  name   sex   age sibsp parch ticket  fare cabin embarked  boat  body home.dest
#    <int>    <int> <int> <int> <int> <int> <int>  <int> <int> <int>    <int> <int> <int>     <int>
#1      0        0     0     0   263     0     0      0     1  1014        2   823  1188       564


text:
Q: Outbound Map not being used I have a receive port. It calls a stored procedure for transport, then the receive pipeline is just passthrureceive (I tried XMLReceive, but that caused many more issues). I have a send port that has the filter set so it picks up the type of the receive port. The send port has a map and send pipeline. The map maps the xml from the receive port to a flat file schema, and then sends it to it's location. THe send pipeline has a flat file assembler.
So the map never runs. I just get errors from the send pipeline saying it can't match the document. No it can't, because it wasn't mapped. I read that you need an XML Disassembler on the recieve pipeline of the receive location. I added that, and that just started destroying my messages. They just get turned into a blank message or just a " in the message. So the XML disassembler is clearly not working right. I'm not sure what to do at this point.

A: OK, I figured it out. I have to use the XML disassembler to make the map run. The reason it was erasing my messages is, well I don't know the reason, but when I set the schema to "elementFormDefault = Qualified", it worked. I'm not really sure what that did, as I really don't have a good understanding of the whole qualified message thing, but that was the problem for me.

A: There is a wizard in Visual Studio to help you create the schemas and bindings that you use to communicate with stored procedures. I guess you didn't use that?  (Right click on the project, hit "Add", then "Add Generated Items", then "Consume Adapter Service")
I'm calling my stored procedure from an orchestration hooked to two way send/receive port. I'm using a custom WCF type port with XMLTransmit and XMLReceive for the pipelines. This seems to work fine. The caveat being it's always a bit fiddly getting WCF to work since there are so many options.

A: In order to map from one format to another on ports, you need to have MessageType promoted. In your case it can be accomplished by using XMLReceive on the receive pipeline.


text:
Q: Get response when every jQuery Ajax requests is done? I can get response when 'all' Ajax requests are done from this question.
Wait until all jQuery Ajax requests are done?
While I can't find a question to get 'every' response when each Ajax are done.
How can I do this?
Example for wait until all responses done, but I want to get response when each ajax complete.
function translate(...){
    return $.ajax({
        // settings...
    });
});

var requests = [];
translatable_fields.each(function(){
    requests.push(translate(...));
});

$.when.apply($, requests).done(function(schemas) {
     console.log("All requests complete");
    // do something...
});

A: The responses will be passed to the callback for done. Each AJAX call will get its own parameter, and each parameter will be an array of the three parts of the response: the response text, the status, and the jqXHR object associated with the AJAX call. Documentation for $.when
You can get the response texts all at once using the arguments object:
$.when.apply($, requests).done(function() {
    var responses = $.map(arguments, function(arr) { return arr[0] });
});


text:
Q: Windows 7 problem reporting tool analogue for Windows XP I am very glad that Microsoft finally included a tool like "Problem reporting tool" in Windows 7 - this is a great piece of software, which I mostly use to explain other users what needs to be done to solve / figure out a certain solution for the problem that they are having.
The problem is that this tool only works on Windows 7, however at work I am using Windows XP.
Maybe anyone knows any free similar tools for Windows XP?
Thank you in advance!

A: There only seems to be software like "Adobe Captivate" which is able to work at least similarly to Windows 7 problem reporting tool. There seems to be no freeware alternatives available.


text:
Q: Steam Installation Failure Ubuntu 16.04 I'll be honest, I don't know much about Linux; my friend who's been using it for years is teaching me, but we're both out of ideas now.
We "installed" Steam on both my Chromebook that has Ubuntu 16.04 on it and my Raspberry Pi which runs a form of Debian (which might have the same problem).
They both say that libgl1-mesa-dri:i386, libgl1-mesa-glx:i386, and libc6:i386 are missing (packages needed to be installed) when we try to launch steam on them. We've attempted to run every command we've found and it didn't work. Every time it just says it can't be located. Any help would be appreciated.
Current Status
(xenial)tex@localhost:~$ uname -m; dpkg --print-architecture; dpkg --print-foreign-architectures
aarch64
arm64
i386

My friend also says this might be helpful
(xenial)tex@localhost:~$ screenfetch -n
tex@localhost
OS: Ubuntu 16.04 xenial
Kernel: aarch64 Linux 4.4.127-13890-g6c206f1711d4
Uptime: 10h 23m
Packages: 970
Shell: bash 4.3.48
Resolution: 1280x800
DE: XFCE
WM: Xfwm4
WM Theme: Default
Xfce-dusk [GTK2]

Icon Theme: elementary-xfce-dark
Font: Sans 10
CPU: ARMv8 rev 4 (v8l) @ 1.512GHz

RAM: 1859MiB / 3813MiB

A: When I installed steam I had to install these packages using this command before installing steam
sudo apt install wget gdebi-core libgl1-mesa-dri:i386 libgl1-mesa-glx:i386

but not libc6:i386, so that might be part of gdebi-core
This is the page I followed https://linuxconfig.org/how-to-install-steam-on-ubuntu-18-04-bionic-beaver-linux
I just checked my history, on one machine I followed the Ubuntu section of that guide, which does not install those libraries, on my other machine I followed the steam section which did install those libraries. Both systems are working fine, so either set of instructions should work for you.

A: This is the friend mentioned who has "Linux experience". I'm not an expert, I just enough knowledge to guide him.
I've already told him that an ARM version doesn't exist but I'm posting this so people get a clearer answer.
The issue is Valve doesn't have a build of Steam available for ARM from what I've read from people trying to install it on ARM computers. It's only available on x86_x64. And I feel like Valve won't ever since the Steam Link is a thing. (src)
For those looking for a way to stream (Steam or not) games to an ARM computer using Ubuntu/Debian should look at Parsec or Limelight forks like Moonlight (this requires an NVIDIA GPU on the host machine!)
For those looking to play Steam games on ARM devices looks like you're out of luck until Valve releases Steam for ARM.


text:
Q: Returning ViewModel works fine in EF query returning list of entities but not while returning single entity I have a method in my Asp.Net Core Api for insert new entity which get a ViewModel as an argument and returns another ViewModel as result.
I have added Set() method as one of its properties to return list of CreditUserViewModel and it's working fine.
    public async Task<IEnumerable<CreditUserViewModel>> GetAll()
    {
        return await Task.Run(() =>
            _context.Credit
                .Select(CreditUserViewModel.Set));
    }

But while I want to return single object, I have no access to Set() method. Why?
Result ViewModel :
public class CreditUserViewModel
{
    public string PlanTitle { get; set; }
    public string CardSerial { get; set; }
    public DateTime PurchaseDate { get; set; }
    public int ValidationDays { get; set; }
    public int PaidAmount { get; set; }
    public string PurchaseCode { get; set; }
    public static CreditUserViewModel Set(Credit credit)
    {
        return new CreditUserViewModel
        {
            PlanTitle = credit.CreditPlan.Title,
            CardSerial = credit.Card.SerialNumber,
            PurchaseDate = DateTime.UtcNow,
            ValidationDays = credit.CreditPlan.ValidationDays,
            PaidAmount = credit.CreditPlan.Cost,
            PurchaseCode = credit.PurchaseCode
        };
    }
}

Add() method which I expect to return single CreditUserViewModel:
    public async Task<CreditUserViewModel> Add(CreditRegisterViewModel credit)
    {
        var newCredit = new Credit
        {
            CardId = credit.CardId,
            CreditPlanId = credit.CreditPlanId,
            PurchaseCode = credit.PurchaseCode,
            RechargeDate = DateTime.UtcNow
        };

        _context.Entry(newCredit).State = EntityState.Added;

        try
        {
            await _context.SaveChangesAsync();
        }
        catch
        {
            throw new Exception();
        }

        return new CreditUserViewModel.Set(newCredit); **// Error is in this line: The type name Set does not exist in the type CreditUserViewModel**
    }

Error message : The type name Set does not exist in the type
  CreditUserViewModel

A: Shouldn't that be something like:
public async Task<IEnumerable<CreditUserViewModel>> GetAll()
{
    var data = _context.Credit
                       .Select( c => CreditUserViewModel.Set(c) )
                       .ToList();

    return Task.FromResult(data);
}

And this
 return new CreditUserViewModel.Set(newCredit);

should be
 return CreditUserViewModel.Set(newCredit);

Since CreditUserViewModel.Set is a method, not a type, and by convention would normally be called Create as it's in lieu of a constructor.  Or implemented as an Extension method called ToViewModel() targeting the entity type, something like:
public static CreditUserViewModel ToViewModel(this CreditUser entity)
{
  ...
}


text:
Q: Retrieving MySQL data dynamically and plotting on android using retrofit and MPAndroidChart I am following to plot following this example. Things work if I have a static JSON and it will plot the data like shown in the website. However, I am retrieving data from MySQL and they are being updated every hour (I had look into this; create a button and potential to call the URL every hour), but I am not too sure if that's the efficient approach.
My question is if I have a MySQL table/data that is being every hour, how do I retrieve them and plot (retain old values as well as plot the new ones)? I have the following
Api Client with URL:
public class ApiClient {

    private static Retrofit retrofit = null;

private static OkHttpClient buildClient() {
    return new OkHttpClient
            .Builder()
            .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
            .build();
}

public static Retrofit getClient() {
    if (retrofit == null) {
        retrofit = new Retrofit.Builder()
                .client(buildClient())
                .addConverterFactory(GsonConverterFactory.create())

                /**
                 *
                 *  base url here for api
                 */

                .baseUrl("https://xxx")       //retrieve data from MySQL
                .build();
    }
    return retrofit;
}
}

MainActivity:
public class BarchartRetrofit extends AppCompatActivity {

        public ApiInterface apiInterface;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        apiInterface = ApiClient.getClient().create(ApiInterface.class);

        /**
         *  api call to get some data from server
         *
         */
        getData();

    }

    private void getData() {
        Call<PiChart> piChartCall = apiInterface.init();
        piChartCall.enqueue(new Callback<PiChart>() {
            @Override
            public void onResponse(Call<PiChart> call, Response<PiChart> response) {
                Log.d("CHART_RESPONSE", "" + response.body().getBarMonths().toString());
                setData(response.body());
            }

            @Override
            public void onFailure(Call<PiChart> call, Throwable t) {

            }
        });
    }

     private void setData(PiChart piChart) {

            ArrayList<BarDataSet> dataSets = null;

            ArrayList<BarEntry> completed = new ArrayList<>();

            for (int i = 0; i < piChart.getBarCompleted().size(); i++) {
                BarEntry value = new BarEntry(piChart.getBarCompleted().get(i), i); // Jan
                completed.add(value);
            }

            BarDataSet completeData = new BarDataSet(completed, "Completed Issue");
            completeData.setColor(Color.rgb(0, 155, 0));

            ArrayList<BarEntry> pending = new ArrayList<>();
            for (int i = 0; i < piChart.getBarCompleted().size(); i++) {
                BarEntry value = new BarEntry(piChart.getBarPending().get(i), i); // Jan
                pending.add(value);
            }

            BarDataSet pendingdata = new BarDataSet(pending, "Pending Issue");
            pendingdata.setColor(Color.rgb(253, 129, 0));

            ArrayList<BarEntry> rejected = new ArrayList<>();
            for (int i = 0; i < piChart.getBarCompleted().size(); i++) {
                BarEntry value = new BarEntry(piChart.getBarRejected().get(i), i); // Jan
                rejected.add(value);
            }

            BarDataSet rejectedData = new BarDataSet(rejected, "Rejected Issue");
            pendingdata.setColor(Color.rgb(255, 0, 0));

            dataSets = new ArrayList<>();
            dataSets.add(completeData);
            dataSets.add(pendingdata);
            dataSets.add(rejectedData);

            ArrayList<String> xAxis = new ArrayList<>();
            for (String months : piChart.getBarMonths()) {
                Log.d("CHART_RESPONSE", "month: " + months.toString());
                xAxis.add(months);
            }

            com.github.mikephil.charting.charts.BarChart chart = (com.github.mikephil.charting.charts.BarChart) findViewById(R.id.barchart);

            BarData data = new BarData(xAxis, dataSets);

            chart.setData(data);
            chart.setDescription("Bar chart");
            chart.invalidate();

        }
    }

Create JSON POJO:
public class Example {

@SerializedName("success")
@Expose
private boolean success;
@SerializedName("bar_months")
@Expose
private List<String> barMonths = null;
@SerializedName("bar_pending")
@Expose
private List<Integer> barPending = null;
@SerializedName("bar_rejected")
@Expose
private List<Integer> barRejected = null;
@SerializedName("bar_completed")
@Expose
private List<Integer> barCompleted = null;

public boolean isSuccess() {
return success;
}

public void setSuccess(boolean success) {
this.success = success;
}

public List<String> getBarMonths() {
return barMonths;
}

public void setBarMonths(List<String> barMonths) {
this.barMonths = barMonths;
}

public List<Integer> getBarPending() {
return barPending;
}

public void setBarPending(List<Integer> barPending) {
this.barPending = barPending;
}

public List<Integer> getBarRejected() {
return barRejected;
}

public void setBarRejected(List<Integer> barRejected) {
this.barRejected = barRejected;
}

public List<Integer> getBarCompleted() {
return barCompleted;
}

public void setBarCompleted(List<Integer> barCompleted) {
this.barCompleted = barCompleted;
}

}

The JSON is:
{

  "success": true,

  "bar_months":[
  "jan",
  "feb",
  "mar"
],

  "bar_pending":[
    100,
    200,
    300
  ],

   "bar_rejected":[
    140,
    220,
    340
  ],

   "bar_completed":[
    170,
    290,
    310
  ]

}

So basically, my data in bar_months,bar_pending, bar_rejected and bar_completed will changed instead of a static value, wondering what suggestions/ examples that I can try to retrain the dynamic data every hour. Thanks in advance for reading and helping!

A: In order to schedule your getData() task as recurring (even when your app is not in the foreground) you can use a workmanager.
In this specific case, you'll need a PeriodicWorkRequestBuilder (link).
The first step is defining the work you want to run periodically, extend the Worker class to do so:
class ExampleWorker(
    appContext: Context,
    workerParams: WorkerParameters
) :
    Worker(appContext, workerParams) {
    override fun doWork(): Result {
        getData()
        // Indicate whether the work finished successfully with the Result
        return Result.success()
    }

    private fun getData() {
        val piChartCall: Call<PiChart> = apiInterface.init()
        piChartCall.enqueue(object : Callback<PiChart?>() {
            fun onResponse(call: Call<PiChart?>?, response: Response<PiChart?>) {
                Log.d("CHART_RESPONSE", "" + response.body().getBarMonths().toString())
                setData(response.body())
            }

            fun onFailure(call: Call<PiChart?>?, t: Throwable?) {}
        })
    }
}

The second step will be to schedule this work in a recurring way, PeriodicWorkRequestBuilder function can help you:
private fun schedulePeriodicWork(context: Context) {
    val request =
        PeriodicWorkRequestBuilder<ExampleWorker>(1, TimeUnit.HOURS).build()
    WorkManager.getInstance(context).enqueueUniquePeriodicWork(
        "charSync",
        ExistingPeriodicWorkPolicy.REPLACE, request
    )
}

Probably it would be a wise choice to put the scheduling function call in the onCreate() method of your Application class


text:
Q: Laravel 4 Nested controllers without namespaces It's possible to nest controllers into subfolders like L3?
http://paste.laravel.com/uc8

A: Yes, however namespaces are recommended for organizational reasons, in this case, keeping your admin functions controlled.
But if you're set on not using Namespaces, you can access it like a normal controller, but you'll need to dump the composer autoload so it can find your class. You can do that by doing
composer dump-autoload
or
php composer.phar dump-autoload

A: Based on the book of Dayle Rees it should be posible if you would use instead of the . notation a slash so for example administrator.StatisticsController@index would be administrator\StatisticsController@index Laravel 4 uses the PSR-0 Loading scheme.


text:
Q: Given mixed accented and normal characters in string not working in java when searching String text = "Cámélan discovered ônte red aleŕt \n Como se extingue la deuda";

If I give the input Ca, it should highlight from the given string Cá but it's not highlighting.
Below is what I tried.
 Pattern mPattern;
  String filterTerm; //this is the input which I give from input filter. Say for eg: Ca
   String regex = createFilterRegex(filterTerm);
        mPattern = Pattern.compile(regex);

 private String createFilterRegex(String filterTerm) {
        filterTerm = Normalizer.normalize(filterTerm, Normalizer.Form.NFD);
       filterTerm = filterTerm.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
        return filterTerm;
    }

public Pattern getPattern() {
        return mPattern;
    }

In another class,
private SpannableStringBuilder createHighlightedString(String nodeText, int highlightColor) { //nodeText is the entire list displaying.
        SpannableStringBuilder returnValue = new SpannableStringBuilder(nodeText);
        String lowercaseNodeText = nodeText;
        Matcher matcher = mFilter.getPattern().matcher((createFilterRegex(lowercaseNodeText)));
        while (matcher.find()) {
            returnValue.setSpan(new ForegroundColorSpan(highlightColor), matcher.start(0),
                    matcher.end(0), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        }

        return returnValue;
    }

viewHolder.mTextView.setText(createHighlightedString((node.getText()), mHighlightColor));
But what I am getting the output as,
If I type single alphabet o alone, it's highlighting but if I pass more than two alphabets say for eg: Ca, it's not highlighting and displaying. I couldn't figure out what mistake I am doing.
But if you look WhatsApp. it has been achieved.
I typed Co,  it's recognizing and highlighting accented characters in the sentence.

A: As you said,
String text = "Cámélan discovered ônte red aleŕt \n Como se extingue la deuda";
So whenever you give first input, receive that first character and compare.
Eg: If you give Ca,  then
if (StringUtils.isNotEmpty(substring)) { //this is the search text
substring=substring.substring(0,1); //now you get C alone.

}
So whatever you type it displays by filtering the first character. Now
 SpannableString builder = higlightString((yourContent.getText()), mHighlightColor);
    viewHolder.mTextView.setText(builder);

private SpannableString higlightString(String entireContent, int highlightColor) {
            SpannableString returnValue = new SpannableString(entireContent);

            String lowercaseNodeText = entireContent;
        try {
            Matcher matcher = mFilter.getPattern().matcher(((diacritical(lowercaseNodeText.toLowerCase()))));
            while (matcher.find()) {
                returnValue.setSpan(new ForegroundColorSpan(highlightColor), matcher.start(0),
                        matcher.end(0), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }

            return returnValue;

    }

 private String diacritical(String original) {
       String removed=null;
           String decomposed = Normalizer.normalize(original, Normalizer.Form.NFD);
           removed = decomposed.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
       return removed;
   }

Test case:
When you give input Ca, it goes to the entire text by displaying all the C content get all the datas and filter out by normalising the content and it matches with accented characters too and display by higlighting.

A: You already got:
private String convertToBasicLatin(String text) {
    return Normalizer.normalize(text, Normalizer.Form.NFD)
        .replaceAll("\\p{M}", "").replaceAll("\\R", "\n");
}

In order to have one unaccented basic latin char match one Unicode code point of an accented letter,
one should normalize the to the composed form:
private String convertToComposedCodePoints(String text) {
    return Normalizer.normalize(text, Normalizer.Form.NFC).replaceAll("\\R", "\n");
}

In general one might make the assumption that the Unicode code point is 1 char long too.

*

*The search key uses convertToBasicLatin(sought)

*The text view's content uses convertToComposedCodePoints(content)

*The text content for matching uses convertToBasicLatin(content)

Now the matcher's index positions of start and end are correct.
I normalized explicitly line endings (regex \R) like \r\n or \u0085 to a single \n.
One cannot normalize to lowercase/uppercase, as the number of chars might vary:
German lowercase ß corresponds with uppercase SS.
String sought = ...;
String content = ...;

sought = convertToBasicLatin(sought);
String latinContent = convertToBasicLatin(content);
String composedContent = convertToComposedUnicode(content);

Matcher m = Pattern.compile(sought, Pattern.CASE_INSENSITIVE
        | Pattern.UNICODE_CASE | Pattern.UNICODE_CHARACTER_CLASS
        | Pattern.UNIX_LINES)
    .matcher(latinContent);
while (m.find()) {
    ... // One can apply `m.start()` and `m.end()` to composedContent of the view too.
}

A: I'm not a Java programmer, so just some basic raw regex solution here.
If you can Normalize the string with it's decomposition form
assume it's this
String sSourceTargetDecom = Normalizer.normalize(sourcetarget, Normalizer.Form.NFD);,
that should turn something like 0000C1 Á LATIN CAPITAL LETTER A WITH ACUTE
into two characters A and 000301 ́  COMBINING ACUTE ACCENT.
You can get most combining characters from blocks using
[\p{Block=Combining_Diacritical_Marks}\p{Block=Combining_Diacritical_Marks_Extended}\p{Block=Combining_Diacritical_Marks_For_Symbols}\p{Block=Combining_Diacritical_Marks_Supplement}\p{Block=Combining_Half_Marks}]

which has a hex range of
[\x{300}-\x{36f}\x{1ab0}-\x{1aff}\x{1dc0}-\x{1dff}\x{20d0}-\x{20ff}\x{fe20}-\x{fe2f}]

It turns out that most of the combining marks relative to basic Latin that can be
decomposed are in the [\x{300}-\x{36f}] range.
You can decompose both the source target and the input search string.

Then create a regex from the input search string.
Inject [\x{300}-\x{36f}]?  after each basic Latin letter.
String regex = sSearch.replaceAll("([a-zA-Z])[\\x{300}-\\x{36f}]?", "\\1[\\x{300}-\\x{36f}]?");

(not sure what Java uses for codepoint character notation in their regex, possibly needs to be \u{DD}
Then use the regex on the sSourceTargetDecom string, it will match the basic latin as a stand alone, and/or with an optional combining code.


text:
Q: How does dojo/request/iframe work? I am slowly getting better at the whole Javascript/Dojo world. But, I am confused by the whole dojo/request/iframe business.
I know that in Javascript you can only connect to the origin server for security reasons. That's a given. However, when people start taking about "using iframes to get around that", I get very lost.
Dojo/resources/blank.html:

*

*contains

*Needs to be hosted by the same server that has your application. So, if you use dojo from a CDN, you need to have this blank.html file saved on the same server where the application is coming from

The page http://livedocs.dojotoolkit.org/dojo/request/iframe explains, about iframe:

*

*Calling a service on a server other than the one that originated the calling page (cross-domain request). Note that in this case, the response body cannot be read: you can send data, but not get any replies. If you need access to the return data, see dojo/request/script.

*Uploading files from a form (e.g. file input controls). The normal XHR mechanism cannot access file data referenced by file selection tags as a security measure. dojo/request/iframe can by proxying those calls through an IFrame, making it possible to still do file uploads in an asynchronous manner.
How does an empty HTML page help me with this? (Well, one that sets a global variable "isLoaded"...?)
Also, after explaining in the two points above that you cannot retrieve the response, the documentation continues with:

*

*An example of making a request to retrieve some XML would look like:

So... you can retrieve?
I think I need to go one step back and really understand the whole "using an iframe to get around cross-domain request" as well as actually understand the issue that "normal XHR mechanisms" (what mechanisms?) cannot access data references by the selection tags (what selection tags? And isn't the data in the request body anyway?) can proxy those callls through an iFrame (you mean a single empty file that sets isLoaded?!? )
I am very confused... and lost. Can somebody give me a bit of direction?
Thank you...
Merc.

A: Well, I don't know about the blank.html page, but the second part of your question is something I understand.
As far as I know, most (all) browsers deny cross-domain requests from XHR/JavaScript and neither can they send data from file upload form elements due to security reasons. If it was possible, hackers could (by injecting some JavaScript) do horrible things like sending data to other domains or read uploaded files.
To get around this issue you can use iframes. Iframes CAN load cross-domain pages, however the problem is that you can not simply access the content of an iframe if it's a cross domain request. However, with JavaScript you can set the source of the iframe and thus you can send data through an iframe.
The same thing with files, you cannot send it directly, but you can send them through iframes, because you can manipulate what iframes do (and send data).
So TL;DR: Browsers block certain things that you can do with JavaScript like:

*

*Sending data through XHR that is cross-domain

*Read file data through XHR

*Reading iframe data that is cross-domain

So you CAN do the following:

*

*Send data that is cross-domain through an iframe

*Read file data through an iframe

*Read iframe that that is not cross-domain

So you can indeed read a file with the iframe dojo module as long as it is not a cross-domain request.
I hope I explained it good enough to understand.


text:
Q: check if SPField exists using list services I want to check if a custom field exists for my list using list services but not sure how I can do it, I know it can be done using object model method "ContainsField()" but how can I do same with services,
    public bool fieldExists()
    {
        XmlDocument doc = new XmlDocument();
                    //field exists or not ?

A: Yup you can look into hash table and find key you need for that field if it exists or not. I don't remember 100% the code I used but I will try to provide it someone need it in future.
Hope it helps if someone else came across same problem :)


text:
Q: How to post data in nested serializer using id field I'm trying to post data in nested serializer using only id field, but it does not work.
This project is for making orders in restaurants
What i want to see
Here is how i push data:
{
    "is_done": false,
    "dishes": [
        {"dish":1}
    ]
}

The GET request looks like this:
{
    "id": 14,
    "is_done": false,
    "dishes": [
        {
            "dish": 1,
            "quantity": 1
        }
    ]
}

But I want to see it like this
{
    "id": 14,
    "is_done": false,
    "dishes": [
        {
            "dish": {
                "id": 1,
                "name": "Simple dish 1",
                "price": "200.00"
            },
            "quantity": 1
        }
    ]
}

Here is my python code
OrderItemSerializer
OrderSerializer
class OrderItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = OrderItem
        fields = (
            'dish',
            'quantity',
        )

class OrderSerializer(serializers.ModelSerializer):
    dishes = OrderItemSerializer(many=True, read_only=False)

    class Meta:
        model = Order
        fields = (
            'id',
            'is_done',
            'dishes',
            # 'created_at',
            # 'updated_at',
        )

    def create(self, validated_data):
        order_items = validated_data.pop('dishes')
        order = Order.objects.create(**validated_data)
        for dish in order_items:
            OrderItem.objects.create(order=order, **dish)
        return order

    def update(self, instance, validated_data):
        order_items = validated_data.pop('dishes')

        instance.is_done = validated_data.get('is_done', instance.is_done)
        instance.save()

        for dish in order_items:
            order_item = OrderItem.objects.get(order=instance)
            order_item.dish = dish['dish']
            order_item.quantity = dish['quantity']
            order_item.save()

        return instance

Models
class Order(models.Model):
    is_done = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'Заказ'
        verbose_name_plural = 'Заказы'

class OrderItem(models.Model):
    order = models.ForeignKey(Order, related_name='dishes',
                              on_delete=models.CASCADE)
    dish = models.ForeignKey(Dish, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)

A: you can add a serializer for dish to your OrderItemSerializer which represents data the way you want it.
so it will be:
class DishSerializer(serializers.ModelSerializer):
    class Meta:
        model = Dish
        fields = (
            'id',
            'name',
            'price',
        )
class OrderItemSerializer(serializers.ModelSerializer):
    dish = DishSerializer(read_only=True)
    class Meta:
        model = OrderItem
        fields = (
            'dish',
            'quantity',
        )

class OrderSerializer(serializers.ModelSerializer):
    dishes = OrderItemSerializer(many=True, read_only=False)

    class Meta:
        model = Order
        fields = (
            'id',
            'is_done',
            'dishes',
            # 'created_at',
            # 'updated_at',
        )

    def create(self, validated_data):
        order_items = validated_data.pop('dishes')
        order = Order.objects.create(**validated_data)
        for dish in order_items:
            OrderItem.objects.create(order=order, **dish)
        return order

    def update(self, instance, validated_data):
        order_items = validated_data.pop('dishes')

        instance.is_done = validated_data.get('is_done', instance.is_done)
        instance.save()

        for dish in order_items:
            order_item = OrderItem.objects.get(order=instance)
            order_item.dish = dish['dish']
            order_item.quantity = dish['quantity']
            order_item.save()

        return instance


text:
Q: PHP SQL Preventing Duplicate User names: Catching Exception vs Select Query For preventing duplicate user names from being entered into the database and notifying the user, is it more standard/preferred to use exception catching when inserting or select query before inserting?

*

*Exception catching: if I try to insert the user input and the user name already exists then the SQL database will throw a primary key constraint violation exception. I can catch it if that happens and do whatever.

*Select Query: if it returns any tuples matching the user name then I won't bother with the insert. Then I can display the error message.
I suppose the main pro of using Exceptions here is there is less queries and lines (better speed?). However, I don't think this is an exceptional case since duplicates probably occur fairly often.

A: In the very least, you should use option 1 - handle primary key constraint violation - when possible since the database is the last point of entry. Duplication is still possible if you check for duplicates in code (albeit highly unlikely) since there is a delay between when the initial SELECT is returned and the INSERT statement is sent back, and another user could have performed the same insert in that time window.
However, it is likely more efficient to run a select first to see if the record exists, rather than blindly letting the insert run every single time.
So I would recommend both.

A: If you use Exception catching method i.e.  try to insert then keep in mind one thing when ever the Exception occurs your counter for auto_increment column will increase lets take an example you have inserted one record successfully and its id is 1 then you try to insert the same information you got the Exception then you try to insert another data with different data  it will be inserted but the id no. for this time will be 3 not 2 as 1 was incremented when Exception occurred so keep in mind if you play with Exception case you will loose these id no.s when when Exception occurs .If id counter is not your concerned then go ahead with this option.
But i prefer to  select first then insert
Hope it makes sense

A: Unless, your database querying layer provides multiple Exception classes (for each SQL states - in case of relational databases) you should not use Exception catching; in that case you need to rely on the exceptions' messages - it could change over time.

A: I don't think there actually is a "standard" of doing this like this. Either you query, then insert, or you go for the INSERT / exception.
Both works fine if applied correctly.
I usually prefer to let the database do this task. Alter your table so the field you want to be unique is actually a unique index. When you want to insert the data, and it is a duplicate, you'll receive an error which can be used to decide what to do next. Or you might use an ON DUPLICATE KEY (if available on the RDBMS of your choice) if you want to do another table operation instead, if needed.
This avoids having problems on the database side, if not only your application writes into those tables. Even if you query first, you should do this in order to have a solid table.

A: How about the IGNORE clause:
CREATE TABLE `users` (
`username` VARCHAR(16),
PRIMARY_KEY (`username`)
);

INSERT IGNORE INTO `users`
(`username`)
VALUES ('Foo Dude');

This will generate a warning but won't terminate.
Apparently you can use the following to capture that warning in PHP 5.1.0 and beyond:
function exception_error_handler($severity, $message, $errfile, $errline)
{
    if (error_reporting()) { // skip errors that were muffled
        throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
    }

    // Or handle in some other way, like filtering for the WARNING
    // that is generated by the INSERT IGNORE.
}

set_error_handler("exception_error_handler");

But, I haven't tried this.  Check out the PHP manual for "ErrorException" [http://php.net/errorexception] and especially the comments -- consider implementing your own "ErrorException" class where you filter for the WARNING generated by duplicate key inserts when using INSERT IGNORE.
OR
Apparently error_get_last() will also get warnings.
AND
If you don't want these warnings to show up in the log, then either use error_reporting() to suppress them, or try putting an '@' in front of the query function [use with extreme caution 'cuz this will suppress ALL errors/warnings!]:
@mysqli_query($query);


text:
Q: Brazil Language problem in the TikZ diagram I have a problem with TikZ diagram, I don't get to make the diagram with babel under the brazil language.
I used the code with french and everything is OK!
\documentclass[a4paper,12pt, brazil]{article}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[body={16.5cm,24cm}]{geometry}
\usepackage{amsthm, amssymb}
\usepackage{babel}
\usepackage{comment}
\usepackage{amsmath}
\usepackage{color}
\usepackage{graphicx}
\usepackage{tikz-cd}

\begin{document}

\begin{defi}

\[\begin{tikzcd}[column sep=small]
Y_1 \ar[dr, "\pi_1"'] \ar[rr, "f"]& & \ar[ld, "\pi_2"] Y_2 \\
& X &
\end{tikzcd}\]

\end{defi}

\end{document}

A: portuges.ldf (loaded by option brazil) makes " an active shorthand
that disturbs the tikz-cd code. The shorthand can be disabled via \shorthandoff:
\documentclass[a4paper,12pt,brazil]{article}

\usepackage{babel}
\usepackage{tikz-cd}

\begin{document}

\shorthandoff{"}
\[\begin{tikzcd}[column sep=small]
Y_1 \ar[dr, "\pi_1"'] \ar[rr, "f"]& & \ar[ld, "\pi_2"] Y_2 \\
& X &
\end{tikzcd}\]
\shorthandon{"}

\end{document}

(\usetikzlibrary{babel} didn't work for this example, tikz-cd seems to expect a " with catcode 12 (other), see \tikzcd@enablequotes.)
Patch version
The following example patches some TikZ macros to support the active quotes:
\documentclass[a4paper,12pt,brazil]{article}

\usepackage{babel}
\usepackage{tikz-cd}

\makeatletter
\shorthandon{"}
% Patch for tikzlibarycd.code.tex
\g@addto@macro\tikzcd@enablequotes{%
  \pgfkeys{%
    /handlers/first char syntax/\meaning"/.initial=\tikzcd@passquotes
  }%
}

% Patch for tikzlibraryquotes.code.tex
\def\active@tikz@quote@parser#1{\active@tikz@quote@@parser#1\pgf@stop}
\def\active@tikz@quote@@parser"#1"{%
  \pgfutil@ifnextchar\bgroup{%
    \tikz@quote@@parser@group{#1}}{%
    \pgfutil@ifnextchar'{%
      \tikz@quote@@parser@apo{#1}}{%
      \tikz@quote@@parser@normal{#1}}}}

\g@addto@macro\tikz@enable@node@quotes{%
  \pgfkeyssetvalue{/handlers/first char syntax/\meaning"}%
                  {\active@tikz@quote@parser}%
}
\g@addto@macro\tikz@enable@edge@quotes{%
  \pgfkeyssetvalue{/handlers/first char syntax/\meaning"}%
                  {\active@tikz@quote@parser}%
}
\g@addto@macro\tikz@enable@pic@quotes{%
  \pgfkeyssetvalue{/handlers/first char syntax/\meaning"}%
                  {\active@tikz@quote@parser}%
}
\shorthandoff{"}
\makeatother

\begin{document}

\[\begin{tikzcd}[column sep=small]
Y_1 \ar[dr, "\pi_1"'] \ar[rr, "f"]& & \ar[ld, "\pi_2"] Y_2 \\
& X &
\end{tikzcd}\]

\end{document}

A: This is essentially the same as Tikz and babel error
\documentclass[a4paper,12pt, brazil]{article}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{babel}

\usepackage{tikz-cd}

\tikzset{
  every picture/.prefix style={
    execute at begin picture=\shorthandoff{"}
  }
}

\begin{document}

\[
\begin{tikzcd}[column sep=small]
Y_1 \ar[dr, "\pi_1"'] \ar[rr, "f"]& & \ar[ld, "\pi_2"] Y_2 \\
& X &
\end{tikzcd}
\]

\end{document}

Unfortunately, \usetikzlibrary{babel} doesn't seem to work with tikz-cd.
Update
As of tikz-cd version 0.9c (released 2014/10/20), the babel library is supported and the following works.
\documentclass[a4paper,12pt, brazil]{article}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{babel}

\usepackage{tikz-cd}[2014/10/20] % ensure it's version 0.9c or later
\usetikzlibrary{babel}

\begin{document}

\[
\begin{tikzcd}[column sep=small]
Y_1 \ar[dr, "\pi_1"'] \ar[rr, "f"]& & \ar[ld, "\pi_2"] Y_2 \\
& X &
\end{tikzcd}
\]

\end{document}


text:
Q: Combobox's SelectedValue (or SelectedItem) OneWay binding not working. Any ideas? In the below window, the Existing Reports combo is bound to an observeablecollection of reportObjects. I have a reportObject property currentReport bound to the combo's SelectedValue property, OneWay. However, that's not working when bound in XAML.
SelectedValue="{Binding currentReport, Mode=OneWay}"

TwoWay binds fine, but I can't do it that way without writing an undo() method to the reportObject class. I'm binding the currentReport's properties to the various textboxes for editing. I want to bind OneWay so the source doesn't get changed. The currentReport's properties are all TwoWay bound to the corresponding textboxes so when I update the table in SQL [Save], it'll pull from that object, who's data is current.
<TextBox Text="{Binding currentReport.reportName, Mode=TwoWay}"

All of the properties bound from currentReport to the textboxes work fine as well. The only problem is the OneWay binding from the SelectedValue to the currentReport object. Does anyone have any ideas how to get this to work? I saw there was a bug, but the post I saw was 2009.

Sorry about the yellow. Not my idea. =)
EDIT: Added this XAML just in case.
<ComboBox ItemsSource="{Binding reportsCollection}" SelectionChanged="cboReports_SelectionChanged"
                                  DisplayMemberPath="displayName"
                                  SelectedValue="{Binding currentReport, Mode=TwoWay}"
                                  x:Name="cboReports" Width="342" Height="40" VerticalAlignment="Center"/>

A: Forget about you need to change values - that is a separate problem - need to review your data design. Start with the UI problem question. If you want a user to be able to select an item from a combo box then it must have two way binding. Your first question is SelectedValue="{Binding currentReport, Mode=OneWay}" is failing why?


text:
Q: Using reduceRegion() together with group? I am trying to use Hansen forest change dataset to identify the forest loss area across years for all states of India. I have a "lossYear band" where each pixel in the lossYear band contain values from 0 to 18 indicating the year in which the loss occurred.I want to use a grouped reducer, specifying the band index of the grouping band (1) so the pixel areas will be summed and grouped according to the value in the lossYear band.
This works well for a single geometry but how do i do the same for multiple polygons. Check code below. I am trying to recreate this lab ( https://www.geospatialecology.com/emm_lab_7/) for multiple features/states.
my code is as follows. It throws an error stating "unrecognized arguments"
var gfc2021 = ee.Image('UMD/hansen/global_forest_change_2021_v1_9');
var treeCover = gfc2021.select(['treecover2000']);
var lossImage = gfc2021.select(['loss']);
var gainImage = gfc2021.select(['gain']);

var level0 = ee.FeatureCollection("FAO/GAUL/2015/level0");
var level1 = ee.FeatureCollection("FAO/GAUL_SIMPLIFIED_500m/2015/level1");

var India = level0.filter(ee.Filter.eq('ADM0_CODE',115));
var IndianStates = level1.filter(ee.Filter.eq('ADM0_CODE',115));

// Add the tree cover layer in green.
Map.addLayer(treeCover.updateMask(treeCover),
    {palette: ['000000', '00FF00'], max: 100}, 'Forest Cover');

// Add the loss layer in red.
Map.addLayer(lossImage.updateMask(lossImage),
            {palette: ['FF0000']}, 'Loss');

// Add the gain layer in blue.
Map.addLayer(gainImage.updateMask(gainImage),
            {palette: ['0000FF']}, 'Gain');

// Load country boundaries from LSIB.
var countries = ee.FeatureCollection('USDOS/LSIB_SIMPLE/2017');
// Get a feature collection with just the Malaysia feature. Country codes here: https://en.wikipedia.org/wiki/List_of_FIPS_country_codes#I
var malay = countries.filter(ee.Filter.eq('country_co', 'MY'));

// Get the loss image.
// This dataset is updated yearly, so we get the latest version.

var lossAreaImage = lossImage.multiply(ee.Image.pixelArea());

var lossYear = gfc2021.select(['lossyear']);
var lossByYear = lossAreaImage.addBands(lossYear).reduceRegions({
  collection:IndianStates,
  reducer: ee.Reducer.sum().group({
    groupField: 1
    }),
  scale: 30,
  maxPixels: 1e9
});
//print(lossByYear);

A: As the error message says, reduceRegions doesn't have a maxPixels argument.  Just remove it.


text:
Q: Azure Container Instances: authenticate to private ACR with client certificate based service principal in ARM template The Azure Container Instances ARM template schema exposes the below fields to authenticate to pull an image from a private ACR using a service principal:
"imageRegistryCredentials": [
      {
        "server": "myacrserver.azurecr.io",
        "username": "00000-000-000-00",  // Service principal application ID
        "password": "servicePrincipalClientSecret"
      }
    ],

Using an ARM template based deployment, is it possible to use a service principal with a client certificate based login, instead of a client secret? Can I specify the "password" field to be the base64 encoding of the private key of the certificate that can be used to access the relevant service principal?

A: I'm afraid it's impossible. ARM template does not have the property to set the credential with a certificate instead of the secret. Maybe it's possible in the future, but not it does not support it.


text:
Q: Images load by themselves, but not as a randomized list. - Flutter and thank you in advance for any assistance.
So, I have images load properly when I use them within a container in other areas of the code, but I also want some of those images to display randomly within the AppBar.
Given that they do load in other locations within the code, I don't suspect a Pubyaml error.
I'm still fairly new to flutter, and lists in general. So I wouldn't be surprised if I messed up something with the list itself, or the way it's called.
It gives me this error:
Syncing files to device iPhone...
Reloaded 8 of 502 libraries in 411ms.

════════ Exception caught by image resource service ════════════════════════════════════════════════
The following assertion was thrown resolving an image codec:
Unable to load asset: Image(image: AssetImage(bundle: null, name: "images/Mem2.JPG"), frameBuilder: null, loadingBuilder: null, alignment: center, this.excludeFromSemantics: false, filterQuality: low)

When the exception was thrown, this was the stack:
#0      PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7)
<asynchronous suspension>
#1      AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:484:44)
#2      AssetBundleImageProvider.load (package:flutter/src/painting/image_provider.dart:469:14)
#3      ImageProvider.resolve.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:flutter/src/painting/image_provider.dart:327:17)
...
Image provider: AssetImage(bundle: null, name: "Image(image: AssetImage(bundle: null, name: "images/Mem2.JPG"), frameBuilder: null, loadingBuilder: null, alignment: center, this.excludeFromSemantics: false, filterQuality: low)")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#c99db(), name: "Image(image: AssetImage(bundle: null, name: "images/Mem2.JPG"), frameBuilder: null, loadingBuilder: null, alignment: center, this.excludeFromSemantics: false, filterQuality: low)", scale: 1.0)
════════════════════════════════════════════════════════════════════════════════════════════════════

Here's the code:
class ContactProfilePage extends StatefulWidget {
  @override
  _ContactProfilePageState createState() => _ContactProfilePageState();
}

class _ContactProfilePageState extends State<ContactProfilePage> {
  List<Attr> attr = [
    Attr(name: ''),
  ];

  dynamic randAppBarImg = [
    "images/Mem2.JPG",
    "images/Mem3.JPG",
    "images/Mem4.JPG",
    "images/Mem6.jpg",
    "images/memory - 1.jpeg",
    "images/memory - 2.jpeg",
    "images/memory - 3.jpeg",
    "images/memory - 4.jpeg",
    "images/memory - 5.jpeg",
    "images/memory - 6.jpeg",
  ];

  Random rnd;

  Image img() {
    int min = 0;
    int max = randAppBarImg.length - 1;
    rnd = Random();
    int r = min + rnd.nextInt(max - min);
    String image_name = randAppBarImg[r].toString();
    return Image.asset(image_name);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.lightBlueAccent,
        child: Icon(Icons.add),
        onPressed: () {
          //Modal sheet brings up the whole bottom pane when the plus button is pressed.
          showModalBottomSheet(
            context: context,
            builder: (context) => AddAttrScreen(
              (newAttrTitle) {
                setState(() {
                  //adds the Attr to the list anytime the user presses "Add"
                  attr.add(Attr(name: newAttrTitle));
                });
                Navigator.pop(context);
                //Hides the floating add Attr screen after pressing "Add"
              },
            ),
          );
          //TODO Change it so the categories don't have to be selected every time. Instead, have the add button WITHIN each category.
          // This floating button should instead create a new category.
        },
      ),
      drawer: DrawerMain(),
      body: NestedScrollView(
        //This allows for the top bar to collapse, while retaining the image.
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return <Widget>[
            SliverAppBar(
              expandedHeight: 200.0,
              floating: true,
              snap: true,
              pinned: true,
              flexibleSpace: Stack(
                children: <Widget>[
                  Positioned.fill(
                      child: Image.asset(
                    img().toString(),
                    fit: BoxFit.cover,
                  ))
                ],
              ),
            ),
          ];
        },

        body: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              Row(
                mainAxisSize: MainAxisSize.max,
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.all(15.0),
                    child: CircleAvatar(
                        maxRadius: 50.0,
                        backgroundImage: AssetImage("images/fox.jpeg")),
                  ),
                  Container(
                    //TODO ADD ON PRESSED FUNCTION TO SOCIAL ICONS
                    margin: EdgeInsets.all(15.0),
                    child: Icon(
                      FontAwesomeIcons.facebook,
                      size: 40.0,
                      color: Color(0xFF306060),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.all(15.0),
                    child: Icon(
                      FontAwesomeIcons.instagram,
                      size: 40.0,
                      color: Color(0xFF306060),
                    ),
                  ),
                ],
              ),
              Padding(
                padding: const EdgeInsets.only(left: 15.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      'Armando Pacheco Ortiz',
                      style: TextStyle(
                          fontSize: 25.0,
                          fontWeight: FontWeight.bold,
                          color: Color(0xFF306060)),
                    ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(left: 15.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      'Freelance App Developer from Puerto Rico',
                      style: TextStyle(
                          fontSize: 20.0,
                          fontStyle: FontStyle.italic,
                          color: Color(0xFF306060)),
                    ),
                    SizedBox(
                      child: Divider(),
                    ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(15.0),
                child: Row(
                  children: <Widget>[
                    Text('Memories',
                        style: TextStyle(
                            fontSize: 20.0,
                            fontStyle: FontStyle.italic,
                            color: Color(0xFF306060),
                            fontWeight: FontWeight.bold))
                  ],
                ),
              ),

              //Horizontal scrolling images.
              //TODO These need to update based on uploads, perhaps use something like google's face detection to auto add?
              Padding(
                padding: const EdgeInsets.all(15.0),
                child: SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      Container(
                        height: 310,
                        width: 200,
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(20.0),
                          child: (Image.asset(
                            'images/Mem6.jpg',
                            fit: BoxFit.cover,
                          )),
                        ),
                      ),
                      SizedBox(
                        width: 20,
                      ),
                      Container(
                        height: 310,
                        width: 200,
                        //ClipRRect allows for it to have the border radius. Container is painted behind the image.
                        //For that reason, adding a border radius to the container doesn't work.
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(20.0),
                          child: (Image.asset(
                            'images/Mem2.JPG',
                            fit: BoxFit.cover,
                          )),
                        ),
                      ),
                      SizedBox(
                        width: 20,
                      ),
                      Container(
                        height: 310,
                        width: 200,
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(20.0),
                          child: (Image.asset(
                            'images/memory - 4.jpeg',
                            fit: BoxFit.cover,
                          )),
                        ),
                      ),

I pasted the code as far down as the first image, to show how I have it set up in the other locations.
I'm not sure if the issue is with random images within the appBar, or maybe some code I'm missing.
Hopefully, someone can shed some light on this!
Many thanks.
UPDATE:
So that helped a ton and definitely got things running!  But I did notice two new problems cropping up.

*

*I had to rename all the images from: "memory - 6" to "Mem6", and that finally allowed them to show up.
Otherwise, sometimes it would revert back to the default teal color, and not display anything, besides an error about not being able to load the asset again. I imagine it's just a naming error I was unknowingly causing?

*Scrolling down will cause the Appbar to "refresh" again, and randomize the pictures with the slightest scrolling until you stop. If I scroll back up, it'll do it again. It doesn't create an error, but it does crash the app eventually from so much refreshing I guess.
How would I get around this? Is there an override, or should I simply create the widget with some Finals, or stateless/stateful widgets? I'm still learning the lingo and all that, so my apologies for the ignorance.

A: You can copy paste run full code below
Your img() has bug, you return an Image.asset and wrap in Image.asset again cause duplicate
Image.asset(
             img().toString(),
             fit: BoxFit.cover,
           ))

code snippet just return String of image_name will work
and do not include space in image name
String img() {
    int min = 0;
    int max = randAppBarImg.length - 1;
    rnd = Random();
    int r = min + rnd.nextInt(max - min);
    String image_name = randAppBarImg[r].toString();
    //return Image.asset(image_name);
    return image_name;
  }

working demo

full code
import 'package:flutter/material.dart';
import 'dart:math';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ContactProfilePage(),
    );
  }
}

class Attr {
  String name;
  Attr({this.name});
}

class ContactProfilePage extends StatefulWidget {
  @override
  _ContactProfilePageState createState() => _ContactProfilePageState();
}

class _ContactProfilePageState extends State<ContactProfilePage> {
  List<Attr> attr = [
    Attr(name: ''),
  ];

  dynamic randAppBarImg = [
    "images/Mem2.JPG",
    "images/Mem3.JPG",
    /*"images/Mem4.JPG",
    "images/Mem6.jpg",
    "images/memory-1.jpeg",
    "images/memory-2.jpeg",
    "images/memory-3.jpeg",
    "images/memory-4.jpeg",
    "images/memory-5.jpeg",
    "images/memory-6.jpeg",*/
  ];

  Random rnd;

  String img() {
    int min = 0;
    int max = randAppBarImg.length - 1;
    rnd = Random();
    int r = min + rnd.nextInt(max - min);
    String image_name = randAppBarImg[r].toString();
    //return Image.asset(image_name);
    return image_name;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(
          backgroundColor: Colors.lightBlueAccent,
          child: Icon(Icons.add),
          onPressed: () {
            //Modal sheet brings up the whole bottom pane when the plus button is pressed.
            /*       showModalBottomSheet(
              context: context,
              builder: (context) => AddAttrScreen(
                (newAttrTitle) {
                  setState(() {
                    //adds the Attr to the list anytime the user presses "Add"
                    attr.add(Attr(name: newAttrTitle));
                  });
                  Navigator.pop(context);
                  //Hides the floating add Attr screen after pressing "Add"
                },
              ),
            );*/
            //TODO Change it so the categories don't have to be selected every time. Instead, have the add button WITHIN each category.
            // This floating button should instead create a new category.
          },
        ),
        //drawer: DrawerMain(),
        body: NestedScrollView(
            //This allows for the top bar to collapse, while retaining the image.
            headerSliverBuilder:
                (BuildContext context, bool innerBoxIsScrolled) {
              return <Widget>[
                SliverAppBar(
                  expandedHeight: 200.0,
                  floating: true,
                  snap: true,
                  pinned: true,
                  /*flexibleSpace: FlexibleSpaceBar(
                      centerTitle: true,
                      title: Text("",
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16.0,
                          )),
                      background: Image.asset(
                        "images/Mem2.JPG",
                        fit: BoxFit.cover,
                      )),*/
                  flexibleSpace: Stack(
                    children: <Widget>[
                      Positioned.fill(
                          child: Image.asset(
                        img().toString(),
                        fit: BoxFit.cover,
                      ))
                    ],
                  ),
                ),
              ];
            },
            body: SingleChildScrollView(
                child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                  Row(
                    mainAxisSize: MainAxisSize.max,
                    children: <Widget>[
                      Padding(
                        padding: const EdgeInsets.all(15.0),
                        child: CircleAvatar(
                            maxRadius: 50.0,
                            backgroundImage: AssetImage("images/fox.jpeg")),
                      ),
                      Container(
                        //TODO ADD ON PRESSED FUNCTION TO SOCIAL ICONS
                        margin: EdgeInsets.all(15.0),
                        child: Icon(
                          FontAwesomeIcons.facebook,
                          size: 40.0,
                          color: Color(0xFF306060),
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.all(15.0),
                        child: Icon(
                          FontAwesomeIcons.instagram,
                          size: 40.0,
                          color: Color(0xFF306060),
                        ),
                      ),
                    ],
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 15.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          'Armando Pacheco Ortiz',
                          style: TextStyle(
                              fontSize: 25.0,
                              fontWeight: FontWeight.bold,
                              color: Color(0xFF306060)),
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 15.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          'Freelance App Developer from Puerto Rico',
                          style: TextStyle(
                              fontSize: 20.0,
                              fontStyle: FontStyle.italic,
                              color: Color(0xFF306060)),
                        ),
                        SizedBox(
                          child: Divider(),
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(15.0),
                    child: Row(
                      children: <Widget>[
                        Text('Memories',
                            style: TextStyle(
                                fontSize: 20.0,
                                fontStyle: FontStyle.italic,
                                color: Color(0xFF306060),
                                fontWeight: FontWeight.bold))
                      ],
                    ),
                  ),

                  //Horizontal scrolling images.
                  //TODO These need to update based on uploads, perhaps use something like google's face detection to auto add?
                  Padding(
                      padding: const EdgeInsets.all(15.0),
                      child: SingleChildScrollView(
                          scrollDirection: Axis.horizontal,
                          child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: <Widget>[
                                Container(
                                  height: 310,
                                  width: 200,
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.circular(20.0),
                                    child: (Image.asset(
                                      'images/Mem6.jpg',
                                      fit: BoxFit.cover,
                                    )),
                                  ),
                                ),
                                SizedBox(
                                  width: 20,
                                ),
                                Container(
                                  height: 310,
                                  width: 200,
                                  //ClipRRect allows for it to have the border radius. Container is painted behind the image.
                                  //For that reason, adding a border radius to the container doesn't work.
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.circular(20.0),
                                    child: Image.asset(
                                      'images/Mem2.JPG',
                                      fit: BoxFit.cover,
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  width: 20,
                                ),
                                Container(
                                  height: 310,
                                  width: 200,
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.circular(20.0),
                                    child: (Image.asset(
                                      'images/memory-4.jpeg',
                                      fit: BoxFit.cover,
                                    )),
                                  ),
                                ),
                              ])))
                ]))));
  }
}


text:
Q: Find string between matching patterns In PowerShell I want to capture string between the first : and first , or first // (see examples below).
Example 1:

Iteration: Hourly, Hours: 0, Minutes: 15Frequency: "Minutes/Hours: every 15 minutes"

Output:

Hourly

Example 2:

// Iteration: Once // Frequency: "Once: at 9:57 AM on Thursday, April 28, 2016"

Output:

Once

A: This should work for you:
$string = 'Iteration: Hourly, Hours: 0, Minutes: 15Frequency: "Minutes/Hours: every 15 minutes"'
$regex = ':\s*(.+?)(?=,|\/\/)'
[regex]::Match($string, $regex).Groups[1].Value

Demo

A: You can use this in powershell
'// Iteration: Once // Frequency: "Once: at 9:57 AM on Thursday, April 28, 2016"' -match ':\s*(.*?)(?:,|\/\/)' | Out-Null; $Matches[1]


text:
Q: axis2/c server could not be opened I'm going to use axis2/c on windows to build a program, but when i click the "axis_http_server.exe" to start up the axis2/c server, nothing happened but a flashing window, i could't see the message "Started Simple Axis2 HTTP Server..." which was seen in the offical tutorial by apache, i've not changed anything but set the System's environment variable which was initial, so how can i open this?
i've turned to the directory axix2c/logs,the details in the axis2.log are as below:
....\src\core\deployment\conf_builder.c(903) Transport sender is NULL for transport http, unable to continue
 ....\src\core\deployment\conf_builder.c(262) Processing transport senders failed, unable to continue
 ....\src\core\deployment\dep_engine.c(752) Populating Axis2 Configuration failed
 ....\src\core\deployment\conf_init.c(64) Loading deployment engine failed for repository ../.
 ....\src\core\transport\http\receiver\http_receiver.c(126) unable to create private configuration contextfor repo path ../
 ....\src\core\transport\http\server\simple_axis2_server\http_server_main.c(215) Server creation failed: Error code: 103 :: Failed in creating DLL


text:
Q: MySQL UPDATE and SELECT in one pass I have a MySQL table of tasks to perform, each row having parameters for a single task.
There are many worker apps (possibly on different machines), performing tasks in a loop.
The apps access the database using MySQL's native C APIs.
In order to own a task, an app does something like that:

*

*Generate a globally-unique id (for simplicity, let's say it is a number)

*UPDATE tasks
SET guid = %d
WHERE guid = 0 LIMIT 1

*SELECT params
FROM tasks
WHERE guid = %d

*If the last query returns a row, we own it and have the parameters to run
Is there a way to achieve the same effect (i.e. 'own' a row and get its parameters) in a single call to the server?

A: You may create a procedure that does it:
CREATE PROCEDURE prc_get_task (in_guid BINARY(16), OUT out_params VARCHAR(200))
BEGIN

  DECLARE task_id INT;

  SELECT id, out_params
  INTO task_id, out_params
  FROM tasks
  WHERE guid = 0
  LIMIT 1
  FOR UPDATE;

  UPDATE task
  SET guid = in_guid
  WHERE id = task_id;

END;

BEGIN TRANSACTION;

CALL prc_get_task(@guid, @params);

COMMIT;

A: try like this
UPDATE `lastid` SET `idnum` =  (SELECT `id` FROM `history` ORDER BY `id` DESC LIMIT 1);

above code worked for me

A: If you are looking for a single query then it can't happen.  The UPDATE function specifically returns just the number of items that were updated.  Similarly, the SELECT function doesn't alter a table, only return values.
Using a procedure will indeed turn it into a single function and it can be handy if locking is a concern for you. If your biggest concern is network traffic (ie: passing too many queries) then use the procedure. If you concern is server overload (ie: the DB is working too hard) then the extra overhead of a procedure could make things worse.

A: I have the exact same issue. We ended up using PostreSQL instead, and UPDATE ... RETURNING:

The optional RETURNING clause causes UPDATE to compute and return value(s) based on each row actually updated. Any expression using the table's columns, and/or columns of other tables mentioned in FROM, can be computed. The new (post-update) values of the table's columns are used. The syntax of the RETURNING list is identical to that of the output list of SELECT.

Example: UPDATE 'my_table' SET 'status' = 1 WHERE 'status' = 0 LIMIT 1 RETURNING *;
Or, in your case: UPDATE 'tasks' SET 'guid' = %d WHERE 'guid' = 0 LIMIT 1 RETURNING 'params';
Sorry, I know this doesn't answer the question with MySQL, and it might not be easy to just switch to PostgreSQL, but it's the best way we've found to do it. Even 6 years later, MySQL still doesn't support UPDATE ... RETURNING. It might be added at some point in the future, but for now MariaDB only has it for DELETE statements.
Edit: There is a task (low priority) to add UPDATE ... RETURNING support to MariaDB.

A: I don't know about the single call part, but what you're describing is a lock.  Locks are an essential element of relational databases.
I don't know the specifics of locking a row, reading it, and then updating it in MySQL, but with a bit of reading of the mysql lock documentation you could do all kinds of lock-based manipulations.
The postgres documenation of locks has a great example describing exactly what you want to do: lock the table, read the table, modify the table.

A: UPDATE tasks
SET guid = %d, params = @params := params
WHERE guid = 0 LIMIT 1;

It will return 1 or 0, depending on whether the values were effectively changed.
SELECT @params AS params;

This one just selects the variable from the connection.
From: here


text:
Q: Retroft GET Request Call There are a lot of examples but I didn't find what I really wanted (didn't get it) so if anyone would like to help it would be appreciated.
using post I know we do the following:
@POST("/SearchFor")
    @FormUrlEncoded
    void SearchFor(@Field("QueryID")String  QueryID,@Field("ElementID")String  ElementID,@Field("Language")String  Language, Callback<Response> cb);

Then implement on success and on failure.
now on GET:
The URL I want as an output is :
 URL+=BASE_URL+"?QueryID="+ID+"&ElementID=where%20"+INPUTFLDDBNAME+"%20like'%25"+Value+"%25'&Language="+interfacelang+"";

ID,INPUTFLDDBNAME,interfacelang will be replaced by strings
So I did the following:
 @GET("/QueryID={QueryID}&ElementID=where%20{ElementID}%20like'%25{Value}%25'&Language={Language}")
    void SearchFor(@Path("QueryID")String  QueryID,@Path("ElementID")String  ElementID,@Path("Value")String  Value,@Path("Language")String  Language, Callback<Response> cb);

but obviously it didn't work and got the following error:
No Retrofit annotation found. (parameter #1)

this is how im calling it
Retrofit Retrofit=new Retrofit();
                    RestAPI PushNotificationWebService=Retrofit.SetRestAdapter("BASE_URL");
                    PushNotificationWebService.SearchFor(ID,fields.get(0).getText().toString(),INPUTFLDDBNAME,interfacelang,new Callback<Response>() {
                        @Override
                        public void success(Response response, Response response2) {
...

Please someone guide me it would be much appreciated.

A: You should use @Query() to add the query params to your base URL
@GET("/SearchFor")
void SearchFor(@Query("QueryID") String QueryID, @Query("ElementID") String ElementID,@Query("Language") String Language, Callback<Response> cb)

Then use something along the lines of:
String element = URLEncoder.encode(String.format("where %s like'%%%s%%'", element_id, value));
PushNotificationWebService.SearchFor(ID, element, ...)


text:
Q: Execution time of functions decreases at runtime. (C++) Why? For some testing purposes I have written a piece of code for measuring execution times of several fast operations in my real-time video processing code. And things are working fine. I am getting very realistic results, but i noticed one interesting peculiarity.
I am using a POSIX function clock_gettime with CLOCK_MONOTONIC attribute. So i am getting timespecs with nanosecond precision (1/1000000000sec) and it is said that getting a timespec value in that manner takes only several processor ticks.
Here are two functions that i am using for saving timespecs. I also added definitions of datastructures that are being used:
QVector<long> timeMemory;
QVector<std::string> procMemory;
timespec moment;

void VisionTime::markBegin(const std::string& action) {
    if(measure){
    clock_gettime(CLOCK_MONOTONIC, &moment);
    procMemory.append(action + ";b");
    timeMemory.append(moment.tv_nsec);
    }
}

void VisionTime::markEnd(const std::string& action) {
    if(measure){
    clock_gettime(CLOCK_MONOTONIC, &moment);
    procMemory.append(action + ";e");
    timeMemory.append(moment.tv_nsec);
    }
}

I am collecting the results into a couple of QVectors that are used later.
I noticed that when these two functions are executed for the first time(right after each other, having nothing between them), the difference between two saved timespecs is ~34000ns. Next time the difference is about 2 times smaller. And so on. If i execute them for hundreds of times then the average difference is ~2000ns.
So an average recurrent execution of these functions takes about 17000x less time than the first one.
As i am taking hundreds of measurements in a row, it does not really matter to me that some first executions last a little bit longer. But anyway it just interests me, why is it that way?
I have various experience in Java, but i am quite new to c++. I do not know much how things work here.
I am using O3 flag for optimization level.
My QMake conf:
QMAKE_CXXFLAGS += -O3 -march=native
So, can anyone tell, which part of this little code gets faster at runtime, how and why? I doubt appending to QVector. Does optimization affect this somehow?
It's my first question here on stackoverflow, hope it's not too long :) Many thanks for all your responses!

A: It is probably due to branch prediction. http://en.wikipedia.org/wiki/Branch_predictor

A: There are quite a few potential first-time costs in your measurement code, here's a couple and how you can test for them.
Memory allocation: Those QVectors won't have any memory allocated on the heap until the first time you use them.
Also, the vector will most likely start out by allocating a small amount of memory, then allocate exponentially more as you add more data (a standard compromise for containers like this).  Therefore, you will have many memory allocations towards the beginning of your runtime, then the frequency will decrease over time.
You can verify that this is happening by looking at the return value of QVector::capacity(), and tune the behavior by QVector::reserve(int) - e.g. if you do timeMemory.reserve(10000);, procMemory.reserve(10000);, you can reserve enough space for the first ten thousand measurements before your measurements begin.
Lazy symbol binding: the dynamic linker by default won't resolve symbols from Qt (or other shared libraries) until they are needed.  So, if these measuring functions are the first place in your code where some QVector or std::string functions are called, the dynamic linker will need to do some one-time work to resolve those functions, which takes time.
If this is indeed the case, you can disable the lazy loading by setting the environment variable LD_BIND_NOW=1 on Linux or DYLD_BIND_AT_LAUNCH=1 on Mac.