text:
Q: Solving PDEs with multiple phases in MATLAB - controlling constant B.C. throughout the simulation (ode15s). I am trying to solve a system of PDEs for a 1D flow ($Z$-axis) in time $t$ having several phases distinct by different boundary conditions of mixed type (their duration is fixed by defining a time for each phase). I am using FVM with TVD.
Problem description: my approach
Initially, I define initial conditions for t = 0, which I put in the resulting vector of unknown parameters. Next, I implement boundary conditions for the first phase for $Z = 0$ ($Z = 0.5$ for FVM) and $Z = N$ ($Z = N+0.5$), respectively, and execute the ODE solver ($\texttt{ode15s}$ as the set of PDEs is stiff).
I have noticed that during the time integration, the ode15s overwrites the boundary values for $Z = 0.5$, which I need to remain constant. Specifically, $\texttt{ode15s}$ returns a non-zero values for the time derivatives at $Z = 0.5$, thus "changing" the boundary values for each time layer.
Arguably, this is not correct as the $\texttt{ode15s}$  returns a non-zero values for the time derivatives on the $Z = 0.5$ boundary where they should be constant.
My solution: To "fix" this error, I have not found a better way than to zero (by "force") the time derivatives for $Z = 0.5$, after the $\texttt{ode15s}$  has been computed, to achieve constant values at this boundary throughout the simulation.
Principally, the algorithm should work by defining the time derivatives only once at the beginning and then changing only the boundary conditions, in my opinion.
Numerical scheme and implementation of ICs and BCs

*

*I use FVM with TVD (with ghost cells) and specify boundary conditions for the first and last finite volume walls ($Z = 0.5$ and $Z = N+0.5$, respectively).

*At the beginning of my algorithm, initial conditions are assigned to all central values of the finite volumes for time $t = 0$ for all $N$ volumes.

*At the beginning of each phase, the boundary conditions are again
assigned to the first and last walls while zeroing of the time
derivates (likely a mistake) is performed for the initial finite
volume centre, i.e. $Z = 1$.

MATLAB example: my implementation
I made a simple code document my problem and my implementation (the original code is "long"):

*

*If I introduce ghost cells at the walls of the numerical grid, the
function returns non-zero time derivatives at its beginning and end, with the $\texttt{ode15s}$ subsequently changing these values by time
integration.

*If I "hard" set the first and last time derivatives equal to 0, then these temperature values (first and last) are constant throughout the $\texttt{ode15s}$ time integration.
Questions

*

*What computation (implementation), different to mine, of the boundary conditions for the first time layer and for all time derivatives, to keep them constant all the time, would you use, rather than force these values to remain constant by introducing zero time derivatives ($\texttt{dTdt(1) = 0;}$ , $\texttt{dTdt(nz+1) = 0;}$)? (In other words, would you please have any recommendations on how to keep the boundary values constant in the ODE solver without overwriting the time derivatives within the run of the algorithm?).

% Simulation of a heat conduction
% 24012023
  clear all
  clc

  % Input parameters
  L     = 1;            % [m]
  t     = 1;            % [s]
  alfa  = 0.1;          % [degC/m]
  Ta    = 80;           % [degC]
  Tb    = 20;           % [degC]

  % Mesh
  nz    = 20;
  dz    = L/nz;         % [m]

  % Initial conditions
  T0       = Tb*ones(1,nz+1);
  T0(1)    = Ta;                % Boundary condition/values for Z = 0
  T0(nz+1) = Tb;                % Boundary condition/values for Z = L

  z        = linspace(0,L,nz+1);

  % ODE solver
  opts = odeset('RelTol',1e-4,'AbsTol',1e-5);
  % Ghost cell
  [time,T_ODE]   = ode15s(@heat_calc, [0 t], T0, opts, nz, alfa, dz, Ta, Tb, 0);
  % dTdt = 0
  [time2,T2_ODE] = ode15s(@heat_calc, [0 t], T0, opts, nz, alfa, dz, Ta, Tb, 1);

  % Plotting results
  subplot(2,1,1), plot(z,T_ODE),title('Ghost ODE')
  subplot(2,1,2), plot(z,T2_ODE),title('dTdt=0 ODE')

%%
  function dTdt = heat_calc(t, T, nz, alfa, dz, Ta, Tb, parametr)
    % Add ghost cell
    % Boundary condition for Z = 0 and Z = L, is such implementation correct?
    Tg         = [Ta; T; Tb];
    dTdt       = (alfa/dz^2).*(Tg(3:nz+3,1)...
         - 2.*Tg(2:nz+2,1) + Tg(1:nz+1,1));

    % For keeping Ta and Tb constant, is such implementation correct?
    if parametr == 1
        dTdt(1)    = 0;
        dTdt(nz+1) = 0;
    end
  end

A: In my opinion, the best way to ensure that the boundary conditions remain constant is to not make them dependent variables in the first place and only simulate the dynamics on the interior cells. The ODE function would be exactly the same except you would have to manually write out the cases for the leftmost and rightmost interior cells as their values would de generated by the finite volume stencil with the boundary condition values inside them. If you want to keep the exterior nodes in the state (this makes the bookkeeping easier on you, but you get these problem in exchange), then setting the derivatives to zero manually seems like the best course of action.
Edit: With minimal modifications to your code, something like this should work. I don't have MATLAB on this computer, so I haven't tested it. However, something like this should work. The important changes are in the grid and problem dimension. I changed the grid so that nz is the number of internal nodes, then add two for the boundaries. The ODE function then only simulates the internal nodes. This is very important. Notice that the part of the ODE function that touches the boundaries still had to be manually specified, but it still matches the FV stencil. I then concatenate the output of the ODE to add the boundary conditions at both ends of the domain for plotting. The rows/columns might be slightly off here since I couldn't test but this should work.
% Simulation of a heat conduction
% 24012023
 clear all
 clc

% Input parameters
  L     = 1;            % [m]
  t     = 1;            % [s]
  alfa  = 0.1;          % [degC/m]
  Ta    = 80;           % [degC]
  Tb    = 20;           % [degC]

% Mesh
  nz    = 20;           % number of internal cells
  dz    = L/nz;         % [m]
  z     = linspace(0,L,nz+2);   %grid containing boundary points

% Initial conditions
  T0       = Tb*ones(nz,1);

% ODE solver
  opts = odeset('RelTol',1e-4,'AbsTol',1e-5);
  [time,T_ODE]   = ode15s(@heat_calc, [0 t], T0, opts, nz, alfa, dz, Ta, Tb);

% Concatenate boundary conditions with solution
 Tcat = [Ta*ones(size(time)); T_ODE; Tb*ones(size(time))]
% Plotting results
  plot(z,Tcat)

%%
function dTdt = heat_calc(t, T, nz, alfa, dz, Ta, Tb)
    dTdt = T
    dTdt(2:end-1,1) = (alfa/dz^2).*(Tg(3:end,1)...
         - 2.*Tg(2:end-1,1) + Tg(1:end-2,1));

    dTdt(1,1) = (alfa/dz^2).*(T(2,1) - 2.*T(1,1) + Ta);
    dTdt(end,1) = (alfa/dz^2).*(Tb - 2.*T(end,1) + T(end-1,1));
end


text:
Q: DNS Server in Docker Container I have the DNS server Unbound in a docker container. This container has the following port mapping in the docker deamon:
0.0.0.0:53->53/tcp, 0.0.0.0:53->53/udp
The docker host has the IP address 192.168.24.5 and a local DHCP server announces the host's IP as the local DNS server. This works fine all over my local network.
The host itself uses this DNS server through the IP 192.168.24.5. That's the address that is put to the host's /etc/resolv.conf. (I know it would not work with docker if there was 127.0.0.1 as the nameserver address.)
I have some other docker containers and they are supposed to use this DNS server as well. The point is, they don't.
What actually happens is this:
Whithin a random container I can ping the host's address as well as the address of the unbound-container. But when I use dig inside a container I get these results:
# dig @172.17.0.6 ...
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: REFUSED, id: 22778
;; flags: qr rd ad; QUERY: 0, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; WARNING: recursion requested but not available
# dig @192.168.24.5 ...
;; reply from unexpected source: 172.17.0.1#53, expected 192.168.24.5#53
This looks like some internal DNS server intercepts the queries and tries to answer them. That would be fine if it would use the host's DNS server to get an answer, but it doesn't. DNS doesn't work at all in the containers.
Am I doing wrong or is docker doing something it should not ?

A: The issue is iptables UDP nat for DNS server. You're querying the host IP while it's the docker bridge network's response.
To fix this issue in at least to ways:

*

*Use container IP (DNS container) as DNS resolver if possible.

or

*

*Provide --net=host to your DNS server container and remove port mapping altogether. Then host IP DNS would work as expected.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to start application after migrating to Websphere 9 I am trying to migrate my applications to websphere 9 from wensphere 8.5.5.x. My application was developed on Java 7. I changed the JRE to 1.8 and created a maven build on JDK 1.8 as WAS 9 supports java 8. After I deployed my application EAR to WAS 9 and tried to start the application I started getting ClassNotFoundException for com.sun.faces.taglib.jsf_core package.
I saw some suggestions that I need to add this dependency in my project. I added the dependency in pom.xml. After adding this dependency, when I start the application, it just hangs trying to start and after 40-45 minutes I get below exception.
Dependency that I added to add com.sun.faces.taglib.jsf_core package.
    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-impl</artifactId>
        <version>2.2.20</version>
    </dependency>

Stack trace:
[8/20/19 15:49:31:732 EDT] 000000a9 webapp        E com.ibm.ws.webcontainer.webapp.WebApp notifyServletContextDestroyed SRVE0285E: Exception caught while destroying context: {0}
                                 java.lang.NullPointerException
               at org.jboss.weld.servlet.WeldInitialListener.contextDestroyed(WeldInitialListener.java:134)
               at com.ibm.ws.webcontainer.managedobject.ManagedObjectListenerWrapper.contextDestroyed(ManagedObjectListenerWrapper.java:138)
               at com.ibm.ws.webcontainer.webapp.WebApp.notifyServletContextDestroyed(WebApp.java:1867)
               at com.ibm.ws.webcontainer.webapp.WebApp.destroy(WebApp.java:3288)
               at com.ibm.ws.webcontainer.webapp.WebAppImpl.destroy(WebAppImpl.java:1561)
               at com.ibm.ws.webcontainer.webapp.WebGroupImpl.addWebApplication(WebGroupImpl.java:97)
               at com.ibm.ws.webcontainer.VirtualHostImpl.addWebApplication(VirtualHostImpl.java:170)
               at com.ibm.ws.webcontainer.WSWebContainer.addWebApp(WSWebContainer.java:904)
               at com.ibm.ws.webcontainer.WSWebContainer.addWebApplication(WSWebContainer.java:789)
               at com.ibm.ws.webcontainer.component.WebContainerImpl.install(WebContainerImpl.java:427)
               at com.ibm.ws.webcontainer.component.WebContainerImpl.start(WebContainerImpl.java:719)
               at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:1219)
               at com.ibm.ws.runtime.component.DeployedApplicationImpl.fireDeployedObjectStart(DeployedApplicationImpl.java:1514)
               at com.ibm.ws.runtime.component.DeployedModuleImpl.start(DeployedModuleImpl.java:704)
               at com.ibm.ws.runtime.component.DeployedApplicationImpl.start(DeployedApplicationImpl.java:1096)
               at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplication(ApplicationMgrImpl.java:786)
               at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplicationDynamically(ApplicationMgrImpl.java:1421)
               at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:2232)
               at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:436)
               at com.ibm.ws.runtime.component.CompositionUnitImpl.start(CompositionUnitImpl.java:123)
               at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:379)
               at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.access$500(CompositionUnitMgrImpl.java:127)
               at com.ibm.ws.runtime.component.CompositionUnitMgrImpl$1.run(CompositionUnitMgrImpl.java:654)
               at com.ibm.ws.security.auth.ContextManagerImpl.runAs(ContextManagerImpl.java:5488)
               at com.ibm.ws.security.auth.ContextManagerImpl.runAsSystem(ContextManagerImpl.java:5614)
               at com.ibm.ws.security.core.SecurityContext.runAsSystem(SecurityContext.java:255)
               at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.startCompositionUnit(CompositionUnitMgrImpl.java:668)
               at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.startCompositionUnit(CompositionUnitMgrImpl.java:612)
               at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplication(ApplicationMgrImpl.java:1311)
               at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
               at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:90)
               at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
               at java.lang.reflect.Method.invoke(Method.java:508)
               at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:83)
               at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
               at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:90)
               at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
               at java.lang.reflect.Method.invoke(Method.java:508)
               at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:287)
               at javax.management.modelmbean.RequiredModelMBean$4.run(RequiredModelMBean.java:1263)
               at java.security.AccessController.doPrivileged(AccessController.java:666)
               at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
               at javax.management.modelmbean.RequiredModelMBean.invokeMethod(RequiredModelMBean.java:1257)
               at javax.management.modelmbean.RequiredModelMBean.invoke(RequiredModelMBean.java:1096)
               at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:831)
               at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:813)
               at com.ibm.ws.management.AdminServiceImpl$1.run(AdminServiceImpl.java:1350)
               at com.ibm.ws.security.util.AccessController.doPrivileged(AccessController.java:118)
               at com.ibm.ws.management.AdminServiceImpl.invoke(AdminServiceImpl.java:1243)
               at com.ibm.ws.management.commands.AdminServiceCommands$InvokeCmd.execute(AdminServiceCommands.java:251)
               at com.ibm.ws.console.core.mbean.MBeanHelper.invoke(MBeanHelper.java:246)
               at com.ibm.ws.console.appdeployment.ApplicationDeploymentCollectionAction.execute(ApplicationDeploymentCollectionAction.java:608)
               at org.apache.struts.action.RequestProcessor.processActionPerform(Unknown Source)
               at org.apache.struts.action.RequestProcessor.process(Unknown Source)
               at org.apache.struts.action.ActionServlet.process(Unknown Source)
               at org.apache.struts.action.ActionServlet.doPost(Unknown Source)
               at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
               at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
               at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1239)
               at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:778)
               at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:477)
               at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
               at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:143)
               at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:78)
               at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:969)
               at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1109)
               at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:1386)
               at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:195)
               at org.apache.struts.action.RequestProcessor.doForward(Unknown Source)
               at org.apache.struts.tiles.TilesRequestProcessor.doForward(Unknown Source)
               at org.apache.struts.action.RequestProcessor.processForwardConfig(Unknown Source)
               at org.apache.struts.tiles.TilesRequestProcessor.processForwardConfig(Unknown Source)
               at org.apache.struts.action.RequestProcessor.process(Unknown Source)
               at org.apache.struts.action.ActionServlet.process(Unknown Source)
               at org.apache.struts.action.ActionServlet.doPost(Unknown Source)
               at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
               at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
               at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1239)
               at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:778)
               at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:477)
               at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
               at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:143)
               at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:96)
               at com.ibm.ws.console.core.servlet.WSCUrlFilter.setUpCommandAssistance(WSCUrlFilter.java:970)
               at com.ibm.ws.console.core.servlet.WSCUrlFilter.continueStoringTaskState(WSCUrlFilter.java:517)
               at com.ibm.ws.console.core.servlet.WSCUrlFilter.doFilter(WSCUrlFilter.java:338)
               at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:197)
               at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:90)
               at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:969)
               at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1109)
               at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:4112)
               at com.ibm.ws.webcontainer.webapp.WebAppImpl.handleRequest(WebAppImpl.java:2171)
               at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:304)
               at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:1028)
               at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1817)
               at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:294)
               at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:465)
               at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:532)
               at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:318)
               at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:88)
               at com.ibm.ws.ssl.channel.impl.SSLReadServiceContext$SSLReadCompletedCallback.complete(SSLReadServiceContext.java:1820)
               at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
               at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
               at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
               at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
               at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
               at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
               at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
               at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1892)

A: The JSF SunRI engine was removed in WebSphere traditional V9.0. You can either use the MyFaces implementation included in WebSphere traditional V9.0 or package your own JSF engine with your application. Here is a documentation page talking about the features that were removed in WebSphere traditional V9.0 (including JSF SunRI) and how to resolve them: https://www.ibm.com/support/knowledgecenter/SSAW57_9.0.5/com.ibm.websphere.nd.multiplatform.doc/ae/rmig_remfeat.html
As mentioned in the comments, I would suggest running the Migration Toolkit for Application Binaries (https://developer.ibm.com/wasdev/downloads/#asset/tools-Migration_Toolkit_for_Application_Binaries) against your application. It will help you find these kinds of issues and tell you how to resolve them. It includes information about the JSF SunRI removal.


text:
Q: Alternatives to react-native-date-picker? I am trying to use the react-native-date-picker on my vanilla react native project (no expo). I followed all of the installation instructions, but any time I attempt to render the DatePicker I get the following error...
[Invariant Violation: requireNativeComponent: "RNDatePicker" was not found in the UIManager.]

Now, when I check the documentation, I can see that it looks like I need to declare <RNDateTimePicker mode="date" /> somewhere, but the documentation is so piss poor, I have no idea where to put it in the file or in relation to the date picker object. The documentation through and through is petulantly unhelpful, to say it positively. Does anyone know how to fix this issue, where to put that magic line, or have any idea what DatePickers aren't inherently broken with the documentation skills of a 2nd grader?


text:
Q: Django Multiple fields in search error I have six text box in search field and user can enter either of the values. I capture those values in view by:
if request.GET:
     result_list = []
     client_build = request.GET.get('client_build','')
     app_build = request.GET.get('app_build','')
     ws_build = request.GET.get('ws_build','')
     asset = request.GET.get('asset','')
     feature = request.GET.get('feature','')
     test_type = request.GET.get('test_type','')
result_lists = result.objects.filter(asset=asset,feature=feature,      test_type=test_type)
     job_list = job.objects.filter(client_build=client_build ,app_build =   app_build,ws_build = ws_build)

When I try to filter them it gives "invalid literal for int() with base 10: ''" error! How can I get only those values which are entered by user and query in filter accordingly.
I referred to this post Django - multiple field search issues but i have six text box doing multiple if and else is not what I am looking for.

A: @vikalp.sahni is correct. You enter an integer but you didn't know that the input convert your answer into string. To fix that, as you said that the client_build is the only integer, it must be:
client_build = int(request.GET.get('client_build',''))

Overall I think your query is correct. Just remember to put int if it is integer.


text:
Q: how to have UIImage below UILabel or UITextView in a scrollview How can I set a UILabel or UITextViewbelow an UIImageView in a UIScrollView so that when the image is scrolled, the label or text should also scrolled along with it simultaneously. Need guidance on this.

A: You must implement your UIScrollView and then add the desired subview (UIImageView and UILabel in your case).
In you viewDidLoad:
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
scrollView.backgroundColor = [UIColor redColor];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, scrollView.frame.size.width * 2, 100)];
imageView.backgroundColor = [UIColor blueColor];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(imageView.frame.size.width, 0, imageView.frame.size.width * 2, 40)];
label.text = @"Hello World";

[self.view addSubview:scrollView];
[scrollView addSubview:imageView];
[scrollView addSubview:label];

Do not forget to set your UIScrollView's content size > to your frame:
scrollView setContentSize:CGSizeMake(self.view.frame.size.width * 2, self.view.frame.size.height);

This should provide you the guidance you requested.


text:
Q: Are initial submanifolds cofibrations? In Natural Operations in Differential Geometry by Kolar, Michor, & Slovak, they define an initial submanifold as follows:

They can be shown to satisfy the following universal property:

I am aware that the inclusion of an embedded submanifold is a cofibration, and I am wondering if the same holds for the more general class of initial submanifolds?


text:
Q: CS50: Speller (pset5) produces output that is exactly the same as the staff's solution, but check50 returns many errors. What's happening? My speller program (part of pset5) works well and the output exactly matches that of the staff's solution. However, when I run my program through check50, I still get several errors per their script:
:) dictionary.c, dictionary.h, and Makefile exist
:) speller compiles
:) handles most basic words properly
:( handles min length (1-char) words
    expected "MISSPELLED WOR...", not "MISSPELLED WOR..."
:( handles max length (45-char) words
    expected "MISSPELLED WOR...", not "MISSPELLED WOR..."
:( handles words with apostrophes properly
    expected "MISSPELLED WOR...", not "MISSPELLED WOR..."
:( spell-checking is case-insensitive
    expected "MISSPELLED WOR...", not "MISSPELLED WOR..."
:) handles substrings properly
:) program is free of memory errors

These errors are strange. My program definitely recognizes one-character words such as "a" and "i," takes apostrophes correctly, etc. I know this since I ran the staff's solution next to mine and programmatically compared the misspelled words in Excel: They all matched.
Here is my code. I can't find what makes check50 trip. Thanks to any brave soul who answers!
// Implements a dictionary's functionality

#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <strings.h>
#include <string.h>

#include "dictionary.h"

// Represents a node in a hash table
typedef struct node
{
    char word[LENGTH + 1];
    struct node *next;
}
node;

// Number of buckets in hash table
const unsigned int N = 26;

// Hash table
node *table[N]; // This looks like just the beginning of the list

// Variable added by me: A counter for each word added into the dictionary
int wordLoadedCount = 0;

// Returns true if word is in dictionary else false
// This is where the actual dictionary is put to work.
// check will only be passed words that contain letters and possibly apostrophes
bool check(const char *word)
{
    // CASE INSENSITIVE

    // 0. Remove apostrophes from the word [???]

    // 1. Hash word to obtain a hash value
    int index = hash(word);

    // 2. Access linked list at the index in the hash table
    //Pointer to the first node: table[index]
    // 3. Traverse linked list, looking for the word.

    // CODE FROM WEEK 5 LECTURE
    // Print List / Loop Through Linked List
    for (node *tmp = table[index]; tmp != NULL; tmp = tmp->next)
    {
        if (strcasecmp(word, tmp->word) == 0)
        {
            return true;
        }
    }

    return false;
}

// Hashes word to a number
unsigned int hash(const char *word)
{
    //Objective: Return a number from 0 to 25 given the first letter of the word.

    //Initialize index variable
    int index = 26;

    //Check the first letter of the word and convert it to an index from 0 to 25:

    // Convert the first number to its ASCII-equivalent int
    int firstLetter = (int)word[0];

    // Case: Uppercase letters
    if (firstLetter >= 65 && firstLetter <= 90)
    {
        // We want index = 0 when ASCII value = 65
        index = firstLetter - 65;
    }
    // Case: /Lowercase letters
    else if (firstLetter >= 97 && firstLetter <= 122)
    {
        //We want index = 0 when ASCII value = 97
        index = firstLetter - 97;
    }

    //Check to make sure the return value is actually between 0 and 25 (that the value
    //was actually changed
    if (index == 26)
    {
        printf("We could not hash %s.\n", word);
        return -1;
    }

    //Return index as intended
    return index;
}

// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
    // 1. Open dictionary file
    FILE *file = fopen(dictionary, "r");
    // Intermediate check to see if the file opened
    if (file == NULL)
    {
        printf("Could not open %s.\n", dictionary);
        unload();
        return false;
    }

    //Initialize a buffer variable where we are storing each word
    char storedWord[LENGTH + 1];

    // 2. Read strings from the file one at the time
    while(fscanf(file, "%s", storedWord) != EOF)
    {
        //3. Create a new node for each word
        node *newNode = malloc(sizeof(node));
        //Check if malloc() returns NULL
        if (newNode == NULL)
        {
            printf("You program ran out of memory\n");
            return false;
        }
        //Copy the word into the newly created node using strcpy()
        strcpy(newNode->word, storedWord);
        newNode->next = NULL;

        // Update "word loaded" count.
        wordLoadedCount++;

        // 4. Hash word to obtain hash value / index
        int index = hash(storedWord);

        //5. Insert node into the hash table at that location

        // If this bucket of the hash table is empty (not pointing at anything yet)
        // I'm not sure if this step is necessary
        if (table[index] == NULL)
        {
            table[index] = newNode;
            newNode->next = NULL;
        }

        // If it is not empty:
        else if (table[index] != NULL)
        {

            //a. Point new node to the existing first node
            newNode->next = table[index];

            //b. Point the list head to the new node
            table[index] = newNode;

        }

    }

    //Close the file to release memory
    fclose(file);

    return true;
}

// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{

    // If the dictionary was loaded...
    if (wordLoadedCount > 1)
    {
        // Go through hash stucture created in load() and count the words stored
        // I will do this inside the load function itself
        return wordLoadedCount;
    }

    // Return 0 if the dictionary not loaded
    return 0;
}

// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
    // Loop through each bucket in the hash table
    for (int i = 0; i < N; i++)
    {
        // COPIED FROM WEEK 5 LECTURE CODE
        // "Free list
        // Since we're freeing each node as we go along, we'll use a while loop
        // and follow each node's next pointer before freeing it, but we'll see
        // this in more detail in Problem Set 5."
        while (table[i] != NULL)
        {
        node *tmp = table[i]->next;
        free(table[i]);
        table[i] = tmp;
        }

        //Check to see if we did in fact clear the memory allocated to the hash table.
        if (table[i] != NULL)
        {
            printf("Something went wrong while freeing memory in unload() function.\n");
            return false;
        }
    }

    //Return true if sucessful
    return true;

}

A: Create a one word dictionary. Use it as both arguments to ./speller. Does program produce these counts results?

WORDS MISSPELLED:     0
  WORDS IN DICTIONARY:  1
  WORDS IN TEXT:        1

Concentrate on the size function to find the problem.


text:
Q: auto update python library In Windows OS, I have a python library in a git repository.
Some users, on different computers, use the library (scripts, etc), for routine tasks. But they have no knowledge of python or programming, only use the scripts.
when I push a new commit to repository, how they can get automatically update of library ?

A: What OS are you using?  Linux has a utility called cron that lets you schedule routine tasks.  You could tell cron on each computer to run cd repo && git pull every hour.
You might also consider doing something with a git hook:
http://git-scm.com/book/en/Customizing-Git-Git-Hooks

A: If each user has cloned the library repo to his site-packages, it is possible to schedule a task on their systems, which will do git pull with fixed frequency.
Here is a tutorial on how to setup a scheduled task on Winodws 7.


text:
Q: Mongodb Pushing document into array nested in object value Okay, well I'm building an app that uses nodejs and it has a pretty complex schema. Here's an example of what's going on there's giant document that looks like this:
var docJSON = {
  people:{
    funny:[{
      name:'Joe',
      height:177
    }]
  }
}

whenever I try to push a new object into funny It never gets pushed! No errors come up or anything.
The code I'm using right now to push into funny people is:
var funnyJSON = {
   name:'Paul',
   height:200,
}
mongo.get('people').update({_id:'SOME_STRING'},{
    $push:{'people.funny':funnyJSON}
},function(err){
    if(err) throw err;
});

A: Is your _id a BSON ObjectId? If so, try the following:
var ObjectID = require('mongodb').ObjectID;

mongo.get('people').update({_id: new ObjectID('SOME_STRING')},{
    $push:{'funny':funnyJSON}
},function(err){
    if(err) throw err;
});


text:
Q: What AngularJS design pattern to use with 2 services that have a common set of fields? I've got a situation where every solution I seem to come up with doesn't feel very "Angular" to me, so it makes me wonder if I'm missing an obvious approach somewhere. I have two services that share a common set of fields (in this case paging fields to help with paging data on a screen) -
app.service('service1', [function () {
        var model = this;

        model.totalItems = 0;
        model.currentPage = 1;
        model.itemsPerPage = 10;
}

app.service('service2', [function () {
        var model = this;

        model.totalItems = 0;
        model.currentPage = 1;
        model.itemsPerPage = 10;
}

This isn't too bad with just 3 fields, but as I've added more fields and functions I wind up duplicating a good bit of code. If I was just working with functions here, I could just share a common service between the two, but since I have data I can't use a singleton (both services need their own values in the fields). In an OO language like C# I would solve this with inheritance, but in the JS/Angular world that seems to be frowned upon because it tightly couples the services. Anyone have an approach to this that I'm missing?

A: If you feel like inheritance is the best way to model this then don't let Angular/JavaScript stop you from using it. You could set this up in Angular with something like this:
var ParentService = function() {
    this.totalItems = 0;
    this.currentPage = 1;
    this.itemsPerPage = 10;
}

var Service1 = function() {
    ParentService.call(this);
}
Service1.prototype = Object.create(ParentService.prototype);
app.service('service1', Service1);

var Service2 = function() {
    ParentService.call(this);
}
Service2.prototype = Object.create(ParentService.prototype);
app.service('service2', Service2);

If composition seems like a better fit you could use that instead. e.g.:
var ItemPageModel = function() {
    this.totalItems = 0;
    this.currentPage = 1;
    this.itemsPerPage = 10;
}
app.controller('itemPageModel', ItemPageModel);

var Service1 = function($controller) {
    this.model = $controller('itemPageModel');
}
Service1.$inject = ['$controller'];
app.service('service1', Service1);

var Service2 = function($controller) {
    this.model = $controller('itemPageModel');
}
Service2.$inject = ['$controller'];
app.service('service2', Service2);


text:
Q: How to print ClosedRange in Kotlin I'm learning Kotlin , and I'm trying to undetstand Ranges
I created a range of String as follows
val alpha = "A".."Z"

I want to print this for that I wrote
for (item in alpha) println(item)

But it gives the error

Error:(13, 18) Kotlin: For-loop range must have an 'iterator()' method

Can anyone help, how to print this range?

A: Well you can't do it with Strings by default, since there's no iterator() for ClosedRange<String>, but Chars will work directly:
val r = 'A'..'Z'
r.forEach(::println)

It will be of type CharRange and provide the needed iterator().
To make your very special example work with Strings, you could define your own extension function and delegate to a Iterator<Char>:
operator fun ClosedRange<String>.iterator(): Iterator<String> {
    val charIt = (start.toCharArray().first()..endInclusive.toCharArray().first()).iterator()

    return object : Iterator<String> {
        override fun hasNext() = charIt.hasNext()
        override fun next(): String = charIt.nextChar().toString()
    }
}

Now it works as you wished. But be aware that this does not make sense for most use cases with ranges of String.

A: val alpha = "A".."Z"

This is a plain range, which means it's an abstract representation of a contiguous subset within a total order. The only operation such an entity supports is answering the question "is this element within this range?", and it will be based purely on the contract of Comparable<T>.
In your case, consider a string like "THREAD". Does it belong to your range? It sorts higher than "A" but lower than "Z", so it does belong to it. But you probably didn't intend to iterate over it, or the infinity of all other strings belonging to your range.
What you considered as a given is actually a special case: iterable ranges. They are defined only on the three types representing integral types: IntRange, LongRange and CharRange. These are the types where the subset belonging to the range can actually be enumerated and iterated over.

A: I Loved The answers of @s1m0nw1 and @Marko Topolnik.
You can't really iterate over a ClosedRange<String>.
The literal may mislead us to think it's a ClosedRange<Char>
var range = "A".."C" // misleading literal

What you CAN do:
Just a small addition: is to map the characters to Strings
val r = ('A'..'Z').map { it.toString() }//.forEach(::println)
for (letter in r){

}

A:
How to print this range?

I think the only way to print this range is
println(alpha)

And you'll get
A..Z

This is how to "print" this range.
You're trying to travel through a non-iterable range, this is invalid.
Like, you cannot for (i in File("a.txt")..File("Main.java")) println(i).

A: Can You Try This May Help You, I think you actually want 'A'..'Z' not "A".."Z"
var A = 'A'..'Z'
for(value in A){
    println("$value")
}


text:
Q: Check list for strings using string? Hi I am having a little trouble testing a list to see if the list contains only strings. I am reading the documentation 2.3(Iterations, and Recursion) + 3.12 (Conditionals) and I can't quite seem to work lists in the way that I want.
I'm trying to keep it as simple as possible,
(define (strings-only? lst)
  [cond
    [(empty? lst) true]
    [else (string?(first lst))
          (string?(rest lst))]])

What I assume this does is first checks the list (lst) to see if it's empty.
Then it checks the first variable of the list to see if its a string, then checks the rest. When I put in
(define a (list "This" "that"))

It pops back that the test is false. I feel like the problem is with the way I'm trying to iterate through the list with first/rest. Any thoughts would be appreciated.

A: Check your else clause:
[else (string? (first lst))
      (string? (rest lst))]

1) You have two predicate calls that both return some boolean value, but you aren't connecting them in any way. You want to know if all elements in the list are strings, so what boolean operator (and, or, etc.) would fit best here?
2) (string? (rest lst)) is going to return false every time, because rest returns a list, not a string. To actually make this a recursive function, you want to call strings-only? again with the rest of the lst.

In summary:
(define (strings-only? lst)
  (cond
    [(empty? lst) true]
    [else (___ (string? (first lst))
               (strings-only? (rest lst)))]))

Fill in the blank with the boolean operator that makes the most sense here.

A: You can use the built in andmap function to accomplish this
(define (strings-only? lst)
  (andmap string? lst))


text:
Q: How to prevent table from being dropped? In PostgreSQL, how can I prevent anyone (including superusers) from dropping some specific table?
EDIT: Whoa, did we have some misunderstanding here. Let's say there is a big, shared QA database. Sometimes people run destructive things like hibernate-generated schema on it by mistake, and I'm looking for ways to prevent such mistakes.

A:
anyone (including superusers) from dropping some specific table?

Trust your peers.

A: You can do that by writing some C code that attaches to ProcessUtility_hook.  If you have never done that sort of thing, it won't be exactly trivial, but it's possible.
Another option might be looking into sepgsql, but I don't have any experience with that.

A: A superuser is precisely that. If you don't want them to be able to drop things, don't make them a superuser.
There's no need to let users run as superusers pretty much ever. Certainly not automated tools like schema migrations.
Your applications should connect as users with the minimum required user rights. They should not own the tables that they operate on, so they can't make schema changes to them or drop them.
When you want to make schema changes, run the application with a user that does have ownership of the tables of interest, but is not a superuser. The table owner can drop and modify tables, but only the tables it owns.
If you really, truly need to do something beyond the standard permissions model you will need to write a ProcessUtility_hook. See this related answer for a few details on that. Even then a superuser might be able to get around it by loading an extension that skips your hook, you'll just slow them down a bit.
Don't run an application as a superuser in production. Ever.
See the PostgreSQL documentation on permissions for more guidance on using the permissions model.

A: I don't think you can do that. You could perhaps have super super users who are going to manage the dropping of everything first. OR have backups constantly, so the higher member of the hierarchy will always have the possibility of retrieving the table.

A: I don't know what the real original intention of this question is... but a lot of people seem to have hypothetical answers like trusting your peers or using least permissions models appropriately. Personally, this misses the point altogether and instead answers with something everyone probably knew already, which isn't particularly helpful.
So let me attempt a question + answer of my own: How do you put in safety locks to prevent yourself or others from accidentally doing something you shouldn't? If you think that this "should never happen" then I think your imagination is too narrow. Or perhaps you are more perfect than me (and possibly a lot of other people).
For the rest of us, here is a solution that works for me. It is just a little lock that is put wherever you want it to - using event triggers. Obviously, this would be implemented by a super-user of some sort. But the point of it is that it has no bearing on permissions because it is error-based not permission based.
Obviously, you shouldn't implement this sort of thing if production behavior is dependent on it. It only makes sense to use in situations where it makes sense to use. Don't use it to replace what should be solved using permissions and don't use it to undermine your team. Use common sense - individual results may vary.

CREATE SCHEMA testst;

CREATE OR REPLACE FUNCTION manual_override_required() RETURNS event_trigger AS
$$
DECLARE
    obj record;
BEGIN
FOR obj IN SELECT * FROM pg_event_trigger_dropped_objects()
LOOP
    RAISE INFO 'object_oid: %, object_type: %', obj.objid, obj.object_type;
    RAISE info '%', obj.object_name;
    IF obj.object_type = 'schema' and obj.object_name = 'testst' THEN
        RAISE EXCEPTION 'You have attempted to DROP something which has been hyper-locked and requires manual override to proceed.';
    END IF;
END LOOP;
END
$$
LANGUAGE plpgsql
;

DROP EVENT TRIGGER IF EXISTS lock_schema;
CREATE EVENT TRIGGER lock_schema
   ON sql_drop
EXECUTE FUNCTION manual_override_required();

DROP SCHEMA testst;

-- produces error: "ERROR: You have attempted to DROP something which has been admin-locked and requires manual override to proceed."

-- To override the admin-lock (you have the permission to do this, it just requires two turns of a key and positive confirmation):

ALTER EVENT TRIGGER lock_schema DISABLE;

DROP SCHEMA testst;
-- now it works!

An example of how I use this is in automation workflows. I have to switch between dev and prod environments a dozen times a day and I can (i.e. have) easily lost track of which is which despite the giant flags and banners I've put up to remind myself. Dropping certain schemas should be a rare and special event in Prod (thus the benefit of a active-confirmation approach) whereas in dev I rebuild them all the time. If I maintain the same permission structures in Dev as in Prod (which I do) then I wouldn't be able to solve this.


text:
Q: L2 Norm of Pseudo-Inverse Relation with Minimum Singular Value Consider a matrix $A \in\mathbb R^{n\times m}$ with $n>m$. It has full column rank, i.e. $\operatorname{rank}(A)=m$. Its left pseudo-inverse is given by; $$A^{-1}_\text{left}=(A^TA)^{-1}A^T $$
From two different results during my studies, I have realized the following:
$$ \|A^{-1}_\text{left}\|_2 = \frac{1}{\sigma_{\min}(A)} $$
just like the case as if $A$ is square invertible matrix.
I have seen a similar question, however I couldn't relate the answer with the equality given above.
My question is: How can we show that the L2 norm of left pseudo-inverse of $A$ is related to its minimum singular value?
Thank you in advance for your help.

A: Hint: It suffices to prove the following facts:

*

*If $U,V$ are orthogonal (and square), then $\|AV\| = \|UA\| = \|A\|$

*$(U\Sigma V^T)^\dagger = V\Sigma^{\dagger}U^T$ (where $\dagger$ denotes the pseudo-inverse)

*If $\Sigma$ is a diagonal matrix of singular values, then $\|\Sigma^{\dagger}\| = 1/\sigma_{min}(\Sigma)$

Perhaps you can put the pieces together from here. Happily, this approach still works when $A$ does not have full column-rank.

A: For brevity, denote this left inverse $A^{-1}_{\text{left}}$ by $B$. It is well-known that $AB$ is the orthogonal projection onto the column space of $A$. Therefore, $ABy\perp(I-AB)y$ for every vector $y$. It follows that
\begin{aligned}
\|B\|_2&=\max_{y\ne0}\frac{\|By\|}{\|y\|}\\
&=\max_{y\ne0}\frac{\|By\|}{\|ABy+(I-AB)y\|}\\
&=\max_{By\ne0}\frac{\|By\|}{\|ABy+(I-AB)y\|}\\
&\le\max_{By\ne0}\frac{\|By\|}{\|ABy\|}\\
&\le\max_{x\ne0}\frac{\|x\|}{\|Ax\|}\\
&=\left(\min_{x\ne0}\frac{\|Ax\|}{\|x\|}\right)^{-1}\\
&=\frac{1}{\sigma_\min(A)}.
\end{aligned}


text:
Q: Is Princess Leia the only surviving member of royal family of Alderaan? Did any other members of House Organa survive the destruction of Alderaan?
Other survivors were scattered across the galaxy and hated the Empire. Who did they recognize as their ruler? If she was the only survivor, that would make her queen.

A: Yes, she was the sole heir to the throne
It seems this question has been somewhat addressed in newer Canon material. According to Star Wars: The Force Awakens: The Visual Dictionary (using this as an indirect reference), the monarchy of Alderaan was more like a traditional monarchy (unlike Naboo's elected one), and was passed down, and to the eldest child of the monarch. As their only child (albeit adopted, she was thus considered next in line for the throne to the survivors.
However, she never took up this role, and a regent ruled in her place. It also notes that by the time of The Force Awakens, virtually no one recognized the authority of the position anymore, having been left unfulfilled.

A: Princess Leia was the only one of the royal bloodline to survive, at least according to the man elected by the surviving Alderaanians to lead them to their new home. Apparently some other members of the "great houses" survived by leaving the planet in emergency craft (or simply not being there when Alderaan blew up).

Eglyn Valmor is up and pacing, as is her wont. "This is our home. This
patch of sky is ours. Our world was here. And the diaspora has
returned us to this place. We are home and I will not leave it." She
tugs on the loose braid from her ice-blond hair. She's young, Gale
thinks, unlike himself. But she's got a vital heart. He likes her. She
and the others are not royals — there exists only one of those, now — but
they are what the world has left. Alderaan has to be ruled by someone,
and the commoners are what remains. Valmor is not queen, but rather,
regent administrator.
Life Debt: Aftermath

Leia showed little interest in taking on the title of "Queen", actively rejecting it on at least one occasion.

Star Wars: Princess Leia #01
Apparently the surviving Alderaanians placed little importance in blood heritage as a means of determining their leadership

"Of course. I was sorry to hear of it." Lord Mellowyn had been a
distant kinsman to Bail Organa. Over the years, Leia had made a few
trips to visit him, since Mellowyn had been one of the few people who
still remembered her father and had called him friend.
(When she thought of her father, she thought only of Bail Organa. He
had been her father in spirit, and surely that was more important than
anything else.) "Well, the governorship passes down through the elder
bloodlines—" Lady Carise began, her dark-brown eyes alight at the
thought of royal titles. Virtually no one took the concept of
hereditary nobility seriously any longer, not even the other members
of the Elder Houses. However, Lady Carise seemed unable to imagine any
greater honor. "But as Lord Mellowyn had no children, the title has
now passed to you."
Star Wars: Bloodline


text:
Q: using nested printf statements giving strange output I recently came across this code and I'm unable to understand how it works
#include<stdio.h>
int main(){
    printf("Line 1\n",
    printf("Line 2\n",
    printf("Line 3\n",
    printf("Line 4\n",
    0))));
return 0;
}

It is giving the following output:
Line 4
Line 3
Line 2
Line 1

A: This isn't strange at all.
Expressions are evaluated (executed) from within to outside, just like mathematical expressions.
So put it simple terms: the expression with the most parentheses around it is evaluated / executed first.
Simplified it is:
printf("1", printf("2", printf("3", printf("4"))));

A: printf is used to print a formatted line. For example, to print an integer, you call:
printf( "%d", 1 );

What you did, is call it with the return value of the nested print as argument, which means that it first need to evaluate the nested call. Your call is similar to:
int temp;
temp = printf("Line 4\n", 0);
temp = printf("Line 3\n", temp);
temp = printf("Line 2\n", temp);
temp = printf("Line 1\n", temp);

Also, note that since you have no format specifiers in the format string, there is no meaning to the second argument, and if your compiler is nice enough it will even warn you about that.

A: You need to evaluate the parameter of a function before actually calling it. So the most inner print is called first.


text:
Q: Why CouldNotLockPageException occured on production server but not on local system? We are facing CouldNotLockPageException If this exception occurred on our production environment, we to have restart the tomcat.
When I tried to generate same exception on my local system as well as demo server. but it can't reproduce. for reproducing that exception we have tried with increase load on demo server hit the multiple url at time download and upload large files, but still I am not able to reproduce it.
below stack trace of CouldNotLockPageException, after this exception we have to restart the tomcat
stack trace

[WARN ] 2021-03-24 04:26:56.355 [http-nio-8080-exec-68] PageAccessSynchronizer - Thread 'http-nio-8080-exec-68' failed to acquire lock to page with id '1', attempted for 1 minute out of allowed 1 minute. The thread that holds the lock has name 'http-nio-8080-exec-66'.
[WARN ] 2021-03-24 04:26:56.357 [http-nio-8080-exec-68] PageAccessSynchronizer - "http-nio-8080-exec-66" daemon prio=5 tid=368 state=BLOCKED
org.apache.wicket.util.lang.Threads$ThreadDump: null
at biz.smart360.elastic.app.DefaultAppCache$DefaultUserCache.bizRepository(AppCache.scala:146) ~[elastic-app.jar:?]
at biz.smart360.biz.repository.BizUserSession.repositoryOperations(BizUserSession.scala:73) ~[smart360.jar:0.1.0-SNAPSHOT]
at biz.smart360.biz.repository.BizRepositoryOperationsDirectResolver.repositoryOperations(BizRepositoryOperationsDirectResolver.scala:21) ~[smart360.jar:0.1.0-SNAPSHOT]
at biz.smart360.biz.repository.BizRepositoryOperationsDirectResolver.openedTabularViewpointsMenu(BizRepositoryOperationsDirectResolver.scala:47) ~[smart360.jar:0.1.0-SNAPSHOT]
at biz.smart360.biz.repository.BizRepositoryOperationsResolverTransientProxyBase.openedTabularViewpointsMenu(BizRepositoryOperationsResolverTransientProxyBase.java:62) ~[smart360.jar:0.1.0-SNAPSHOT]
at biz.smart360.webapp.ui.component.navigation.RepositoryNavigationActionsPanel.onInitialize(RepositoryNavigationActionsPanel.java:101) ~[smart360.jar:0.1.0-SNAPSHOT]
at org.apache.wicket.Component.fireInitialize(Component.java:878) ~[wicket-core-7.9.0.jar:7.9.0]
at org.apache.wicket.MarkupContainer.internalInitialize(MarkupContainer.java:1070) ~[wicket-core-7.9.0.jar:7.9.0]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) [catalina.jar:9.0.41]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) [catalina.jar:9.0.41]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [catalina.jar:9.0.41]
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690) [catalina.jar:9.0.41]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) [catalina.jar:9.0.41]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [catalina.jar:9.0.41]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) [tomcat-coyote.jar:9.0.41]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-coyote.jar:9.0.41]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:888) [tomcat-coyote.jar:9.0.41]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597) [tomcat-coyote.jar:9.0.41]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-coyote.jar:9.0.41]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) [?:?]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) [?:?]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-util.jar:9.0.41]
at java.lang.Thread.run(Thread.java:834) [?:?]
[ERROR] 2021-03-24 04:26:56.359 [http-nio-8080-exec-68] InMemoryErrorReporting - Error with id 19bbb439-e89f-40ad-89c3-a05a6805e53e registered for user jiwon.lim1@y-k.co.kr:
org.apache.wicket.page.CouldNotLockPageException: Could not lock page 1. Attempt lasted 1 minute
at org.apache.wicket.page.PageAccessSynchronizer.lockPage(PageAccessSynchronizer.java:167)
at org.apache.wicket.page.PageAccessSynchronizer$2.getPage(PageAccessSynchronizer.java:245)
at org.apache.wicket.DefaultMapperContext.getPageInstance(DefaultMapperContext.java:113)
at org.apache.wicket.core.request.handler.PageProvider.getStoredPage(PageProvider.java:299)
at org.apache.wicket.core.request.handler.PageProvider.isNewPageInstance(PageProvider.java:211)
at org.apache.wicket.core.request.mapper.AbstractBookmarkableMapper.checkExpiration(AbstractBookmarkableMapper.java:335)
at org.apache.wicket.core.request.mapper.AbstractBookmarkableMapper.processHybrid(AbstractBookmarkableMapper.java:258)
at org.apache.wicket.core.request.mapper.AbstractBookmarkableMapper.mapRequest(AbstractBookmarkableMapper.java:364)
at org.apache.wicket.request.mapper.CompoundRequestMapper.mapRequest(CompoundRequestMapper.java:147)
at org.apache.wicket.protocol.https.HttpsMapper.mapRequest(HttpsMapper.java:101)
at org.apache.wicket.request.cycle.RequestCycle.resolveRequestHandler(RequestCycle.java:189)
at org.apache.wicket.request.cycle.RequestCycle.processRequest(RequestCycle.java:219)
at org.apache.wicket.request.cycle.RequestCycle.processRequestAndDetach(RequestCycle.java:293)
at org.apache.wicket.protocol.http.WicketFilter.processRequestCycle(WicketFilter.java:261)

A: Wicket throws CouldNotLockPageException when an HTTP request cannot get a lock on a page instance for some duration (the default is 1 minute).
In your particular case an HTTP worker thread has acquired a lock on that page instance and waits at:
biz.smart360.elastic.app.DefaultAppCache$DefaultUserCache.bizRepository(AppCache.scala:146)

For some reason this method takes more than a minute.
You need to debug why it takes so long.
To reproduce it locally you could add TimeUnit.SECONDS(90).sleep() at RepositoryNavigationActionsPanel.onInitialize(RepositoryNavigationActionsPanel.java:101) and then load the page and click on some Ajax link in it.


text:
Q: For loop with binary numbers I want to use a for loop in Verilog to get from binary 0000000 to 0011111.  I have a problem with the increment part of the for loop. How should I exactly move to get to the 0011111?
I tried the following code, but it gives me an error.
for(DATA_IN=7'b0000000; DATA_IN<=7'b0011111; 1<<DATA_IN);

A: The expression 1<<DATA_IN is illegal syntax for the for_step part of the for loop.  Typically, you need to make an assignment to the iterator variable: DATA_IN=...  Refer to IEEE Std 1800-2017, section 12.7.1 The for-loop.
For example, to increment by 1 each time through the loop, use DATA_IN=DATA_IN+1.  Here is a self-contained example:
module tb;

reg [7:0] DATA_IN;

initial begin
    for (DATA_IN=7'b0000000; DATA_IN<=7'b0011111; DATA_IN=DATA_IN+1) begin
        $displayb(DATA_IN);
    end
end

endmodule

Output:
00000000
00000001
00000010
00000011
00000100
00000101
00000110
00000111
00001000
00001001
00001010
00001011
00001100
00001101
00001110
00001111
00010000
00010001
00010010
00010011
00010100
00010101
00010110
00010111
00011000
00011001
00011010
00011011
00011100
00011101
00011110
00011111


text:
Q: Variable product selectors: Getting the live selected values In WooCommerce use the code below to add a custom label after product prices in simple and variables products:
add_filter('woocommerce_variation_price_html','prices_custom_labels', 10, 2    );
add_filter('woocommerce_price_html','prices_custom_labels', 10, 2 );
function prices_custom_labels( $price, $product ){

    // Set HERE your custom labels names
    $per_dozen = ' '. __('per dozen', 'woocommerce' );
    $per_case = ' '. __('per case (20 dozens)', 'woocommerce' );

    // 1) Variable products
    if ($product->product_type != 'simple' && $product->variation_id ) {

        // Getting the array of existing attributes values for a variation
        $variation_attribute_value = $product->variation_data;
        // Here we keep only the last value in this array
        $last_variation_attribute_slug_value = ' ' .    end($variation_attribute_value);

        // Finding the word 'case' in the attribute value slug
        $has_case = strstr($last_variation_attribute_slug_value, 'case');

        // Setting the right displayed label depending on attribute value slug
        if( $has_case )
            $attribute_quantity_name_value = $per_case;
        else
            $attribute_quantity_name_value = $per_dozen;

        // Here the output price + custom label
        $price = ''.woocommerce_price( $product-   >regular_price ).$attribute_quantity_name_value.'';
    }
    // 2) Simple products
    else
    {
        // Here the output price + custom default label
        $price = ''.woocommerce_price( $product-  >regular_price ).$per_dozen.'';
    }
    return $price;
}

But in variable products, I have an issue with the appended custom label in the  live displayed price. The code that I use only display after the live price "per dozen".
I will need to get the selected value on the custom "quantity" selector to add the right label after the price:

*

*If the selected value is "Dozen" I need to display after live price " per dozen",

*If the selected value is "Case (20 dozens)" I need to display after live price " per case (20 dozens)".

This screenshot is what I have actually for all cases:

Check this issue on my web site specific product page

So I would need to get the attribute "quantity" selected value to append the right label to the live price.

What can I do to get that working?

A: The only way to get this working is to use Javascript / jQuery, but it's complicated as WooCommerce is already running  some Javascript / Ajax code on it.
First, Is not possible to detect the selected customer choice on the selectors as WooCommerce remove "selected" attribute from <option> html tags.

Once customer have make a complete selection (so choosed one variation from this variable product), Woocommerce add the corresponding variation ID value in a hidden <imput> html field and display the corresponding price.
Our PHP code pass to javascript an array of the variations IDs for this variable product, with the corresponding value of the "quantity" attribute for each of them.
Then we can use the "on blur" javascript event on the <select> html tags to get that hidden variation ID value and then append the price with the right "label".

Here is that functional code, that will add a custom label to the live price depending on the customer selection (so the selected product variation):
add_action( 'woocommerce_after_add_to_cart_form', 'custom_get_variations_js' );
function custom_get_variations_js() {
    global $product;

    // Set HERE your "quantity" attribute slug
    $attribute_qty_slug = 'pa_quantity';
    $attribute_qty_slug_key = 'attribute_'.$attribute_qty_slug;

    foreach($product->get_available_variations() as $values){
        $attribute_qty_slug_value = $values['attributes'][$attribute_qty_slug_key];
        $attribute_qty_name_value = get_term_by( 'slug', $attribute_qty_slug_value, $attribute_qty_slug );
        $variations_id_arr[$values['variation_id']] = __(' per ', 'woocommerce' ) . strtolower($attribute_qty_name_value->name);
    }

    ## THE JQUERY SCRIPT ##
    ?>

    <?php
}

Then we need to change your existing code to avoid displaying a second custom label on this specifics variable products (in the first hooked function):
add_filter('woocommerce_variation_price_html','prices_custom_labels', 10, 2 );
add_filter('woocommerce_price_html','prices_custom_labels', 10, 2 );
function prices_custom_labels( $price, $product ){

    // Custom label name
    $per_dozen = ' '. __('per dozen', 'woocommerce' );

    // Set HERE your "quantity" attribute slug
    $attribute_qty_slug = 'pa_quantity';

    $attribute_qty_slug_key = 'attribute_'.$attribute_qty_slug;
    $append_label = '';

    // 1) Variable products
    if ($product->product_type != 'simple' && $product->variation_id ) {

        // Getting the attribute "quantity" value
        $attribute_qty_is_set = $product->variation_data[$attribute_qty_slug_key];
        echo '
'; print_r($product->variation_data[$attribute_qty_slug_key]); echo '
';

        // if "quantity" not set we display " per dozen"
        if( ! $attribute_qty_is_set )
            $append_label = $per_dozen;

        // Outputed price + custom label
        $price = ''.woocommerce_price( $product->regular_price ).$append_label.'';
    }
    // 2) Simple products
    else
    {
        // Here the output price + custom default label
        $price = ''.woocommerce_price( $product->regular_price ).$per_dozen.'';
    }
    return $price;
}

add_filter('woocommerce_variable_price_html', 'prices_custom_labels_min_max', 20, 2);
function prices_custom_labels_min_max( $price, $product) {

    // Custom label name
    $per_dozen = ' '. __('per dozen', 'woocommerce' );
    $per_case = ' '. __('per case', 'woocommerce' );

    // Set HERE your quantity attribute slug
    $attribute_qty_slug = 'pa_quantity';

    // Getting the min and max variations prices
    $variation_min_reg_price = $product->get_variation_regular_price('min', true);
    $variation_max_reg_price = $product->get_variation_regular_price('max', true);
    $variation_reg_price = $product->get_variation_regular_price();

    if( $variation_min_reg_price == $variation_max_reg_price )
    {
        $price = ''.woocommerce_price($variation_reg_price) . $per_dozen . '';
    }
    else
    {
        if( !in_array( $attribute_qty_slug, array_keys( $product->get_attributes() ) ) )
        {
            $price = '' . woocommerce_price($variation_min_reg_price) . $per_dozen . ' - ' . woocommerce_price($variation_max_reg_price) . $per_dozen . '';
        }
        else
        {
            $price = '' . woocommerce_price($variation_min_reg_price) . $per_dozen . ' - ' . woocommerce_price($variation_max_reg_price) . $per_case . '';
        }
    }
    // print_r($product->get_attributes());
    return $price;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Related answer:

*

*Pass the chosen product variations data into Contact Form 7 enquiry form

*Adding custom text labels to the product prices depending on their type

A: It should'nt be 'case' it should 'Case', strstr is a case sensitive function and as it is boolean the below statment will return false always. Because the values in ur selector is Case (20 dozens) not case (20 dozens) See the reference below to know more.
Thus change the below line:
$has_case = strstr($last_variation_attribute_slug_value, 'case');

to:
$has_case = strstr($last_variation_attribute_slug_value, 'Case');

ref: https://www.w3schools.com/php/func_string_strstr.asp


text:
Q: How can a socket connect when bound to a specific ethernet interface that's also being used by VPN / utun interface? I'm trying to write a function that can connect to a server using a specific network interface so that it's consistently routed through that interface's gateway. This is on a macOS system that has one or more VPN connections.
Here's a proof-of-concept test function I've written:
void connectionTest(const char *hostname, int portNumber, const char *interface) {
    struct hostent *serverHostname = gethostbyname(hostname);

    if (serverHostname == NULL) {
        printf("error: no such host\n");
        return;
    }

    int socketDesc = socket(AF_INET, SOCK_STREAM, 0);
    int interfaceIndex = if_nametoindex(interface);

    if (interfaceIndex == 0) {
        printf("Error: no such interface\n");
        close(socketDesc);
        return;
    }

    // Set the socket to specifically use the specified interface:
    setsockopt(socketDesc, IPPROTO_IP, IP_BOUND_IF, &interfaceIndex, sizeof(interfaceIndex));

    struct sockaddr_in servAddr;
    bzero((char *)&servAddr, sizeof(servAddr));
    servAddr.sin_family = AF_INET;
    bcopy((char *)serverHostname->h_addr, (char *)&servAddr.sin_addr.s_addr, serverHostname->h_length);
    servAddr.sin_port = htons(portNumber);

    if (connect(socketDesc, (struct sockaddr *)&servAddr, sizeof(servAddr)) < 0) {
        printf("connect failed, errno: %d", errno);
        close(socketDesc);
        return;
    }

    printf("connection succeeded\n");
    close(socketDesc);
}

This function will successfully connect so long as the interface is one of the utun interfaces created by the VPNs, or a physical interface that is not used by the VPNs. But if I try to use the physical interface that is used by the VPNs, the function fails with errno 51: Network is unreachable.
For a more specific example, consider a system with the following network interfaces:
en0: Ethernet connection
en1: Wi-Fi connection
utun10: VPN connection 1, connected via en0
utun11: VPN connection 2, also connected via en0
If I call my function with something like:
connectionTest("api.ipify.org", 80, "en1");
connectionTest("api.ipify.org", 80, "utun10");
connectionTest("api.ipify.org", 80, "utun11");

... it will succeed. However, this is what produces the "network unreachable" error:
connectionTest("api.ipify.org", 80, "en0");

Is there some way to have the function work in the case of en0? (Preferably without changing the system's routing table just for this one connection?)
Edit:
It looks like the system doesn't know how to route packets through en0 when the VPN is up, unless it has a non-default route for en0.
I tried using the route command to check which route in the table would be used for a specific interface, and I get the following:
$ route get -ifscope en0 1.1.1.1
route: writing to routing socket: not in table

Only -ifscope en0 produces that error. However, the route table indicates there is a default route for en0. Here is the routing table when only ethernet and the VPN are connected (so no Wi-Fi or second VPN):
$ netstat -rn
Routing tables

Internet:
Destination        Gateway            Flags        Refs      Use   Netif Expire
0/1                10.16.0.1          UGSc          165        0  utun10
default            192.168.20.1       UGSc            0        0     en0
10.16/16           10.16.0.8          UGSc            3        0  utun10
10.16.0.8          10.16.0.8          UH              2        0  utun10
127                127.0.0.1          UCS             0        0     lo0
127.0.0.1          127.0.0.1          UH              7  7108160     lo0
128.0/1            10.16.0.1          UGSc           40        0  utun10
169.254            link#8             UCS             1        0     en0      !
192.168.20         link#8             UCS             9        0     en0      !
192.168.20.1/32    link#8             UCS             2        0     en0      !
224.0.0/4          link#22            UmCS            0        0  utun10
224.0.0/4          link#8             UmCSI           1        0     en0      !
224.0.0.251        1:0:5e:0:0:fb      UHmLWI          0        0     en0
255.255.255.255/32 link#22            UCS             0        0  utun10
255.255.255.255/32 link#8             UCSI            0        0     en0      !

There's clearly a default route listed for en0 pointing to its gateway, 192.168.20.1. Why isn't the packet being routed? If I create a static route for 1.1.1.1/32 or even 1/8 it will work. But so long as en0 only has a default route, it won't work. It's like the default route has been disabled somehow.
Edit 2:
If I add a new route to the table using:
$ route add -ifscope en0 0/0 192.168.20.1

so that the routing table now includes the following entry:
Destination        Gateway            Flags        Refs      Use   Netif Expire
default            192.168.20.1       UGScI           1        0     en0

alongside all of the above entries, so there are now two default entries, then the connection works. Why is it necessary for there to be an interface-specific default route in order for this to work?

A: Once you added the routing table to your question, your problem became obvious.
It is the routing table that determines to which gateway a packet is sent. The routing table tells the sending host to which gateway the packet is sent. It does that by comparing the destination address to the routes in the routing table. The most-specific (longest match) route is used. A default route is the least-specific (shortest match) route, and it is used as the route of last resort when there are no more-specific routes in the routing table.
Based on the routing table you provided, any packet with a destination address from 1.0.0.0 to 126.255.255.255 (0.0.0.0/8 and 127.0.0.0/8 are exceptions as unusable ranges) will match the 0/1 routing table entry rather than the default route (0/0), and any packet with a destination address from 128.0.0.0 to 223.255.255.255 (224.0.0.0/4 is multicast, and 240.0.0.0/4 is unusable) will match the 128/1 routing table entry rather than the default route (0/0), because the route length of 1 is more specific than the default route length of 0. That means any packets destined to an address in those ranges (combined, all addresses destined for a different network) will be sent to the gateway (10.16.0.1) referenced by the routing table entries for the 0/1 and 128/1 routes.
To solve your problem, you need to remove the 0/1 and 128/1 routing table entries and replace them with one or more entries that are restricted to the networks which the tunnel can reach. With that, the entries not matching the tunnel route(s) or other more specific routing table entries will use the default route.


text:
Q: Nested REST call in REST-datasource bound Listview I have a Windows 8 JavaScript application, in which I am binding a VirtualDataSource retrieving products from a RESTful service to a Listview.
//fetch data as user scrolls
itemsFromIndex: function (requestIndex, countBefore, countAfter) {

           return WinJS.xhr(options).then(
                //Callback for success
                function (request) {
                    var results = [], count;
                    console.log("request.responseText: " + request.responseText);
                    // Use the JSON parser on the results, safer than eval
                    var obj = JSON.parse(request.responseText);

                    console.log("obj: " + obj);

                    // Verify if the service has returned images
                    if (obj.length > 0) {
                        var items = obj;
                        console.log("returned items: " + items.length);
                        console.log("returned items: " +items[0].productid);
                        // Data adapter results needs an array of items of the shape:
                        // items =[{ key: key1, data : { field1: value, field2: value, ... }}, { key: key2, data : {...}}, ...];
                        // Form the array of results objects
                        for (var i = 0, itemsLength = items.length; i < itemsLength; i++) {
                            var dataItem = items[i];
                            var text = "aaa";
                            **var a = fetchPrice(dataItem.productid);**
                            console.log("shortText = " + a.text);
                            results.push({
                                key: (fetchIndex + i).toString(),
                                data: {
                                    productId: dataItem.productid,
                                    price: a
                                }
                            });
                        }

so far so good... now for the trouble... once I have retrieved all products, I need to display e.g. the price of a product by calling another webservice, but within the same listview template.
What is the best way of going about this? As you may see, I already added code like fetchPrice, which is another WinJS.xhr call. Is there a better way of doing this? Can I bind a price html-element to a productid which will only become available at runtime?
Please help!
Thanks,
Thomas
--
Actually got a bit further now:
                    var obj = JSON.parse(request.responseText);

                    console.log("obj: " + obj);

                    // Verify if the service has returned images
                    if (obj.length > 0) {
                        var items = obj;
                        console.log("returned items: " + items.length);
                        console.log("returned items: " + items[0].productid);
                        var priceText;
                        that.getPriceText(items[0].productid).done(function (b) { priceText = b; console.log("in function : " + priceText); });
                        console.log("priceText is " + priceText);
                        // console.log("var b = " + b.isPrototypeOf);
                        // Data adapter results needs an array of items of the shape:
                        // items =[{ key: key1, data : { field1: value, field2: value, ... }}, { key: key2, data : {...}}, ...];
                        // Form the array of results objects
                        for (var i = 0, itemsLength = items.length; i < itemsLength; i++) {
                            var dataItem = items[i];

                            results.push({
                                key: (fetchIndex + i).toString(),
                                data: {
                                    productId: dataItem.productid,
                                    price: priceText
                                }
                            });
                        }

The console output of the second line saying console.log (console.log("priceTextis " + priceText)) returns undefined: this is expected, as the priceText async call has not yet finished.
The priceText output within the .done function of the async call is output to the console correctly. (Line reading ("in function : " etc.)
How can I directly pass the value of the async call into the price field in the lines where items are being pushed onto the return array?
I have already tried setting price to the .done Promise return value:
price : that.getPriceText(items[0].productid).done(function (b) { return b; })
however, in my WebApp, price is then still "undefined", I assume because the first promise returning all items finished and displays all results.
This is actually what I want: display all product details, and then asynchronously retrieve the price.
Can anyone suggest the best method to achieve this?
Thanks!


text:
Q: How to go at particular value of counter in for loop using gdb? I have a for loop of about 100 odd values. I want to have a breakpoint where I can set some value for the iterator variable and then directly go on that program execution state.
For example
for(int i=0;i<500;i++)
{
  doSomething();
}

Here I want to have a breakpoint on i=100; and step through all values from 0 to 99 in one go. Is this possible in gdb and how do I do it?

A: In gdb you can set conditions on breakpoints.
break line if i == 100

Where "line" is the appropriate line number.

A: There is probably a better way, but I have gotten a lot of mileage out of doing things like this:
if (i == 100) {
    int breakpoint = 10;
}

A: A conditional breakpoint is one that only transfers control to gdb only when a certain condition is true.
This can be useful when you only want gdb control after say 10 iterations of a loop.
To set a condition on a breakpoint, use the condition command with the number of the breakpoint followed by the condition on which to trigger the breakpoint.
Here is an example where setting a conditional breakpoint that will only be triggered when the "condition (i >= 10) is true":
(gdb) break 28                                  # set breakpoint at line 28
(gdb) info break                                # list breakpoint information
  Num Type           Disp Enb Address    What
   1   breakpoint     keep y   0x080588a3 in loopit at loops.c:28

(gdb) condition 1 (i >= 10)                # set condition on breakpoint 1
(gdb) run   (or write `continue` if already running)


text:
Q: Issues with OpenSessionInView I have implemented Spring/Hibernate's OpenSessionInView Pattern for Lazy Loading.  I am facing either "No Sessoon" or "2 or more sessions" issue.  Let me know If I am missing any steps:
Here are detail code fragments:
Web.XML
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
      </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
  </listener>

      <filter>
        <filter-name>hibernateFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
        <init-param>
          <param-name>singleSession</param-name>
          <param-value>false</param-value>
        </init-param>
        <init-param>
          <param-name>flushModeName</param-name>
          <param-value>FLUSH_AUTO</param-value>
        </init-param>
        <init-param>
          <param-name>sessionFactoryBeanName</param-name>
          <param-value>sessionFactory</param-value>
        </init-param>
      </filter>

       <filter-mapping>
         <filter-name>hibernateFilter</filter-name>
         <url-pattern>/*</url-pattern>
         <dispatcher>REQUEST</dispatcher>
         <dispatcher>FORWARD</dispatcher>
       </filter-mapping>

applicationContext.xml
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan"
        value="com.mypack.common.model, com.mypack.school.model" />
        .
        .
        <!-- Other properties -->
        .
</bean>

customer.xhtml
XHTML user interface has autocomplete box showing customer code. Autocomplete query make use of CompleteCustomer Method, whereas getCustomerbyCode is called by converter bean.
Upon selection of cust code, screen is populated by selected customer details. Application User is allowed to make changes and save updates in DB.
CustomerBean.java
@ManagedBean (name="customerBean")
@ViewScoped
public class CustomerBean implements Serializable {

    public List<Customer> completeCustomer(String query) {
        List<Customer> suggestions;

        suggestions = (List<Customer>) customerService.getCustomerslikeCodeOrName(query, authenticationBean.getTenantId());

        return suggestions;
    }

    public void saveCustomerDetails() {
        // Save or Update User Information in Database
        customerService.saveCustomer(custMaster);
        return;
    }

CustomerServiceImpl.java
@Service("customerService")
@Transactional(readOnly = true, propagation=Propagation.REQUIRED)
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    CustomerDAO custMasterDAO;

    @Override
    @Transactional(readOnly = false,propagation = Propagation.REQUIRED)
    public void saveCustomer(Customer custDetails) {
        custMasterDAO.saveCustomer(custDetails);
    }

    @Override
    public Customer getCustomerbyCode(String custCode, TenantId tenantId) {
        return custMasterDAO.getCustomerbyCode(custCode, tenantId);
    }

    @Override
    public List<Customer> getCustomerslikeCodeOrName(String custIDName, TenantId tenantId) {
        return custMasterDAO.getCustomerslikeCodeOrName(custIDName, tenantId);
    }
}

CustomerMasterDAO.java
    @SuppressWarnings("unchecked")
    @Override
    public List<Customer> getCustomerslikeCodeOrName(String custIDName, TenantId tenantId) {
        List<Customer> listCustomers = null;
        custIDName = "%" + custIDName + "%";

        Session session = SessionFactoryUtils.getSession(sessionFactory, false);
        Transaction tx = session.beginTransaction();

        try {
            query = session.createQuery("from Customer " +
                    "where (custId like :codename " +
                    "or custFirstName like :codename " +
                    "or custMiddleName like :codename " +
                    "or custLastName like :codename)")
                .setParameter("codename", custIDName);
            listCustomers = query.list();

        } catch(Exception ex) {
            tx.rollback();
            System.out.println("*** getCustomerslikeCodeOrName ***" + ex.getMessage());
        }

        return listCustomers;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Customer getCustomerbyCode(String custCode, TenantId tenantId) {
        List<Customer> list = null ;
        Query query;

        Session session = SessionFactoryUtils.getSession(sessionFactory, Boolean.FALSE);
        Transaction tx = session.beginTransaction();

        Filter sessionFilter = session.enableFilter("BankRecordFilter");
        sessionFilter.setParameter("bankCode", tenantId.getBankCode());

        try {
            query = session.createQuery("from Customer where custId = :custCode");
            list = query.setParameter("custCode", custCode).list();
        } catch (Exception ex) {
            tx.rollback();
            System.out.println("*** getCustomerbyCode ***" + ex.getMessage());
        }
        if (list == null || list.size() < 1){
//          System.out.println("No Records Found");
            return null;
        }
        return (Customer)list.get(0);
    }

    @Override
    public void saveCustomer(Customer custDetails) {
        Session session = getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();

        try {
            session.saveOrUpdate("bkCustomer", custDetails);
            session.getTransaction().commit();

        } catch (Exception e) {
            session.getTransaction().rollback();
            e.printStackTrace();
        }

    }

Table definations are stored in .hbm.xml files.
I have tried lot of combinations of placing following statements to get session:
    session = getSessionFactory().getCurrentSession();
    Session session = SessionFactoryUtils.getSession(sessionFactory, Boolean.FALSE);
Also transaction in different ways and different location.  I am  either getting error messages for No Session or Two or more sessions are attached error message.
Can you please let me know what is wrong with my code.
Regards,
Shirish

A: Finally I am able to use OpensessionInView.  After spending lot of time on this issue, I observed that LAZY loading was working as per expection, but when I am trying to save date, Session was not properly propagted.
After updating propagation strategy, code started working..  Here is updated code
@Transactional(readOnly = false,propagation = Propagation.NESTED)
@Override
    public void saveCustomer(Customer custDetails) {
        Session session = getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();

        try {
            session.saveOrUpdate("bkCustomer", custDetails);
            session.getTransaction().commit();

        } catch (Exception e) {
            session.getTransaction().rollback();
            e.printStackTrace();
        }

A: You are mixing annotations for transaction handling and programmatic transaction handling.  Looks like your annotations are simply not used...


text:
Q: Nothing appears on the Panel in Ubuntu 14.04 I recently installed Ubuntu 14.04. This was my first Ubuntu installation. The Unity Launcher and Panel did not appear at first but I fixed it by searching from the internet. Now the Panel appears, but it's empty. Only the title of the active window appears and nothing else. The power button, the clock, mail, sound, other indicators nothing appears.
I tried resetting and reinstalling unity. I tried killall unity-panel-services but it says no process found.

A: Try the following commands in a terminal:
sudo apt-get install dconf-tools

dconf reset -f /org/compiz/

setsid unity

unity --reset-icons

Edit: Is this helping you?

A: open startup application and add this command

/usr/lib/x86_64-linux-gnu/indicator-application/indicator-application-service

after logout and login again to your account


text:
Q: How to get the localized version of the months from angularjs? How would I get a localized version of every month in angularjs in an array?  I know how to localize a single date using the format options, but in this case I want all of the months.  Basically, this is going to be bound to a select that the user can than choose a month.

A: I m guessing that your page will be entirely localized in a given language and that you will add the proper angular-locale file as such :
<script src="http://.../angular-locale_xx-xx.js"></script> // ex: angular-locale_fr-fr.js

If this is the case you can simply access all the months as an array like that :
function Controller($scope, $locale) { //inject the $locale service
  var datetime = $locale.DATETIME_FORMATS; //get date and time formats
  $scope.months = datetime.MONTH; //access localized months
}

You can see a working plunker here


text:
Q: Hyper-V reports that the hypervisor is not running. How to start the hypervisor? I've created and run Hyper-V guests on this machine in the past. VT extensions are enabled in the BIOS; no changes made there. I've changed my boot device order recently.
How can I ensure that Hyper-V's host hypervisor is started on Windows startup?
When attempting to start a VM, the Hyper-V Manager error shows:

An error occurred while attempting to start the selected virtual machine(s).
Failed to restore virtual machine state.
Virtual machine 'Windows 10 Tech Preview' could not be started because the hypervisor is not running.

The Hyper-V Virtual Machine Management service is set to Automatic.

I've previously run bcdedit /set hypervisorlaunchtype auto as Administrator.
No other VM products like VMWare or Virtualbox is installed.

A: I had exactly same problem and tips by Daniel B and Norman helped me: Running bcdedit alone revealed that hypervisorlaunchtype was indeed set to off so bcdedit /set hypervisorlaunchtype auto followed by a reboot did the trick.
I am reposting their comments as an answer to preserve them.
This was caused by (unsuccessful) attempt to run Android emulator from Android Studio.

A: For other users: I had exactly the same error.
Running bcdedit /set hypervisorlaunchtype auto did not help me.
Finally I figured out that I need to enable virtualization-related settings in BIOS first (I did not notice that from the question above initially).

A: [Update]
Microsoft released a fix for this (KB5010794), so install the fix rather than removing the update to avoid negative security implications.
Previous comment:
I just encountered this problem. My hyper-v machines were all working perfectly and then the windows server updated overnight and none would start up the next day. The bcdedit did not help for me. It was caused by KB5009624 or KB500263. Removing both of these and then rebooting fixed my issue.

A: If it suddenly occurs starting 2022, this problem is due to bad patching.
KB5009624 is directly at fault and the issue should be solved if it is uninstalled.
This problem occurred for me for Windows 2012 R2 servers.
The updates at fault in question (depending on server version) are: KB5009624 (Windows Server 2012 R2), KB5009557 (Windows Server 2019) and KB5009555 (Windows Server 2022).
Other related patches that came in the same batch (may affect more or less the issue in the case of 2021 R2):
KB5009595

KB5008893

KB5008891

KB5008870

KB5008868

MS Tech Community link

A: Since I've tried to install Docker for Windows, I found out that my CPU just can't run Hyper-V although I could install it.
This page explains that Windows 8 Hyper-V Client (and I think Windows 10 too) requires a SLAT-capable CPU to run.
To check your CPU capabilities, use the Coreinfo utility (https://technet.microsoft.com/en-us/sysinternals/cc835722) with the option -v, the '-' character indicates that the feature is missing.

Maybe your CPU lacks some features too, hope it helps !

A: I had the very same error when using Macrium Reflect's viBoot with Hyper-V on Windows 11, but the other answers did not apply. We are not using Windows Server, bcdedit hypervisorlaunchtype was already set to auto, everything was working until we installed Virtualbox (after already disabling Hyper-V) and we had rebooted both the VM & the host OS.
We had previously used Virtualbox, but that had been uninstalled and the bcdedit was returned to normal (i.e., auto) so that we could return to Hyper-V.
The solution was a somewhat lengthy set of shut downs / boots:

*

*Disable Hyper-V via the Features Add / Remove panel.

*Shut down the PC.

*Boot the PC.

*Enable Hyper-V

*Shut down the PC.

*Boot the PC.

While Windows recommended restarting, for some reason that did not work for us even after a few hours of trying fixes & rebooting. The error message in Macrium noted that some BIOS option changes required a shutdown + fresh boot (and not a reboot), so we wondered if that applied to Hyper-V changes, too? We tried it and it worked.
Throughout all these procedures, hypervisorlaunchtype remained auto which is the most common solution I believe.
Tested on

*

*Windows 11 Pro (22000.556)

*Macrium Reflect v8.0.6635 viBoot w/ Hyper-V

With this, we were finally able to boot into a Windows XP 32-bit guest OS.

A: I got this exact problem after changing a motherboard on a HyperV host computer
Enabling Intel Virtualisation technology in the BIOS fixed it

A: Try Updating linux Kerner
Cheers


text:
Q: Get a data from a web page into a PDF format using Tomahawk in JSF? i am a newbie to JSf and Tomahawk Technology. In application i am having a datatable, i want store the information from he data table into a PDF format on a click of a button using Tomahawk and SandBox.Kindly Help.

A: Even better, use JasperReports. It uses iText behind the scene to export reports to PDF.

A: You may need iText for this.
Also see this - http://www.junlu.com/msg/281869.html

A: As you have mentioned you are using sandbox, use exporterActionListener component in the sandbox to export the data from data tabel into PDF. You need the itext-0.99.jar use the same version
Code sample
<!-- sandbox tag library declaration -->
<%@ taglib uri="http://myfaces.apache.org/sandbox" prefix="s"%>
   .
   .  <!-- your data Tabel will be here -->
   .
   .

<h:commandButton value="Export as pdf">
     <s:exporterActionListener for="Id of the Data Tabel" fileType="PDF" />
</h:commandButton>


text:
Q: Proof that $\int_0^1\frac{(-\log u)^s}{u^s}du=\frac{\Gamma(s+1)}{(1-s)^{s+1}}$ for $|\Re s|<1$ After I've read an identity involving an integral related with special functions, I've consider a different integral by trials asking to Wolfram Alpha online calculator

Example For the code int_0^1 (-log u)^s/u^s du the online calculator said that is equal to $$(1-s)^{-s-1}\Gamma(s+1)$$
  for $-1<\Re s<1$.

Thus we take here $s=\sigma+it$ the complex variable, and the logarithmic function as you see is the natural logarithm. I've refreshed my knowdledges in complex analysis integration, thus I known the more relevant theorems: Cauchy formula and the Residue Theorem. Also I know representations for the Gamma function, and facts about the theory of such function.

Question. How one can prove previous identity? I ask, can you tell us how prove rigurously that $$\int_0^1\frac{(-\log u)^s}{u^s}du=\frac{\Gamma(s+1)}{(1-s)^{s+1}}$$
  holds for $-1<\sigma<1$? Then I can encourage to ask more questions about complex analysis. Thanks in advance.

I don't know if my question is obvious from the definiton of the Gamma function, you can take this approach if such is the case, but I would like to see, if the calculations are feasibles, an answer from complex integration theory.

A: First assume that $0<s<1$.
By the change of variable $x=-\log u$, $u=e^{-x}$, $du=-e^{-x}dx$, one has
$$
\int_0^1\frac{(-\log u)^s}{u^s}du=\int_0^\infty x^s e^{-(1-s)x}dx=\frac1{(1-s)^{s+1}}\int_0^\infty v^s e^{-v}dv
$$ the latter integral is a standard integral representation of the Euler gamma function, we have thus obtained
$$
\int_0^1\frac{(-\log u)^s}{u^s}du=\frac1{(1-s)^{s+1}}\Gamma(s+1), \quad 0<s<1. \tag1
$$ Since, for $0<u<1$, the integrand $(0,1) \ni s \mapsto \frac{(-\log u)^s}{u^s}$ is holomorphic, since $u \mapsto \frac{(-\log u)^s}{u^s}$ is continuous over $(0,1)$, then the left hand side of $(1)$ is a holomorphic function over $(0,1)$  (holomorphic parameter integral) and one may extend $(1)$ by analytic continuation to $-1<\Re s<1$.


text:
Q: Unity3D: Adding Sphere Collider to Cloth Component at Runtime Isn't Doing Anything I'm trying to have it so that the player walks through a cloth curtain.
There's a sphere collider attached to my first person camera, and a cloth script attached to a prim plane. I'm trying to attach the FPS cam collider to the cloth object at runtime.
I wrote a script that seems like it should work, but it doesn't. No errors or nothing. The script compiles and works, but the sphere collider just doesn't connect to the cloth component. what gives?
    public class ClothTest : MonoBehaviour {

          private void Start() {

    Cloth a = GetComponent<Cloth>();

    var ClothColliders = new ClothSphereColliderPair[1];
    ClothColliders[0] = new ClothSphereColliderPair(GameObject.Find("First Person Camera").GetComponent<SphereCollider>());

    ClothColliders[0] = a.sphereColliders[0];

}

Here is a screenshot of the cloth component in the inspector:

A: You are trying to put the SphereCollider from your camera to your Cloth but
ClothColliders[0] = a.sphereColliders[0];

is doing the opposite. It is trying to put the  SphereCollider from your Cloth to the one in your camera. Change that around and also remove the [0] from each side.
That last line of code should be:
a.sphereColliders = ClothColliders;

The complete new function:
void Start()
{
    Cloth a = GetComponent<Cloth>();
    var ClothColliders = new ClothSphereColliderPair[1];
    ClothColliders[0] = new ClothSphereColliderPair(GameObject.Find("First Person Camera").GetComponent<SphereCollider>());

    a.sphereColliders = ClothColliders;
}